<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ruchika Shukla on Medium]]></title>
        <description><![CDATA[Stories by Ruchika Shukla on Medium]]></description>
        <link>https://medium.com/@ruchikahshukla?source=rss-19f2637499fb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Ruchika Shukla on Medium</title>
            <link>https://medium.com/@ruchikahshukla?source=rss-19f2637499fb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 04:38:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ruchikahshukla/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[SQL Query : Reduce rows | Time Series Data]]></title>
            <link>https://medium.com/@ruchikahshukla/sql-query-reduce-rows-time-series-data-9b5397c6031e?source=rss-19f2637499fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b5397c6031e</guid>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[time-series-data]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Ruchika Shukla]]></dc:creator>
            <pubDate>Sun, 24 Aug 2025 06:25:12 GMT</pubDate>
            <atom:updated>2025-08-24T06:41:35.285Z</atom:updated>
            <content:encoded><![CDATA[<p>If you are looking to reduce the resultant rows of your SQL query for time series data, follow along!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9JhuJ7uvT611naIj" /><figcaption>Photo by <a href="https://unsplash.com/@1981digital?utm_source=medium&amp;utm_medium=referral">1981 Digital</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>When did it help me</blockquote><p>While querying about 9M time series rows via a SQL connection in Python, the botteneck was large number of rows requested at once. As a workaround to reduce the rows of the query, I squashed the time series per entity level into a single row using STRING_AGG. So:</p><p><strong><em>Multiple timestamp rows per entity → 1 row</em></strong></p><p>Example for this article:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*qEJtkTrfLifzWJ0OjrbvSQ.png" /><figcaption>Sample Data — Food Consumption (Entity = Person_name + metric)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mp02S8kIlDe_ZuTSk__1gQ.png" /><figcaption>Squashed Time Series and Values</figcaption></figure><p>Well, it doesn’t make a difference in the above dummy example but it reduces the number of rows from the query results drastically when metric + person_name are fixed (N) but time series keeps on increasing across many years with frequent updates.</p><blockquote>How to?</blockquote><p>Before the very simple implementation, let’s clarify DB logistics.</p><p>DB I am using = Duck DB <br>Function Name = STRING_AGG<br>Concept you need to know=Aggregation (yes, the count, sum one)</p><p><em>Introduction</em>:<br>We use group by columns just like in SUM, COUNT, etc. Instead of collapsing into one value, it collapses into a single cell sure but as a list with a separator of your choice.</p><p><em>What we supply</em>: <br>GROUP BY Columns, Column to be turned to list (STRING DATATYPE), OPTIONAL: Separator, ORDER BY Column for the list ordering.</p><p><em>Implementation</em>:</p><p>Sample query will look like</p><pre>SELECT &lt;GROUP BY COLUMN&gt;, <br>STRING_AGG(&lt;COLUMN I WANT AS LIST&gt; &#39;,&#39; ORDER BY &lt;ORDERING COLUMN&gt;) AS REQD_LIST<br><br>FROM TABLE<br>GROUP BY &lt;GROUP BY COLUMN&gt;</pre><p>In our case:</p><pre>select metric, person_name,<br>STRING_AGG(value::STRING, &#39;,&#39; ORDER BY tracking_start_date::text ASC) as values_list,<br>STRING_AGG(tracking_start_date::text, &#39;,&#39; ORDER BY tracking_start_date::text ASC) as start_date_list,<br>STRING_AGG(tracking_end_date::text, &#39;,&#39; ORDER BY tracking_start_date::text ASC) as end_date_list,<br><br>from Food_Consumption<br>group by metric, person_name</pre><blockquote>Name of function as per your DB</blockquote><pre>╔═══════════╦════════════════════╦═════════════════════════════════════════════════════════════════════════════════════════════════════╗                                                <br>║   DB      ║       Function     ║  Documentation                                                                                      ║       <br>╠═══════════╬════════════════════╬═════════════════════════════════════════════════════════════════════════════════════════════════════╣<br>║ Postgres  ║ LISTAGG()          ║ https://www.postgresql.org/docs/9.0/functions-aggregate.html             <br>║ MySQL     ║ GROUP_CONCAT()     ║ https://dev.mysql.com/doc/refman/8.4/en/aggregate-functions.html#function_group-concat              ║<br>║ MS SQL    ║ STRING_AGG()       ║ https://learn.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql?view=sql-server-ver17 ║<br>║ Oracle    ║ LISTAGG()          ║ https://docs.oracle.com/cd/E11882_01/server.112/e41084/functions089.htm                         <br>╚═══════════╩════════════════════╩═════════════════════════════════════════════════════════════════════════════════════════════════════╝</pre><blockquote>References</blockquote><ol><li><a href="https://www.postgresql.org/docs/9.0/functions-aggregate.html">https://www.postgresql.org/docs/9.0/functions-aggregate.html</a></li><li><a href="https://dev.mysql.com/doc/refman/8.4/en/aggregate-functions.html#function_group-concat">https://dev.mysql.com/doc/refman/8.4/en/aggregate-functions.html#function_group-concat</a></li><li><a href="https://learn.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql?view=sql-server-ver17">https://learn.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql?view=sql-server-ver17</a></li><li><a href="https://docs.oracle.com/cd/E11882_01/server.112/e41084/functions089.htm">https://docs.oracle.com/cd/E11882_01/server.112/e41084/functions089.htm</a></li><li><a href="https://medium.com/@mesirii/5-tips-for-embedding-tables-in-your-medium-posts-8722f3fc5bf5">https://medium.com/@mesirii/5-tips-for-embedding-tables-in-your-medium-posts-8722f3fc5bf5</a> (TABLE FORMAT COPIED)</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b5397c6031e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Early Signs of Laptop Crash: Grafana Dashboard]]></title>
            <link>https://medium.com/@ruchikahshukla/early-signs-of-laptop-crash-grafana-dashboard-a86c7eed2d45?source=rss-19f2637499fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/a86c7eed2d45</guid>
            <category><![CDATA[prometheus]]></category>
            <category><![CDATA[grafana]]></category>
            <category><![CDATA[promql]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[grafana-prometheus]]></category>
            <dc:creator><![CDATA[Ruchika Shukla]]></dc:creator>
            <pubDate>Fri, 13 Jun 2025 02:08:36 GMT</pubDate>
            <atom:updated>2025-06-13T02:08:36.079Z</atom:updated>
            <content:encoded><![CDATA[<p>Get started with Grafana and Alert integration using a simple use case and implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BJlbP6e-_8FxjEdDQvXdwA.png" /></figure><blockquote>Installation:</blockquote><p>Follow below videos to install Prometheus, Grafana, and window_exporter as a service from <a href="https://www.youtube.com/@hakehardware">Hake Hardware</a>. <br>1. Prometheus: <a href="https://youtu.be/7V-Ao0OP908?feature=shared">https://youtu.be/7V-Ao0OP908?feature=shared</a><br>2. Grafana: <a href="https://youtu.be/3v4OwEm-zeA?feature=shared">https://youtu.be/3v4OwEm-zeA?feature=shared</a><br>3. Windows Exporter: <a href="https://youtu.be/GHkVoiABiDU?feature=shared">https://youtu.be/GHkVoiABiDU?feature=shared</a><br>4. Save config.yaml in C:\Program Files\windows_exporter as below:</p><pre>---<br># Note this is not an exhaustive list of all configuration values<br>collectors:<br>  enabled: cpu,cs,logical_disk,net,os,service,system,process,memory<br>collector:<br>  service:<br>    include: &quot;windows_exporter&quot;<br>  scheduled_task:<br>    include: /Microsoft/.+<br>log:<br>  level: debug<br>scrape:<br>  timeout-margin: 0.5<br>telemetry:<br>  path: /metrics<br>  max-requests: 5<br>web:<br>  listen-address: &quot;:9182&quot;</pre><blockquote>What do above services do?</blockquote><p>1. Prometheus: Scrapes the metrics from window exporter periodically.<br>2. Grafana: Dashboarding tool, very resourceful for time series analytics and tracking.<br>3. Windows Exporter: Provides metrics of your system to Prometheus and then Grafana.</p><p>Dataflow is from <strong>Windows Exporter → Prometheus → Grafana</strong></p><blockquote>Steps:</blockquote><p>1. Add a new dashboard. <br>2. Add a new panel and play around with type of visualization suitable for your use-case. <br>3. Add a query in PromQL for your metric. Try exploring metrics by typing in your required terms or from the Prometheus datasource.</p><blockquote>Early Laptop Crash Signs:</blockquote><p>To alert a user before a crash occurs, we evaluate the causes:<br>1. Overheating<br>2. High RAM Usage<br>3. High CPU Usage<br>4. Overflow to SSD (Correlated with High RAM Usage, when requests are being pushed to SSD because RAM can’t handle)<br>5. Not shutting down or restarting laptop.</p><p>My laptop doesn’t expose the heat sensor and hence, I will not be considering overheating in the evaluation.</p><p>Altogether, we define a naive linear model for crash score with hardcoded weights for above cases. Based on the value of this Crash Risk Score, we alert the user to take an action.</p><blockquote>PromQL Need-to-knows:</blockquote><ol><li>irate: We use it for getting per second rate of increase. (only previous 2 data points considered).</li><li>filtering: Say you have a metric-windows_cpu_time_total. Like normal tabular data it can have multiple other columns/features. If you want to filter, the syntax is like windows_cpu_time_total{<strong><em>mode= “user”</em></strong>}. Mode is a feature here.</li><li>[time]: How many datapoints to include in calculation? The ones from last 1 minute? The last 30 seconds? If I write:<br> irate(windows_cpu_time_total{mode=”idle”}[1m])), I am considering the metric values in last 1 minute in the query.</li><li>by: This is similar to group by or aggregation level, again mention a level like per core, per process? (irate(windows_cpu_time_total{mode=”idle”}[1m])) will just get all core values. But, avg by(instance)<br> (irate(windows_cpu_time_total{mode=”idle”}[1m])) will average the idle rate to give us per CPU rate.</li><li>Division: a/b generally works. But the problem happens when numerator and denominator have different kind of group by(s). In this case we need to use ignoring, group_left, group_right, and on. <br>Consider we have a PromQL like:<br>numerator = sum by (instance, process) (some irate)<br>denominator = sum by (instance) (some irate)<br>I want to divide all time series for each process by the denominator values which are again a time series. So, I group the numerator (left hand side of “/”) and take what is common from both group by(s) — instance. <br>Syntax for division becomes: (Alternatively we can also use ignoring (process))</li></ol><pre>(numerator)<br>/<br>on(instance) group_left()<br>(denominator)</pre><blockquote>Metrics and Danger Thresholds</blockquote><ol><li>CPU Usage</li></ol><p><strong>Threshold</strong>: &gt; 50 → warning zone; &gt; 65 → danger zone.<strong><br>Query</strong>: There are several modes at which CPU operates. “Idle” meaning not being utilized or being free. We just need to complement of “Idle” time, which is our CPU Usage. Note that avg below is used to get per core rate, for the CPU as a whole.</p><pre>(1 - avg by(instance) (irate(windows_cpu_time_total{mode=&quot;idle&quot;}[1m]))) * 100</pre><p>2. CPU Hoarders<br> <br><strong>Threshold</strong>: We don’t consider this in our final score so no threshold necessary. Can be applied for visual alert.<br><strong>Query</strong>: We are finding the culprit if in any case CPU Usage is high. I have hardcoded my most used apps below; “?i” is regex for making match case independent. The reason we divide with count of instances is to account for % of <strong>total </strong>CPU usage which is per core, considering all threads of a process. We can’t use avg here because that will result in only these limited processes being considered then, also resulting in &gt;100 numbers :)</p><pre>topk(<br>  5,<br>  100 *<br>  sum by(instance, process)(<br>    irate(windows_process_cpu_time_total{<br>      process=~&quot;(?i)chrome|winword|excel|python|spotify|msedge|acrobat|linkedin|pinterest|notepad&quot;<br>    }[1m]))<br>  /<br>  on(instance) group_left()<br>  count by(instance)(windows_cpu_time_total{mode=&quot;idle&quot;})<br>)</pre><p>3. RAM Usage</p><p><strong>Threshold</strong>: &gt; 85 → danger zone<br><strong>Query</strong>: We are just complementing free RAM %.</p><pre>(1 - (windows_os_physical_memory_free_bytes/windows_cs_physical_memory_bytes))*100</pre><p>4. RAM pushing requests to SSD</p><p><strong>Threshold</strong>: &gt; 10 operations/second → danger zone<br><strong>Query</strong>: windows_memory_swap_page_writes_total captures it all.</p><pre>irate(windows_memory_swap_page_writes_total[1m])</pre><p>5. SSD Latency per read</p><p><strong>Threshold</strong>: &gt; 10 ms → danger zone<br><strong>Query</strong>: As the name suggests — SSD Latency divided by total SSD reads.</p><pre>(irate(windows_logical_disk_read_latency_seconds_total{volume=&quot;C:&quot;}[1m])/irate(windows_logical_disk_reads_total{volume=&quot;C:&quot;}[1m]))*1000</pre><p>6. Uptime (in hours)</p><p><strong>Threshold</strong>: &gt; 48 hours (2 days) → danger zone<br><strong>Query</strong>: Subtract windows_system_boot_time_timestamp from current timestamp and divide by 60*60 to give uptime hours.</p><pre>(time() - windows_system_boot_time_timestamp)/(60*60)</pre><p>Putting it altogether in our <strong>Crash Risk Score</strong>:</p><pre>(<br>  ((1 - avg by(instance) (irate(windows_cpu_time_total{mode=&quot;idle&quot;}[1m]))) * 100 &gt; bool 50) * 0.3 + <br>  ((1 - avg by(instance) (irate(windows_cpu_time_total{mode=&quot;idle&quot;}[1m]))) * 100 &gt; bool 65) * 0.2<br>)<br>+ on(instance) (<br>  (((irate(windows_logical_disk_read_latency_seconds_total{volume=&quot;C:&quot;}[1m])/irate(windows_logical_disk_reads_total{volume=&quot;C:&quot;}[1m]))*1000)&gt; bool 20) * 0.15<br>)<br>+ on(instance) (<br>  (irate(windows_memory_swap_page_writes_total[1m]) &gt; bool 10) * 0.15<br>)<br>+ on(instance) (<br>  (((1 - (windows_os_physical_memory_free_bytes/windows_cs_physical_memory_bytes))*100)&gt; bool 85)*0.15)<br>+ on(instance) (<br>  ((time() - windows_system_boot_time_timestamp)*1.0/(60*60) &gt; bool 48) * 0.05<br>)* 100</pre><p>Add these metrics to your dashboard. Next step is to set up alerting when Crash Risk Score exceeds 0.45. 2 things are required for alerting — SMTP setup and Alert configuration.</p><blockquote>SMTP Setup for gmail</blockquote><ol><li>Go to the path where Grafana is installed. Navigate to “..\conf\”.</li><li>Create a copy of defaults.ini. and name it as grafana.ini.</li><li>In your gmail account, create an app password.</li><li>Locate [smtp] block in grafana.ini. And replace with filled info from below. You can alternatively keep other stuff commented or change it you require it for your use case.</li></ol><pre>enabled = true<br>host = smtp.gmail.com:587<br>user = &lt;your gmail id&gt;<br>password = &lt;your app password&gt;<br>skip_verify = false<br>from_address = &lt;your gmail id&gt;<br>from_name = Grafana Alerts<br>startTLS_policy = OpportunisticStartTLS</pre><p>5. Restart Grafana. Go to “Contact Points”, and create a new contact point with your above configured gmail id. Test the contact point using predefined test. If you get an error, you have not configured SMTP properly.</p><p><em>Alert configuration</em></p><ol><li>Go to your dashboard, find a “+” icon → New alert rules</li><li>Most of the details are easy to fill. We will focus on the important ones.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3iBOo7Zxw7huFzCIn_3UYg.png" /><figcaption>Paste the query of Crash Risk Score</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KY3zGfhTw1khFikkaU8R6g.png" /><figcaption>Click on Preview Alert Rule condition and test the query</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LFRvwDSaEMP114BaIv4Tjw.png" /><figcaption>Evaluation time = Query Runs’ Period, Pending period = Condition sustenance period</figcaption></figure><p>Rest, you can set up according to your requirements. By opening intensive processes, test if you actually get an email alert.</p><blockquote>Results:</blockquote><p>1. Dashboard</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JjAnPHF3QXUEle4Jf_tT6g.png" /><figcaption>Grafana Dashboard</figcaption></figure><p>2. Alert</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*zvc8LnTDJndn6oZd_9ROxA.png" /><figcaption>Alert Email on Crash Risk Score &gt; 0.45</figcaption></figure><p>If you have any questions or you face any issues, please let me know in the comments below. I just created this to learn more about Grafana and PromQL and share my learnings as well, so please feel free to point out any inconsistencies/feedback/suggestions.</p><blockquote>References</blockquote><ol><li><a href="https://stackoverflow.com/questions/63019337/how-to-divide-two-by-prometheus-queries-to-calculate-a-percentage">https://stackoverflow.com/questions/63019337/how-to-divide-two-by-prometheus-queries-to-calculate-a-percentage</a></li><li><a href="https://stackoverflow.com/questions/54290717/divide-two-metrics-in-prometheus">https://stackoverflow.com/questions/54290717/divide-two-metrics-in-prometheus</a></li><li><a href="https://stackoverflow.com/questions/58018670/how-to-divide-two-prometheus-counters">https://stackoverflow.com/questions/58018670/how-to-divide-two-prometheus-counters</a></li><li><a href="https://youtu.be/dNxc_6Etkt0?feature=shared">https://youtu.be/dNxc_6Etkt0?feature=shared</a></li><li><a href="https://youtu.be/iOzRpL0TKdI?feature=shared">https://youtu.be/iOzRpL0TKdI?feature=shared</a></li><li><a href="https://stackoverflow.com/questions/41871567/accurate-cpu-usage-with-prometheus-from-windows">https://stackoverflow.com/questions/41871567/accurate-cpu-usage-with-prometheus-from-windows</a></li><li><a href="https://grafana.com/docs/grafana/latest/alerting/configure-notifications/manage-contact-points/integrations/configure-email/">https://grafana.com/docs/grafana/latest/alerting/configure-notifications/manage-contact-points/integrations/configure-email/</a></li><li><a href="https://community.grafana.com/t/setup-smtp-with-gmail/85815">https://community.grafana.com/t/setup-smtp-with-gmail/85815</a></li><li><a href="https://youtu.be/2ttKXVn9_d0?feature=shared">https://youtu.be/2ttKXVn9_d0?feature=shared</a></li><li><a href="https://github.com/prometheus-community/windows_exporter">https://github.com/prometheus-community/windows_exporter</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a86c7eed2d45" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TransRec Explanation: RecSys for Abbott Elementary]]></title>
            <link>https://medium.com/@ruchikahshukla/transrec-explanation-recsys-for-abbott-elementary-cf249a637bab?source=rss-19f2637499fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf249a637bab</guid>
            <category><![CDATA[recommender-systems]]></category>
            <category><![CDATA[information-retrieval]]></category>
            <category><![CDATA[abbott-elementary]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <dc:creator><![CDATA[Ruchika Shukla]]></dc:creator>
            <pubDate>Tue, 13 May 2025 02:46:28 GMT</pubDate>
            <atom:updated>2025-05-13T20:27:18.802Z</atom:updated>
            <content:encoded><![CDATA[<p>Never watched Abbott Elementary? No worries, you’ll still get the technical details of this post. I wanted a pop-culture cast that felt fresh in my mind, and AE was the last show I binged (everything else is a blur 😅). So let’s get started with Janine, Ava, and the cast to understand a recommender-system trick called TransRec. We will generate music recommendations for our people of interest.</p><p><em>But what is TransRec for?</em><br>TransRec is used for sequential recommendations. So, if I have the knowledge that <strong><em>Ava</em></strong><em> </em>last listened to <em>Body by Megan Thee Stallion,</em> how do I recommend her the next track based on this knowledge? Using TransRec!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*u3WD6kuWRfnpo2ejpcyTwA.png" /><figcaption><strong>TransRec Workflow</strong></figcaption></figure><p><em>We will discuss below (in order) to understand TransRec:</em><br>1. Knowledge Graph (KG): Our dataset.<br>2. TransE: Extract relations from our dataset to form relation aware embeddings.<br>3. TransRec: Use TransE embeddings to find recommendations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1pnoXkd0s9RIyXHz" /><figcaption>Photo by <a href="https://unsplash.com/@nataliedivine?utm_source=medium&amp;utm_medium=referral">Natalie Cardona</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Knowledge Graph</h3><p>A Knowledge Graph (KG) , in simple words — models entities and the relations between them. In our case, we keep it simple with entities like <em>Album, Artist, Song, User,</em> and relations linking user → song as <em>listened</em>, song → album as <em>song-album</em>, and artist → album as <em>artist-album</em>. A KG is much more extensive than this, with various intertwined relations, more nuanced entities like genres, emotion tags, award nominations, etc., and it is ever-growing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WhTpIDik11XPm5cNJD2tzQ.jpeg" /></figure><p>From above, we can guess the user profiles overall:</p><ol><li><em>Ava</em>: Should scream confidence or should be TikTok viral.</li><li><em>Barbara</em>: Only Religious songs.</li><li><em>Gregory</em>: Not too loud, should be calming/mellow/low on energy.</li><li><em>Janine</em>: Unreal optimism, prevent failure in any case.</li></ol><h3>TransE Embeddings</h3><p>TransRec needs 2 types of embeddings to work with— Song Listened to, and User listening. In the original TransRec model, user and item embeddings are <strong>learned directly</strong> from interaction sequences. However, one can extend the idea by plugging in pre-trained embeddings. This article focuses on a high-level intuition. So, we are plugging in the TransE embeddings.</p><p>Note: TransE idea is very similar to TransRec.</p><p>As this article is mainly focused on TransRec — we will not go into minute details of TransE.</p><p><strong>TransE working(high-level):</strong></p><ol><li>Start with a KG (it has no sequence information).</li><li>List every triple (head, relation, tail) from the KG → (h, r, t).</li><li>Randomly intialize entity and relation vectors.</li><li>For each triple, compute h + r → compare to t. Calculate loss.*</li><li>Update embeddings. Repeat until convergence/max iterations.</li></ol><p>For detailed algorithm — refer to the original paper. (Link is in references)</p><p>*- We are modelling relations here. For example, Janine + listened ≈ High Hopes.</p><h3>TransRec Recommendations</h3><p>Adding on to the idea from above <em>Janine + listened ≈ High Hopes,</em><strong><em> </em></strong>we expand on the foundational idea for TransRec. In TransRec, we have 3 major components:</p><ul><li>Users</li><li>Items</li><li>Last Listened Song</li></ul><p>Goal: Find <strong><em>next item</em></strong><em> </em>to recommend to the user, given user listened to a particular song.</p><p>How it’s done: User Vector + Item Vector ≈ <em>Next Item</em>. Generally, we don’t have an embedding which matches the <em>Next Item</em>, so we find distances from all Items, and select the one with the lowest distance. As per design choice, if we were to recommend “k” items, we choose k items having lowest distance from the <em>Next Item</em> embedding.</p><blockquote><strong>TransRec in action</strong></blockquote><p><strong>Ava + last listened track: Body</strong><br><em>Ava Embedding</em><br>[ 0.03006757, 0.10690169, … -0.13468632]</p><p><em>Body Embedding</em><br>[ 0.01529577, 0.09548829, … -0.18420848]</p><p><em>Next Item = Ava Embedding + Body Embedding</em><br>[ 0.04536334, 0.20238998, … -0.3188948 ]</p><p>For songs not listened by Ava yet, calculate Euclidean distance between Next Item and Un-listened Items.</p><p><em>Best Match:</em></p><blockquote>Girls in the Hood (distance = 1.2 from Next Item)</blockquote><p>We can similarly calculate for other User + Item combinations. Let’s check other recommendations below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*3gqogM0dAJPnIj4thhf4yg.png" /></figure><p>We missed Melissa &amp; Jacob, but they are searching for Sweet Cheeks🐹</p><h3>References</h3><ol><li>Main credit to my IR professor — all of my understanding comes from his class.</li><li>TransE paper: <a href="https://proceedings.neurips.cc/paper_files/paper/2013/file/1cecc7a77928ca8133fa24680a88d2f9-Paper.pdf">https://proceedings.neurips.cc/paper_files/paper/2013/file/1cecc7a77928ca8133fa24680a88d2f9-Paper.pdf</a></li><li>TransRec paper: <a href="https://dl.acm.org/doi/10.1145/3109859.3109882">https://dl.acm.org/doi/10.1145/3109859.3109882</a></li><li>Music KG Inspiration: <a href="https://graphaware.com/blog/building-and-exploring-music-knowledge-graph/">https://graphaware.com/blog/building-and-exploring-music-knowledge-graph/</a></li><li>ChatGPT o3 for all character pictures.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf249a637bab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Network Visualization in Python using networkx]]></title>
            <link>https://medium.com/@ruchikahshukla/network-visualization-in-python-using-networkx-8d3dd8657f68?source=rss-19f2637499fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d3dd8657f68</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[networkx]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[network-analysis]]></category>
            <dc:creator><![CDATA[Ruchika Shukla]]></dc:creator>
            <pubDate>Thu, 17 Apr 2025 22:01:01 GMT</pubDate>
            <atom:updated>2025-04-18T05:03:02.080Z</atom:updated>
            <content:encoded><![CDATA[<p>The below writeup goes through basic components of a graph, basic types of graph, and ways to visualize them in python using networkx.</p><h3><strong>Installation</strong></h3><ul><li>For jupyter/colab(.ipnyb) environment:</li></ul><pre># for .ipnyb environment <br>!pip install networkx <br>import networkx as nx</pre><ul><li>From console/terminal</li></ul><pre>pip/conda install networkx</pre><h3><strong>Basics</strong></h3><p>Below components of the graph are important to understand before using <strong>networkx</strong>. Let’s understand this with an example of flights and airports.</p><ul><li><strong>Nodes:</strong> Airports would be nodes or centres from/to where flights are leaving or arriving. Like IAH, JFK, ATL, DFW, etc.</li><li><strong>Edges:</strong> These represent the connections between the airports which are the flights in this case. These could be by all different flight operators like Turkish Airlines, Qatar, Lufthansa, etc.</li><li><strong>Weights:</strong> It is an attribute of the edge. We can choose this to be anything which defines the edge like duration of the flight or the frequency of the flight.</li><li><strong>Directions:</strong> This is simple — it just represents incoming or outgoing. So a flight from IAH to JFK would be incoming for JFK, and outgoing for IAH. (So IAH -&gt; JFK)</li></ul><p>Now based on these components, we will discuss:</p><ul><li><strong>Directed Graph:</strong> Directions hold significance.</li><li><strong>Undirected Graph: </strong>Directions don’t hold significance. Hence, they are dropped.</li><li><strong>Unweighted Graph: </strong>There are no attributes for an edge — only directions matter. Hence, weights are dropped.</li></ul><p>We will learn to implement these 3 graphs with networkx.</p><p>Example: Let’s consider we have 3 flights.</p><ol><li>JFK to IAH, Frequency = 3</li><li>BUF TO JFK, Frequency = 5</li><li>ORD to IAH, Frequency = 8</li></ol><blockquote><strong>Undirected graph with weights</strong></blockquote><p><strong>Data required: </strong>Nodes, Edges, Weights <br><strong>Order of Nodes: </strong>Doesn’t matter<br><strong>Steps:</strong><br>1. Collect required data and initialize the graph. <br>2. We have two options to set edges — either we set nodes first and then edges OR directly set edges. We follow the latter. <br>3. Setting the edges — we need list of tuples with the weight of the link between them. <br>For our example, JFK to IAH will be written as (JFK, IAH). The complete list that we require will be [(JFK, IAH), (BUF, JFK), (ORD, IAH)]. The order of individual tuples can also be reversed here as this is an undirected graph and only links matter, not the order. So,</p><p>[(JFK, IAH), (BUF, JFK), (ORD, IAH)] <em>is same as</em> [(IAH, JFK), (JFK, BUF), ( IAH, ORD)].</p><pre>import networkx as nx<br>#step 1<br>G = nx.Graph()<br>#step 2,3<br>edges = [(&quot;JFK&quot;, &quot;IAH&quot;, 3), (&quot;BUF&quot;, &quot;JFK&quot;, 5), (&quot;ORD&quot;, &quot;IAH&quot;, 8)]<br>G.add_weighted_edges_from(edges)<br>#print edges<br>G.edges()</pre><blockquote><strong>Directed graph with weights</strong></blockquote><p><strong>Data required :</strong> Nodes, Edges, Weights <br><strong>Order of Nodes:</strong> Does matter<br><strong>Steps: </strong>Step 1 will change to initialise a directed graph. Rest all steps remain same.</p><pre>#step 1<br>G = nx.DiGraph() #the only difference compared to undirected graph <br>#step 2,3<br>edges = [(&quot;JFK&quot;, &quot;IAH&quot;, 3), (&quot;BUF&quot;, &quot;JFK&quot;, 5), (&quot;ORD&quot;, &quot;IAH&quot;, 8)]<br>G.add_weighted_edges_from(edges)<br>#print edges<br>G.edges()</pre><blockquote><strong>Unweighted graph</strong></blockquote><p>Data required — Nodes, Edges<br>Order of Nodes — Depends</p><p>Steps: Steps are similar to above 2 sections but we don’t assign a weight this time anywhere.</p><pre>#directed <br>U = nx.Graph() <br>edges = [(&quot;JFK&quot;, &quot;IAH&quot;), (&quot;BUF&quot;, &quot;JFK&quot;), (&quot;ORD&quot;, &quot;IAH&quot;)]<br>U.add_edges_from(edges)<br>print(&quot;Undirected unweighted graph: {0}&quot;.format(U.edges))<br><br>#undirected<br>D = nx.DiGraph() <br>D.add_edges_from(edges)<br>print(&quot;Directed unweighted graph: {0}&quot;.format(D.edges))</pre><blockquote><strong>Visualizing a graph</strong></blockquote><p>There are various ways to do this, you have to do trial-error to find the most suitable position for your use-case. But, there are 2 major steps. First, to find the positions according to the layouts and then to draw the graph for the positions found.</p><p>Let’s try some layouts below.</p><ul><li>Circular Layout:</li></ul><pre>#circular layout<br>import matplotlib.pyplot as plt<br>#step 1<br>pos = nx.circular_layout(G)<br>#step 2<br>plt.figure(figsize = (5, 5)) #adjust plot size<br>nx.draw_networkx(G, <br>                 pos = pos, <br>                 arrows = True, <br>                 alpha = 0.5, #increase for decreasing transparency across node labels and arrows<br>                 with_labels = True, <br>                 node_size = 1000, #changes node size of all <br>                 node_color = &quot;indigo&quot;, #changes color of all nodes<br>                 font_weight = &quot;bold&quot;, #bolds the labels<br>                 font_color = &quot;white&quot;                 <br>                 )<br>#adding weights to the arrows <br>weight_dict = {edge:G.get_edge_data(edge[0], edge[1])[&quot;weight&quot;] for edge in list(G.edges)}<br>nx.draw_networkx_edge_labels(G, <br>                             pos = pos, <br>                             edge_labels = weight_dict , <br>                             label_pos = 0.2, #adjust this parameter to avoid overlapping of labels, this describes the position. <br>                                            #default is centre of the arrow<br>                             rotate=True)<br>plt.title(&quot;Directed Graph - Example Visualization (Circular Layout)&quot;)<br>plt.show()</pre><p>Plot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*_zDqGDAcfKU-gA4RmU0qlA.png" /><figcaption>circular layout for directed graph example</figcaption></figure><ul><li>Spring Layout</li></ul><pre>#step 1<br>pos = nx.spring_layout(G)<br>plt.figure(figsize = (5, 5)) #adjust plot size<br><br>#step 2 <br>nx.draw_networkx(G, <br>                 pos = pos, <br>                 arrows = True, <br>                 alpha = 0.5, #increase for decreasing transparency across node labels and arrows<br>                 with_labels = True, <br>                 node_size = 1000, #changes node size of all <br>                 node_color = &quot;indigo&quot;, #changes color of all nodes<br>                 font_weight = &quot;bold&quot;, #bolds the labels<br>                 font_color = &quot;white&quot;                 <br>                 )<br><br>#adding weights to the arrows <br>weight_dict = {edge:G.get_edge_data(edge[0], edge[1])[&quot;weight&quot;] for edge in list(G.edges)}<br>nx.draw_networkx_edge_labels(G, <br>                             pos = pos, <br>                             edge_labels = weight_dict , <br>                             label_pos = 0.2, #adjust this parameter to avoid overlapping of labels, this describes the position. <br>                                            #default is centre of the arrow<br>                             rotate=True)<br>plt.title(&quot;Directed Graph - Example Visualization (Spring Layout)&quot;)<br>plt.show()</pre><p>Plot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*IEfuhtK9vftrX3VIAe0Bdg.png" /><figcaption>spring layout for directed graph example</figcaption></figure><ul><li>Kamada Kawai Layout</li></ul><pre>pos = nx.kamada_kawai_layout(G) #note - this takes A LOT of time for large graphs<br>plt.figure(figsize = (5, 5)) #adjust plot size<br>nx.draw_networkx(G, <br>                 pos = pos, <br>                 arrows = True, <br>                 alpha = 0.5, #increase for decreasing transparency across node labels and arrows<br>                 with_labels = True, <br>                 node_size = 1000, #changes node size of all <br>                 node_color = &quot;indigo&quot;, #changes color of all nodes<br>                 font_weight = &quot;bold&quot;, #bolds the labels<br>                 font_color = &quot;white&quot;                 <br>                 )<br><br>#adding weights to the arrows <br>weight_dict = {edge:G.get_edge_data(edge[0], edge[1])[&quot;weight&quot;] for edge in list(G.edges)}<br>nx.draw_networkx_edge_labels(G, <br>                             pos = pos, <br>                             edge_labels = weight_dict , <br>                             label_pos = 0.2, #adjust this parameter to avoid overlapping of labels, this describes the position. <br>                                            #default is centre of the arrow<br>                             rotate=True)<br>plt.title(&quot;Directed Graph - Example Visualization (Kamada Kawai Layout)&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*AsX243fEC-GrJpnXiCW71g.png" /><figcaption>kamada kawai layout for directed graph example</figcaption></figure><p>You can find other layouts from the networkx official documentation — <a href="https://networkx.org/">https://networkx.org</a>/.</p><h3><strong>An approach for dealing with large graphs</strong></h3><p>Please note that what you want to do with the visualization depends A LOT on your objective of the analysis. Let’s consider our objective is to find the “most connected airports”. Here — the “number of edges” connected to each node becomes our metric of interest. Once you have identified your metric of interest, follow below steps:</p><ul><li>Calculate metric of interest for all nodes</li><li>Label only top “n” nodes based on metric of interest values</li><li>Display the “n” nodes’ proportional to metric of interest values</li><li>Color only the top “n” nodes based on metric of interest values</li></ul><p><em>(Please note that R in the code below is a graph made from dummy data generated from combinations of all US airports)</em></p><pre>#visualizing the graph <br>import numpy as np<br><br>#if node weight is 0, it means that it is not connected to the graph, so let&#39;s obtain the largest sub graph which is actually connected <br>connected_nodes = max(nx.connected_components(R), key=len)<br><br>#make new graph<br>Rnew = nx.subgraph(R, connected_nodes)<br>Rnew_nodes = list(Rnew.nodes())<br><br>#define n <br>n = 5 # adjust n as per your needs <br><br>size_dict = {} #here we will append our node sizes <br>colors = [] #all colors for all of our nodes<br>labels = {} #to add our labels per node <br>node_sizes = []<br><br>for nodes in Rnew_nodes:<br>  sum = 0 #init sum for each ndoe<br>  #iterate over each edge <br>  #get degree<br>  size_dict[nodes] = dict(Rnew.degree()).get(nodes)<br>    <br>  node_sizes.append(dict(Rnew.degree()).get(nodes))<br><br>#get all top n node-size combinations<br>topn_items = {k: v for k, v in sorted(size_dict.items(), reverse = True,  key=lambda item: item[1])[:n]} <br><br>#top n nodes<br>topn_nodes = list(topn_items.keys())<br><br>#making the label and color dict <br>for nodes in list(Rnew.nodes()):<br>    if nodes not in topn_nodes:<br>        <br>        colors.append(&quot;lightgray&quot;)<br>        <br>    else:<br>        colors.append(&quot;lightskyblue&quot;) #add color of your choice <br>        #only labels fro topn ndoes <br>        labels[nodes] = nodes<br>plt.figure(figsize = (25, 20)) #adjust size to your liking<br>pos = nx.spring_layout(Rnew)<br>nx.draw_networkx(Rnew, <br>                pos = pos,<br>                alpha = 0.65,<br>                node_size = np.array(node_sizes, dtype = np.float64)*80,<br>                font_size = 15,<br>                with_labels = True,<br>                labels = labels,<br>                node_color = np.array(colors),<br>                arrows = True, <br>                font_weight = &quot;bold&quot;, <br>                font_color = &quot;black&quot;, <br>                edge_color = &quot;black&quot;)<br><br>#highlighting most visited edges <br>plt.title(&quot;Top {0} Nodes based on sum of all edge weights (Most Connected Airports)&quot;.format(n))<br>plt.show()</pre><p>Plot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*gNhBeYnrS0GN62SOuAYrzw.png" /><figcaption>Most connected Airports in USA</figcaption></figure><p>From the above plot, we can infer that according to the <strong>dummy data</strong> — BHM, RIC, GPT, ILM, OKC are the airports having highest connectivity.</p><p><strong>References</strong></p><p>1.<a href="https://networkx.org/documentation/stable/reference/generated/networkx.convert.from_edgelist.html.">https://networkx.org/documentation/stable/reference/generated/networkx.convert.from_edgelist.html.</a></p><p>2. <a href="https://www.youtube.com/watch?v=flwcAf1_1RU">https://www.youtube.com/watch?v=flwcAf1_1RU</a></p><p>3. <a href="https://www.youtube.com/watch?v=ollW8lwZxNE">https://www.youtube.com/watch?v=ollW8lwZxNE</a></p><p>4. <a href="https://stackoverflow.com/questions/71574758/removing-isolated-nodes-in-order-to-make-the-graph-connected">https://stackoverflow.com/questions/71574758/removing-isolated-nodes-in-order-to-make-the-graph-connected</a></p><p>5. <a href="https://stackoverflow.com/questions/69049689/how-to-color-the-top-20-nodes-over-the-rest-of-the-nodes-in-networkx">https://stackoverflow.com/questions/69049689/how-to-color-the-top-20-nodes-over-the-rest-of-the-nodes-in-networkx</a></p><p>6. <a href="https://stackoverflow.com/questions/54590955/coloring-specific-nodes-in-networkx">https://stackoverflow.com/questions/54590955/coloring-specific-nodes-in-networkx</a></p><p>7. <a href="https://stackoverflow.com/questions/33078907/get-all-edges-linked-to-a-given-node-in-a-networkx-graph">https://stackoverflow.com/questions/33078907/get-all-edges-linked-to-a-given-node-in-a-networkx-graph</a></p><p>8. <a href="https://stackoverflow.com/questions/77732498/how-to-get-for-each-node-the-sum-of-the-edge-weights-for-children-in-a-networkx">https://stackoverflow.com/questions/77732498/how-to-get-for-each-node-the-sum-of-the-edge-weights-for-children-in-a-networkx</a></p><p>9. <a href="https://stackoverflow.com/questions/33078907/get-all-edges-linked-to-a-given-node-in-a-networkx-graph">https://stackoverflow.com/questions/33078907/get-all-edges-linked-to-a-given-node-in-a-networkx-graph</a></p><p>10. <a href="https://stackoverflow.com/questions/20183433/available-font-family-entry-for-draw-networkx-labels">https://stackoverflow.com/questions/20183433/available-font-family-entry-for-draw-networkx-labels</a></p><p>11. <a href="https://stackoverflow.com/questions/55320418/how-to-only-show-important-nodes-name-on-the-networkx-graph">https://stackoverflow.com/questions/55320418/how-to-only-show-important-nodes-name-on-the-networkx-graph</a></p><p>12. <a href="https://stackoverflow.com/questions/69637000/how-can-i-change-the-node-size-in-a-networkx-graph">https://stackoverflow.com/questions/69637000/how-can-i-change-the-node-size-in-a-networkx-graph</a></p><p>13.<a href="https://networkx.org/documentation/stable/reference/generated/networkx.drawing.layout.circular_layout.html">https://networkx.org/documentation/stable/reference/generated/networkx.drawing.layout.circular_layout.html</a></p><p>14.<a href="https://networkx.org/documentation/stable/reference/generated/networkx.drawing.nx_pylab.draw_networkx.html,">https://networkx.org/documentation/stable/reference/generated/networkx.drawing.nx_pylab.draw_networkx.html,</a></p><p>15. <a href="https://stackoverflow.com/questions/17381006/large-graph-visualization-with-python-and-networkx">https://stackoverflow.com/questions/17381006/large-graph-visualization-with-python-and-networkx</a></p><p>16. Various functions from the documentation — <a href="https://networkx.org/documentation/stable/">https://networkx.org/documentation/stable/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d3dd8657f68" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>