<?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 Sam Ho on Medium]]></title>
        <description><![CDATA[Stories by Sam Ho on Medium]]></description>
        <link>https://medium.com/@kitsamho?source=rss-c3acc81ee8bb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*QYyeNvTX70FsqKtV9Lx-1g.jpeg</url>
            <title>Stories by Sam Ho on Medium</title>
            <link>https://medium.com/@kitsamho?source=rss-c3acc81ee8bb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 18:44:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kitsamho/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[Hollywood Networks Unveiled: Actor Collaborations visualised with Streamlit, d3Blocks, and NetworkX]]></title>
            <link>https://medium.com/data-science-collective/hollywood-networks-unveiled-actor-collaborations-visualised-with-streamlit-d3blocks-and-networkx-4a4072a15347?source=rss-c3acc81ee8bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a4072a15347</guid>
            <category><![CDATA[visualization]]></category>
            <category><![CDATA[insights]]></category>
            <category><![CDATA[hollywood]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Sam Ho]]></dc:creator>
            <pubDate>Fri, 18 Apr 2025 03:03:31 GMT</pubDate>
            <atom:updated>2025-04-21T13:26:44.340Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mapping Hollywood: Actor Collaboration Networks with d3Blocks, Streamlit and NetworkX</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yuoZX1iOn1gLf-XynHdJ9Q.jpeg" /><figcaption>Source: <a href="https://petapixel.com/2012/06/23/116-hollywood-stars-in-one-group-picture/">https://petapixel.com/2012/06/23/116-hollywood-stars-in-one-group-picture/</a></figcaption></figure><h4>Introduction</h4><p>The concept of “six degrees of separation” asserts that any two people in the world can be connected through a chain of social acquaintances with no more than six degrees of separation between them. It suggests that the world is smaller than we might think and that social networks are intricately interwoven. This idea inspired the creation of “Six Degrees of Kevin Bacon”. In this game, participants challenge themselves to connect any actor to Kevin Bacon within six steps, linking them through shared film appearances.</p><p>At the core of “Six Degrees of Kevin Bacon” lies the fundamental idea of networks within Hollywood. Networks can be modeled as a graph, with actors as nodes and collaborations as edges. By leveraging graph metrics, such as degree centrality, betweenness centrality, and clustering coefficient we can uncover valuable information about the importance of individual actors, the flow of collaborations, and the presence of tightly-knit groups within a network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*Tm6WuGur9WPqwnkf7mTeNA.jpeg" /><figcaption>Source: <a href="https://oracleofbacon.org/graph.php">https://oracleofbacon.org/graph.php</a></figcaption></figure><h3>Goal</h3><p>We will leverage NetworkX, d3Blocks, and Streamlit to create an interactive application that allows users to explore the network of actor collaborations using data from <a href="https://www.themoviedb.org/">TMDB</a> (The Movie Database)</p><p>By modeling actor data as a graph, visualising it with d3Blocks, and hosting it in a Streamlit app, we aim to provide a fun experience for users to explore the connections between actors.</p><p>Link to app: <a href="https://imdb-actor.streamlit.app/">https://imdb-actor.streamlit.app/</a></p><h4>The kinds of things we want to be able to answer</h4><p><em>“Who is the most well-connected actor in Hollywood, consistently collaborating with a wide range of other actors?”</em></p><p><em>“Are there any actor pairs who frequently collaborate, appearing together in multiple movies?”</em></p><p><em>“Who are the influential connectors in Hollywood, playing a pivotal role in bridging different groups of actors within the network?”</em></p><h3>Acquiring data from TMDB</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DZLKFn2wjteCdUMu" /><figcaption>Photo by <a href="https://unsplash.com/@hishahadat?utm_source=medium&amp;utm_medium=referral">Shahadat Rahman</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>To acquire the data for this project, the following processes were carried out:</p><h4>Obtaining an API key from TMDB</h4><p>The first step involved obtaining an API key from The Movie Database (TMDB) to access their data.</p><p>You can do this <a href="https://developer.themoviedb.org/reference/intro/getting-started">here</a></p><p>It’s a great API; there are very user-friendly limits (there might even be none if I recall) and the number of endpoints is varied and intuitive to use.</p><h4>Building some classes for data querying</h4><p>Two custom classes were developed to facilitate the querying of data from TMDB. One for querying movie data in a certain time span and the second to query the actor data from those movies.</p><p>In building the data querying class, we implemented the tmdbsimple <a href="https://github.com/celiao/tmdbsimple">library</a>, which provides convenient methods for accessing TMDB API endpoints.</p><h4>Movie Payload</h4><p>The get_movie_payload() function is used to create an empty payload for the TMDBMovieScraper class. This payload is a dictionary that serves as a schema for querying data from the TMDB API. It allows customisation of the fields to be queried by defining different sections in the payload and specifying what data fields we need. If you explore the API you can customise this and query the data you need for your own projects.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/971b13f66c7c3f5d02fbe51675a02d54/href">https://medium.com/media/971b13f66c7c3f5d02fbe51675a02d54/href</a></iframe><h4>TMDBMovieScraper</h4><p>The TMDBMovieScraper class represents a movie data scraper that interacts with the TMDB API to retrieve and process movie information. The class is initialised with a list of years to iterate over for querying movie data. The main purpose of this class is to gather movie data by making API requests and transforming the results into a structured Pandas DataFrame.</p><p>The class has various helper methods that handle different aspects of the data retrieval and processing pipeline. These methods include:</p><ul><li>Checking the number of response pages to iterate over</li><li>Querying movie data using the discover API</li><li>Querying movie details using movie IDs</li><li>Transforming the obtained results into DataFrames</li><li>Performing various data cleaning and filtering operations</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1117527d1657d907f4c9959ece69b093/href">https://medium.com/media/1117527d1657d907f4c9959ece69b093/href</a></iframe><p>Example implementation..</p><p>This code snippet will query movie data for 2022 and 2023</p><pre>movies = TMDBMovieScraper(years_check=[2022,2023])<br>df_movies = movies.get_movies()</pre><p>Example output fromTMDBMovieScraper</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VxmupXkA_rL8ITgOg_FMzw.png" /><figcaption>Example output</figcaption></figure><p>The movie ids from this DataFrame are then used when instantiating the TMDBCastCrewScraper — whose purpose is to query the cast data from those movies. You can also use this to query crew data, but that was out of scope for this specific project.</p><h4>TMDBCastCrewScraper</h4><p>The TMDBCastCrewScraper class is designed to fetch cast and crew information for a list of movie IDs. Its primary goal is to query cast data from these movies, although it can also be used for querying crew data, which is not within the scope of this specific project. The class leverages multi-threading to ensure efficient data retrieval and incorporates a popularity threshold to include only actors with a certain level of popularity.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22b995c7f029ff166304efc4ba7c6cc0/href">https://medium.com/media/22b995c7f029ff166304efc4ba7c6cc0/href</a></iframe><p>Example implementation</p><pre>cast = TMDBCastCrewScraper(df_movies.index)<br>df_cast = cast.get_cast_crew()</pre><p>Example output TMDBCastCrewScraper</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zRJKxlWhxgy6xTbYC-pOBg.png" /><figcaption>Example output</figcaption></figure><h4>Data querying and persistence</h4><p>Using the built classes, data was queried from TMDB and stored in two pickled DataFrames. While this local caching approach served the purpose of the demonstration, it is important to note that for larger datasets, it would be ideal to store the data in a data warehouse for efficient querying. However, this comes with associated costs, and for this proof-of-concept, the locally cached data sufficed.</p><h3>App Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cj35Eq5rdk8ukb3wp1JhIg.png" /><figcaption>App Architecture — image by author</figcaption></figure><h4>DataLoader</h4><p>The DataLoader class (nothing to do with PyTorch!) is designed to handle the loading and processing of locally cached movie and cast data. It takes a YAML config file path as a parameter during initialisation. The class has several methods to facilitate the data-loading process.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5f2ab16cefdc4fe7f75d68c684bba13/href">https://medium.com/media/c5f2ab16cefdc4fe7f75d68c684bba13/href</a></iframe><p>Example implementation</p><pre># instantiate DataLoader object with config file path<br>loader = DataLoader(config_path=config_path)  <br>loader.load_data()  # load and join the movies and cast data<br>df_merged = loader.get_df_merged()  # get the merged dataframe</pre><h4>MovieCastTransformer</h4><p>The MovieCastTransformer class handles loaded movie and cast data and interacts with Streamlit, masking the data based on user-set parameters.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e434af4d0feb1989368ede3b796d8718/href">https://medium.com/media/e434af4d0feb1989368ede3b796d8718/href</a></iframe><p>Example Implementation</p><pre># instantiate MovieCastTransformer object<br>trf = MovieCastTransformer(df_merged)  <br># transform data<br>df_merged_transformed = trf.transform_data() </pre><h4>D3Transformer</h4><p>The D3Transformer class then facilitates the transformation of the data into a suitable format for the d3blocks network graph.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e96a7a63e1ac52eabe46757d141f800d/href">https://medium.com/media/e96a7a63e1ac52eabe46757d141f800d/href</a></iframe><p>With various private methods, the class reshapes the data to extract edge and node data points. This reshaping involves representing nodes as source and target, while edges are represented by unique combinations of source and target. The weight assigned to each edge corresponds to the frequency of the observed relationship in the data.</p><p>Example Implementation</p><pre>d3_trf = D3Transformer(df_merged_transformed)<br>df_d3 = d3_trf.transform_data()</pre><p>Example output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/1*RLbdAKTagJ86gmTpJLf27g.png" /><figcaption>Source: Image by author</figcaption></figure><h3>Tab1 — Graph Visualisation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*K_eamjwpKabuGKfe" /><figcaption>Photo by <a href="https://unsplash.com/@clintadair?utm_source=medium&amp;utm_medium=referral">Clint Adair</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>D3Blocks is an excellent Python data visualisation tool that merges D3.js’s strength with Python’s ease. We’ll use the d3graph plot for graph visualisation. To render this in the Streamlit app efficiently, we export the visualization as HTML, cache it locally, and then use Streamlit’s HTML component for rendering.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a31696b84a73a81de5891323b5cb518e/href">https://medium.com/media/a31696b84a73a81de5891323b5cb518e/href</a></iframe><h4>Example implementation</h4><pre>with tab1:<br>  <br>    st.header(&#39;Graph Visualisation&#39;)<br>    #Use cache_d3_network with the d3 DataFrame and provide a temporary file path to save the plot&#39;s HTML<br>    cache_d3_network_plot(df_d3, html_temp_file_path)<br><br>    # call load_cached_file that loads the html file<br>    cached_html = load_cached_file(html_temp_file_path)<br><br>    # render the visualisation<br>    plot_html(cached_html)</pre><h4><strong>What it looks like…</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_2sf4UEYPA7C0d-u4jSReQ.png" /><figcaption>Source: Image by author</figcaption></figure><h3>Tab 2-Graph Metrics</h3><p>The ActorGraphTransformer class is designed to transform a DataFrame into a graph representation using NetworkX and calculate various graph metrics for each actor. It provides convenient methods to access the calculated metrics in both DataFrame and dictionary formats.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82cba475737ae88b2fcf1915c7ad9b5a/href">https://medium.com/media/82cba475737ae88b2fcf1915c7ad9b5a/href</a></iframe><h4><strong>Example implementation</strong></h4><pre>graph_trf = ActorGraphTransformer(df_d3)<br>df_actor_graph_attributes = graph_trf.get_actor_graph_metrics_df()<br>graph_metrics_dict = graph_trf.get_actor_graph_metrics_dict()<br>edge_frequency_dict = graph_trf.get_edge_frequency_dict()</pre><h4>self.get_edge_frequency_dict()</h4><pre>{&#39;Bruce Willis&#39;: 134,<br> &#39;Brad Pitt&#39;: 107,<br> &#39;Bradley Cooper&#39;: 94,<br> &#39;Benedict Cumberbatch&#39;: 91,<br> &#39;Charlize Theron&#39;: 91,<br> &#39;Chris Evans&#39;: 90,<br> &#39;Channing Tatum&#39;: 87,<br> &#39;Angela Bassett&#39;: 75,<br> &#39;J.K. Simmons&#39;: 116,<br> .....</pre><h4>self.get_actor_graph_metrics_dict()</h4><pre>{&#39;John_Goodman&#39;: {&#39;DegreeCentrality&#39;: 0.21,<br>  &#39;BetweennessCentrality&#39;: 0.01,<br>  &#39;EigenvectorCentrality&#39;: 0.077,<br>  &#39;ClusteringCoefficient&#39;: 0.191},<br> &#39;Mary_Elizabeth_Winstead&#39;: {&#39;DegreeCentrality&#39;: 0.098,<br>  &#39;BetweennessCentrality&#39;: 0.002,<br>  &#39;EigenvectorCentrality&#39;: 0.035,<br>  &#39;ClusteringCoefficient&#39;: 0.206},<br> &#39;Bradley_Cooper&#39;: {&#39;DegreeCentrality&#39;: 0.227,<br>  &#39;BetweennessCentrality&#39;: 0.007,<br>  &#39;EigenvectorCentrality&#39;: 0.103,<br>  &#39;ClusteringCoefficient&#39;: 0.287},<br>  ....</pre><h4>self.get_actor_graph_metrics_df()</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AHhvY4AAayV_49HFt3w_rA.png" /></figure><h4>Understanding Graph Metrics</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*av5woS_jHF1uM7h6" /><figcaption>Photo by <a href="https://unsplash.com/@robynnexy?utm_source=medium&amp;utm_medium=referral">Robynne Hu</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><ul><li><strong>Degree Centrality</strong>: Degree centrality measures how connected an actor is by looking at the number of co-stars they have worked with. Actors with a higher degree centrality value have worked with more co-stars (someone like Samuel L. Jackson)</li><li><strong>Betweenness Centrality</strong>: Betweenness centrality quantifies the extent to which an actor acts as a bridge or intermediary between other actors in the graph. In real terms, an actor who has starred in a number of different franchises is likely to have a high betweenness centrality (again someone like Samuel L. Jackson who has been in both the MCU and in the Star Wars franchise)</li><li><strong>Eigenvector Centrality</strong>: Eigenvector centrality measures the influence of an actor based on both their direct connections and the connections of their co-stars. Actors with high eigenvector centrality are not only connected to many other actors but are also connected to other influential actors. (lol, again maybe someone like like Samuel L. Jackson)</li><li><strong>Clustering Coefficient</strong>: The clustering coefficient measures the tendency of actors to form tightly-knit groups or clusters. It quantifies how likely an actor’s co-stars are also connected to each other. Actors with high clustering coefficients are part of cohesive groups within the network. In this instance someone like Elijah Wood from the LOTR franchise would probably have a high clustering coefficient.</li></ul><h4><strong>Example Implementation</strong></h4><pre>with tab2:<br>    st.header(&#39;Graph Metrics&#39;)<br>    st_expander(&#39;Click for info&#39;, visualisation_info[&#39;graph_metrics&#39;])<br>    df_actor_graph_attributes_url = _append_actor_url_to_df_actor_attributes(df_actor_graph_attributes, \<br>                                                                             df_merged_transformed, imdb_image_path)<br>    col1, col2 = st.columns(2)<br>    options_dict = {&#39;Betweenness Centrality&#39;: &#39;BetweennessCentrality&#39;, &#39;Degree Centrality&#39;: &#39;DegreeCentrality&#39;,<br>                    &#39;Eigenvector Centrality&#39;: &#39;EigenvectorCentrality&#39;,&#39;Clustering Coefficient&#39;: &#39;ClusteringCoefficient&#39;}<br><br>    marker_size = st.slider(&#39;Adjust marker size&#39;, 1, 50, 5)<br>    x_axis = col1.selectbox(&quot;Select metric for x axis&quot;, options=sorted(list(options_dict.keys())))<br>    y_axis = col2.selectbox(&quot;Select metric for y axis&quot;, options=reversed(list(options_dict.keys())))<br><br>    plot = plot_graph_metrics(df_actor_graph_attributes_url,<br>                              options_dict[x_axis],<br>                              options_dict[y_axis],<br>                              size=marker_size)<br>    st.altair_chart(plot)</pre><h4>What it looks like</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nEfuoN8SyRtfo8oStbcgyg.png" /></figure><h3>Tab 3-Common Movies</h3><ul><li>Extracting information from the df_d3_to_plot DataFrame to generate a dictionary containing actors and their co-stars.</li><li>We then allow users to select an actor’s name from the first column and a co-star’s name from the second column</li><li>Identifying movies in which both actors have starred together by calling find_common_movies() based on the selected actor and co-star.</li><li>Enhancing the visualization by retrieving movie poster paths for these common movies from the DataFrame and imdb_image_path using get_poster_paths().</li><li>Showcasing a grid of movie posters through display_image_grid(), enabling users to explore the shared cinematic journey of the selected actors.</li></ul><h4>Example Implementation</h4><pre>with tab3:<br>    st.header(&#39;Common Movies&#39;)<br>    actor_co_star_dict = get_actor_co_star_dict(df_d3_to_plot)<br>    col1, col2 = st.columns(2)<br>    selected_actor = col1.selectbox(&quot;Select a key&quot;, options=sorted(list(actor_co_star_dict.keys())), key=&quot;actor_selectbox&quot;)<br>    selected_costar = col2.selectbox(&quot;Select a value&quot;, options=sorted(actor_co_star_dict[selected_actor]), key=&quot;costar_selectbox&quot;)<br>    common_movies = find_common_movies(df_merged_transformed, selected_actor, selected_costar)<br>    paths = get_poster_paths(df_merged_transformed, common_movies, imdb_image_path)<br>    display_image_grid(paths)</pre><h4>What it looks like..</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YgpYDwCPSYgnxJo7TYd0fQ.png" /></figure><h3>Summary</h3><p>And there we have it — a multi-page Streamlit application that enables users to explore the interconnectedness of actors in Hollywood. In this post, we have detailed:</p><ul><li>How we utilised the TMDB API to extract structured movie and cast data</li><li>Our use of a graph plot visualisation in D3blocks to depict actors and their connections</li><li>The application of NetworkX to represent actor-movie data as a graph, incorporating graph metrics such as betweenness and clustering coefficients to facilitate the analysis of actors’ relationships within the network.</li><li>A demonstration of how to consolidate all these features into a multi-tab Streamlit application designed to encourage user interaction and exploration.</li><li>App link here: <a href="https://imdb-actor.streamlit.app/">https://imdb-actor.streamlit.app/</a></li></ul><p>If you found this article informative, please feel free to clap, share, comment :)</p><p>Cheers, Sam</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a4072a15347" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science-collective/hollywood-networks-unveiled-actor-collaborations-visualised-with-streamlit-d3blocks-and-networkx-4a4072a15347">Hollywood Networks Unveiled: Actor Collaborations visualised with Streamlit, d3Blocks, and NetworkX</a> was originally published in <a href="https://medium.com/data-science-collective">Data Science Collective</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OpenAI’s CLIP in Action: Exploring the Power of Image-Text AI using Streamlit]]></title>
            <link>https://medium.com/geekculture/clip-streamlit-app-4648a677b4a8?source=rss-c3acc81ee8bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/4648a677b4a8</guid>
            <dc:creator><![CDATA[Sam Ho]]></dc:creator>
            <pubDate>Fri, 07 Apr 2023 12:39:43 GMT</pubDate>
            <atom:updated>2023-09-23T19:51:14.163Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X20rJD_JaFY2w7ke" /><figcaption>Photo by <a href="https://unsplash.com/@priscilladupreez?utm_source=medium&amp;utm_medium=referral">Priscilla Du Preez</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><a href="https://openai.com/research/clip">CLIP (Contrastive Language-Image Pretraining)</a> is a multi-modal neural network model developed by OpenAI to perform tasks that require an understanding of both images and text. I have used it extensively at Shutterstock and in my own time on personal projects, so I thought I would build an interactive Streamlit app to showcase some of the functionality I frequently lean on when using it.</p><p>TLDR — Streamlit App is here: <a href="https://clip-demo-app.streamlit.app/">https://clip-demo-app.streamlit.app/</a></p><h4>What makes CLIP different?</h4><p>The CLIP model was <a href="https://arxiv.org/pdf/2103.00020.pdf">trained using a contrastive learning approach</a>, where it was trained to differentiate between:</p><ul><li><strong>positive</strong> pairs (images and their <strong>corresponding </strong>captions)</li><li><strong>negative</strong> pairs (images and <strong>random text </strong>captions).</li></ul><p>By incorporating textual information alongside visual information, CLIP is able to learn a lot more about the context in which the images appear, leading to a far higher level of understanding of visual concepts and their related semantics.</p><p>CLIP isn’t a generative model, meaning it can’t hold a conversation with you…. or complete your homework assignments. However, it excels at a range of downstream discriminative tasks that require deep comprehension of image and text data. Subsequently, there are many use cases for the model.</p><h3>CLIP Use Cases</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kOjCKfU0dF14TWES" /><figcaption>Photo by <a href="https://unsplash.com/@imattsmart?utm_source=medium&amp;utm_medium=referral">iMattSmart</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Zero-shot Classification</h3><p>Because CLIP was trained on a diverse set of images and paired natural language descriptions, CLIP is able to generalise its understanding to new and unseen data and correctly classify both objective features but also more abstract concepts.</p><h4>Classification of objective features</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*CRYzWzVQv6n5VkxH2DeaRA.png" /><figcaption>Screenshot by author / Image in app from Unsplash</figcaption></figure><h4>Classification of abstract concepts</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*9HsQzkidMoq9VwHI9G7a5w.png" /><figcaption>Screenshot by author / Image in app from Unsplash</figcaption></figure><p>By leveraging this generalised knowledge, it is possible to build multi-modal AI systems that can adapt to a wide range of tasks without the need for a fully supervised training approach. This allows for swift experimentation and deployment.</p><h3>Clustering</h3><p>We can use CLIP’s encoder to extract text and image embeddings from any input text and/or image data source. Embeddings are mathematical representations of the input data. Amongst other things, these embeddings can be used to cluster similar items. By incorporating dimensionality reduction techniques such as UMAP, clusters can be visualised and interrogated.</p><h3>Semantic Search</h3><p>Semantic search is a search technique that aims to understand the meaning and context of words and phrases in a search query rather than just returning results that are aligned with keywords. CLIP enables a more intuitive and natural way of searching for images based on their content, one way of achieving this is by calculating the cosine similarity between input vectors (search query) and target vectors (images/other text).</p><h3>Streamlit App</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bDacQfa9QI0Gn9oF" /><figcaption>Photo by <a href="https://unsplash.com/de/@askkell?utm_source=medium&amp;utm_medium=referral">Andy Kelly</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Although CLIP is not the new kid on the block, has no user interface, and requires programming knowledge to use, its versatility is undeniable. So to showcase some of its cool features, I built a multi-page Streamlit app to encourage interaction with the CLIP model and to facilitate experimentation in real time.</p><p>Note —to keep this post concise, the focus of this walkthrough is on the Streamlit code used to build the app and only some of the core CLIP code will be covered. To fully understand the functionality and workflow of the app, I recommend exploring the GitHub repository.</p><blockquote><em>Streamlit App Here: </em><a href="https://openai-clip-utilities.streamlit.app/"><em>https://openai-clip-utilities.streamlit.app/</em></a></blockquote><blockquote><em>Github Repository here: </em><a href="https://github.com/kitsamho/clip_app"><em>https://github.com/kitsamho/clip_app</em></a></blockquote><h3>Loading the model, tokeniser, and processor</h3><p>There are a few CLIP models available to use, most of which are reasonably lightweight and available via the<a href="https://huggingface.co/docs/transformers/model_doc/clip"> transformers library</a> kindly maintained by Huggingface. This means it’s reasonably easy to implement in a Streamlit app.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8cfa84614d4930ccbdf428ac2c663592/href">https://medium.com/media/8cfa84614d4930ccbdf428ac2c663592/href</a></iframe><p>model = CLIPModel.from_pretrained(clip_model)</p><ul><li>Loads the model</li></ul><p>processor = AutoProcessor.from_pretrained(clip_model)</p><ul><li>Loads the processor for the CLIP model. This is used to preprocess images before they are fed into the model. The processor takes care of things like resizing, normalization, and cropping the images to the correct size.</li></ul><p>tokenizer = AutoTokenizer.from_pretrained(clip_model)</p><ul><li>loads the tokenizer for the CLIP model, which is used to tokenize text inputs into a format that can be understood by the model.</li></ul><p>Together, these three variables provide the necessary components for using the pre-trained CLIP model to classify images and text.</p><p><em>Note — when downloading models and other resources in Streamlit add the </em><em>st.cache_resourcedecorator in front of your function or method. This means you only ever need to download it once per session. Likewise, use </em><em>st.cache_datafor caching data sets; importing CSV or parquet files for example.</em></p><h3>Zero-Shot Image Classification — Unsplash Images</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i3vEf_KkVZGG-os7IW_nzQ.png" /></figure><ul><li>Upon initialisation, the URLs for royalty-free images are scraped from Unsplash</li><li>The app then presents a random image to the user</li><li>The user can enter two or more labels to describe the image</li><li>The app will use the CLIP model to generate a list of probabilities for each of the labels</li><li>The app loops around the same image until a user requests a new image to classify</li></ul><p>The main Streamlit functionality is provided thisimage_classification_loop function</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5e7c92992d11639c7fd7dffc0d0c3da/href">https://medium.com/media/f5e7c92992d11639c7fd7dffc0d0c3da/href</a></iframe><p>The classification functionality is handled by theclassify_images function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4aeb50f8dd066b0e25efb851d2408575/href">https://medium.com/media/4aeb50f8dd066b0e25efb851d2408575/href</a></iframe><p>The function performs the following steps:</p><ol><li>It calls the calculate_text_features function usingtext_inputs, tokeniser, and model as arguments. This function extracts text embeddings from the text inputs using the CLIP tokeniser and encoder.</li><li>It then calls the calculate_image_features function usingimages, processor, and model as arguments. The images here are a list of image URL’s. This function extracts embeddings from the images using the CLIP model.</li><li>Finally the _calculate_similarity function is called using the text and image features as arguments. This function calculates the similarity between the two sets of embeddings. There is asoftmax function used here to create a probability distribution over all possible output classes. This distribution can then be used to select the most likely class label.</li></ol><h3>Zero-Shot Text Classification — BBC Headlines</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9o9ISQsOA_iZlTYew0tTQQ.png" /></figure><ul><li>Upon initialisation, some current headlines are scraped from <a href="https://www.bbc.co.uk/news">https://www.bbc.co.uk/news</a></li><li>The app then presents a random headline to the user</li><li>The user can enter two or more labels to describe the headline</li><li>The app will use the CLIP model to generate a list of probabilities for each of the labels</li><li>The app loops around the same headline until a user requests a new image to classify</li></ul><p>The main Streamlit functionality is provided this text_classification_loop function</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8bfaa6068a7bd58d78bf920643b749c/href">https://medium.com/media/e8bfaa6068a7bd58d78bf920643b749c/href</a></iframe><h3>Image Clustering — Rock Archive Images Dataset</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MBwxamdaLXrtVKeQeDnsOw.png" /></figure><ul><li>Upon initialisation, pre-computed embeddings for c.1500 images from Rock Archive are loaded. Calculating CLIP embeddings on the fly would be slow so these are cached locally in the repository as a pickled dataframe.</li><li>Users can input a URL to an image (e.g. their LinkedIn photo…. or any link that links directly to an image for that matter)</li><li>The app uses CLIP to generate image embeddings for this user-inputted image</li><li>Pre-computed rock archive images are concatenated with this new user embedding</li><li>The UMAP algorithm is used for dimensionality reduction across the concatenated embedding space</li><li>The resulting markers/clusters are displayed as a scatter plot</li><li>Each marker in the scatter plot represents an image where similar images are grouped together</li></ul><p>The main Streamlit functionality for this is provided by theimage_clustering_loop function</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/006afd5c2699ab86c783fd20f5d7c865/href">https://medium.com/media/006afd5c2699ab86c783fd20f5d7c865/href</a></iframe><h3>Text Clustering — Conceptual Caption Dataset</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QYkdQNiIeY5E57Ug1naTdw.png" /></figure><ul><li>The application loads pre-computed embeddings for approximately 1500 images from the Conceptual Captions dataset during initialization</li><li>These embeddings are labeled as one of seven domains: property, sports, food, musicians, vehicles, illustration, and nature</li><li>Users are then prompted to input text related to one of these domains</li><li>The application uses CLIP to generate image embeddings for the user’s text input and concatenates them with the pre-computed conceptual caption embeddings</li><li>The concatenated embeddings are then reduced to two dimensions using the UMAP algorithm</li><li>The resulting markers and clusters are displayed as a scatter plot, where each marker represents a text string and similar texts are grouped together</li></ul><p>The main Streamlit functionality for this is provided by thetext_clustering_loop function</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/30599a5faeda5ed78af28829bce3a4eb/href">https://medium.com/media/30599a5faeda5ed78af28829bce3a4eb/href</a></iframe><h3>Semantic Search — Rock Archive Images Dataset</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_cawXCNIaH4ftRpg3GecfA.png" /></figure><ul><li>As above, pre-computed embeddings for c.1500 images from Rock Archive are loaded</li><li>The app allows the user to input a natural language query</li><li>CLIP is used to encode both the images and the natural language queries into embeddings, which share the same space</li><li>The cosine similarity between input and target vectors are computed and the scores are ranked and the top 10 most similar images are shown on the app</li><li>Note — there are only 1500 images here so any very obscure searches may yield poor results</li></ul><p>The main Streamlit functionality for this is provided by thesemantic_search_loop function</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2814426d4177a145d96a78dfe495cbd/href">https://medium.com/media/c2814426d4177a145d96a78dfe495cbd/href</a></iframe><p>With this ranking approach, the cosine similarity between input and source vectors was implemented — this is used in rank_vectors</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d341fd126e9e9e861b988c526379f9c/href">https://medium.com/media/8d341fd126e9e9e861b988c526379f9c/href</a></iframe><h3>Summary</h3><p>In this post, I highlighted several useful applications CLIP has when addressing multi-modal data challenges. This was brought to life with a multi-page Streamlit app that I gave a brief overview of.</p><p>I encourage you to clone my repository, utilize my code, and conduct your own investigations. CLIP is a really fun tool with many creative applications.</p><p>Please feel free to contact me on <a href="https://www.linkedin.com/in/kitsamho/">LinkedIn</a> or here if you have any further questions. Thank you for reading!</p><p>Best regards, Sam :)</p><h3>Resources</h3><p>Project Repository: <a href="https://github.com/kitsamho/clip_app">https://github.com/kitsamho/clip_app</a></p><p>Streamlit App: <a href="https://clip-demo-app.streamlit.app/">https://clip-demo-app.streamlit.app/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4648a677b4a8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/clip-streamlit-app-4648a677b4a8">OpenAI’s CLIP in Action: Exploring the Power of Image-Text AI using Streamlit</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Streamlit app to visualise Covid-19 data]]></title>
            <link>https://medium.com/data-science/interactive-dashboard-in-streamlit-to-analyse-owid-covid-19-data-180b1c3372e4?source=rss-c3acc81ee8bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/180b1c3372e4</guid>
            <dc:creator><![CDATA[Sam Ho]]></dc:creator>
            <pubDate>Wed, 21 Jul 2021 19:59:16 GMT</pubDate>
            <atom:updated>2021-07-29T15:57:05.937Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*H9Zjg1jW_C-AGMzG" /><figcaption>Photo by <a href="https://unsplash.com/@edwinhooper?utm_source=medium&amp;utm_medium=referral">Edwin Hooper</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Context</h3><p><a href="https://ourworldindata.org/">Our World in Data</a> (OWID) is an open-source, online research publication. They have a wide range of public data sets covering topics such as disease, climate change, social injustice and poverty.</p><blockquote>The goal of our work is to make the knowledge on the big problems accessible and understandable….Our World in Data is about Research and data to make progress against the world’s largest problems.</blockquote><p>So you won’t be surprised to find that OWID has an extensive collection of Covid-19 data sets hosted on their <a href="https://github.com/owid/covid-19-data">GitHub</a> repository.</p><p>Taking some of their Covid-19 data, I set out to build a <a href="https://streamlit.io/">Streamlit</a> app that would allow users to visualise and analyse Covid-19 data. Of particular importance was the ability for users to be able to <strong>interact with the data</strong> allowing for bespoke analysis and answer questions such as:</p><ul><li><em>Is there a relationship between population density and total cases?</em></li><li><em>Which countries are leading vaccination rollouts and who is lagging?</em></li><li><em>What features are most strongly correlated with deaths?</em></li></ul><p>I wanted it to look easy on the eye so <a href="https://plotly.com/">Plotly</a> was my go-to charting library for this task. I specifically wanted to animate some of the visualisations and Plotly is one of a few libraries that can do this in a code efficient manner.</p><p>The final Streamlit is deployed and you can find it at the link below but I wanted to walk through some of the key steps I took to build it and talk about some of the thinking that took place throughout its development.</p><p><a href="https://share.streamlit.io/kitsamho/covid-19-data/covid_streamlit_app.py">https://share.streamlit.io/kitsamho/covid-19-data/covid_streamlit_app.py</a></p><h3>What data do we have access to?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZWYXyhz5lRHO1vOH" /><figcaption>Photo by <a href="https://unsplash.com/@mbaumi?utm_source=medium&amp;utm_medium=referral">Mika Baumeister</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>There are many datasets on the OWID GitHub repository however they have aggregated many of the key data points into one combined structure. This makes life considerably easier as transformations are in less intensive.</p><p>Let’s have a look at the CSV.</p><pre>import pandas as pd</pre><pre>df = pd.read_csv(&#39;owid-covid-data.csv&#39;)<br>print(df.shape)</pre><pre>(101752, 60)</pre><pre>print(&#39;Total unique continents:&#39;,len(df.continent.unique()))<br>print(&#39;Total unique countries:&#39;,len(df.location.unique()))<br>print(&#39;Date span:&#39;,df.date.min(),df.date.max())</pre><pre>Total unique continents: 7<br>Total unique countries: 231<br>Date span: 2020-01-01 2021-07-11</pre><p>Let’s inspect the head of the data frame..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FlD7dHAVh3dp6ejaGCrX8g.png" /><figcaption>Image by Author — Sample DataFrame</figcaption></figure><h4>Observations</h4><ul><li>We have 60 columns and just over 101,000 rows (correct as of July 2021) with<strong> each row representing a day in the year</strong></li><li>We have 231 countries spanning 6 continents</li><li>Almost all variables are <strong>continuous</strong> whereas country and continent are <strong>categorical</strong>.</li><li>There are <strong>a lot of null values </strong>(more on this in a bit).</li><li>Given the nature of our analysis some of these variables are <strong>dependent</strong> and some are best described as <strong>independent</strong>, especially if we are looking through the lens of risk factors and their impact on the Covid-19 pandemic.</li></ul><p><em>Note — I’ve selected 24 variables that I feel are most useful to demo the dashboard, these are outlined below. If you want you can evolve this app and include more.</em></p><h4>Dependent Variables</h4><pre>dependent_var = [‘total_deaths’,’total_deaths_per_million’,’total_cases_per_million’,’icu_patients_per_million’,‘people_vaccinated_per_hundred’,<br>’total_vaccinations’,&#39;hosp_patients_per_million]</pre><h4>Independent Variables</h4><pre>independent_var = [‘gdp_per_capita’,’population’,’stringency_index’,’population’, <br>‘population_density’, ‘median_age’, ‘aged_65_older’,<br>‘aged_70_older’, ‘gdp_per_capita’, ‘extreme_poverty’,<br>‘cardiovasc_death_rate’, ‘diabetes_prevalence’, <br>‘female_smokers’,’male_smokers’, ‘handwashing_facilities’, <br>‘hospital_beds_per_thousand’,’life_expectancy’,&#39;continent&#39;, &#39;location&#39;]</pre><p>Most of these metrics are self explanatory. For a detailed breakdown of what they represent and how they are measured there is an extensive data dictionary <a href="https://github.com/owid/covid-19-data/blob/master/public/data/owid-covid-codebook.csv">here</a>.</p><h3>Data Preparation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ejcK0ASctTjw9mpY" /><figcaption>Photo by <a href="https://unsplash.com/@kate5oh3?utm_source=medium&amp;utm_medium=referral">Katie Smith</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Missing values &amp; Interpolation</h4><p>Often when we are preparing data we encounter missing values. This can be because of errors in collection pipelines or it could be because there wasn’t any data to begin with. When we are dealing with data that fits a gaussian distribution a valid strategy is to replace nulls with the mean and in other instances the median possibly. For data that is cumulative over time a more appropriate technique would be to use interpolation where we estimate and impute values based on its surrounding values. Pandas has a method pd.interpolate() and the default replacement is linear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yqj3TPMfr7OTXQEKIMpbEg.png" /><figcaption>Image by Author — How I experienced missing values in the OWID Covid-19 dataset</figcaption></figure><p>Inspection of the raw OWID data set revealed that missing values were commonplace. Here are some functions that solve this problem.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5238407a6e7ffbd1855ae877dbabb7c/href">https://medium.com/media/e5238407a6e7ffbd1855ae877dbabb7c/href</a></iframe><p>Below is the main function that produces clean/formatted data that can be used in the app.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/57597ac71a421b049f2044d2fbd176c2/href">https://medium.com/media/57597ac71a421b049f2044d2fbd176c2/href</a></iframe><p>Let’s have a look at the final DataFrame and see what it looks like for the UK.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xofMbX2nH_9W-R8WlasBBQ.png" /><figcaption>Image by Author — Example DataFrame</figcaption></figure><h4>Observations</h4><ul><li>Our Covid-19 <strong>dependent</strong> variables (e.g. total cases, deaths, hospital admissions, vaccinations) are grouped by week however you can see there is variance in the data as time progresses</li><li>Each <strong>independent</strong> feature (e.g GDP per capita, population density, smoking prevalence) is also grouped by week although the data doesn’t change as these things don’t move anywhere near as fast as Covid-19.</li></ul><p>Great, now we have the data in the right format for our needs. Next we need to start thinking about how to present this data in a meaningful and useful way on our app!</p><h3>Streamlit App Design</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jAsnd8wL5CXV0BGF" /><figcaption>Photo by <a href="https://unsplash.com/@kellysikkema?utm_source=medium&amp;utm_medium=referral">Kelly Sikkema</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This post assumes you have a working knowledge of how Streamlit works. If you don’t then please check this post out below for a primer</p><p><a href="https://towardsdatascience.com/streamlit-101-an-in-depth-introduction-fc8aad9492f2">Streamlit 101: An in-depth introduction</a></p><h4>Approach to Analysis</h4><p>There were two useful ways of looking at this data:</p><ul><li><strong>Cross sectionally </strong>— exploring the relationships between multiple independent variables and dependent variables at a <em>given point in time</em></li><li><strong>Time Series </strong>— exploring relationships between multiple independent variables and dependent variables and how this <em>changes over time</em></li></ul><p>I wanted to keep the app light in use and didn’t want to have multiple plots showing different data points so I took the decision to only use one <strong>scatter plot</strong> visualisation but allow for a high level of customisation from the user. This would encourage interactivity and hopefully a degree of discovery.</p><h4>Multiple Pages</h4><p>I built two pages in the app, one for cross section visualisation and one for time series visualisation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*pWpuQZKPuGzo1GN5eZCHSw.png" /><figcaption>Image by Author — Screenshot From App</figcaption></figure><p><em>Note — navigating Streamlit apps using pages is not a native feature on the Streamlit platform but there is a work around to this outlined by </em><a href="https://medium.com/u/ffa230f1042d">Praneel Nihar</a> here:</p><p><a href="https://medium.com/@u.praneel.nihar/building-multi-page-web-app-using-streamlit-7a40d55fa5b4">Building Multi Page Web App Using Streamlit</a></p><h4>Scatter Plots</h4><p>I love scatter plots. If a scatter plot is static and in two dimensions, we have the ability to show up to <strong>five</strong> variables in just the one figure.</p><ul><li>X axis</li><li>Y axis</li><li>Scatter point</li><li>Scatter Size</li><li>Scatter Colour</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*W_uaNJ3Tvnjib_wKrGTb3Q.png" /><figcaption>Image by Author — Example Cross Section Analysis</figcaption></figure><p>And if we animate these plots we can add a sixth dimension of <strong>time</strong> to the visualisation too</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v9KybUeETHTXCcHnWZy0nA.png" /><figcaption>Image by Author — Example Time Series Analysis</figcaption></figure><p>Finally if we can give the user the opportunity to change each one of these variables, then the scope of analysis can be widened even further. Widgets in Streamlit allow us to provide this feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IUKSp75u4lCJUxPprqQKEg.png" /><figcaption>Image by Author — Screenshot of Streamlit dropdown widgets</figcaption></figure><h4>Other Features</h4><p>In addition to X, Y and scatter data points I included some other visualisation options:</p><ul><li>The option to <strong>mask by continent</strong>, i.e. only show countries from specific continents</li><li>For X and Y plot a vertical / horizontal line denoting a measure of central tendency for a feature. This allows you to see which markers are above or below the average for any plotted metric</li></ul><h3>App Example Output — Cross Sectional Scatter Plot</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WWTP_iEXBKx73Zm3I0VEsg.png" /><figcaption>Image by Author — Example Cross Sectional Scatter Plot</figcaption></figure><p>The code block below outlines the steps needed to create the cross sectional scatter plot as above.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71ed145b4e2eeb4930b0075577deb2d9/href">https://medium.com/media/71ed145b4e2eeb4930b0075577deb2d9/href</a></iframe><h3>Example Output — Time Series Scatter Plot</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VPae4nD82iUx9gi4BvhZ7Q.png" /><figcaption>Image by Author — Example Cross Sectional Scatter Plot with animation</figcaption></figure><p>And this code block below outlines the steps needed to create the cross sectional scatter plot that is animated.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f774d127b3d051bfdbfc44fbc32bfc1/href">https://medium.com/media/5f774d127b3d051bfdbfc44fbc32bfc1/href</a></iframe><h3>Summary</h3><p>Hopefully this short walk through has given you some examples of how we can visualise data in a compelling way. By choosing the right tools to interact with the data and through using appropriate visualisations, exploratory analysis can be more efficient, more fun and more informative than using bar charts alone.</p><p>By all means please take my Streamlit code and build on it — there is a lot of data here and even though I have written some comprehensive code to visualise the data I’m sure there’s plenty of other avenues that can be explored and built upon.</p><p>Until next time!</p><p>Sam</p><h3>Links &amp; Resources</h3><p>To launch this app locally you should clone my forked OWID repo and in the command line run:</p><pre>$ streamlit run covid_streamlit_app.py</pre><ol><li><a href="https://share.streamlit.io/kitsamho/covid-19-data/covid_streamlit_app.py">Streamlit App</a></li><li><a href="https://github.com/kitsamho/covid-19-data">Forked OWID repository with my app</a></li><li>Streamlit app r<a href="https://github.com/kitsamho/covid-19-data/blob/master/requirements.txt">equirements</a></li><li><a href="https://github.com/owid/covid-19-data">Original Our World In Data repo</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=180b1c3372e4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/interactive-dashboard-in-streamlit-to-analyse-owid-covid-19-data-180b1c3372e4">Building a Streamlit app to visualise Covid-19 data</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using sentence embeddings to explore the similarities and differences in song lyrics]]></title>
            <link>https://medium.com/data-science/using-sentence-embeddings-to-explore-the-similarities-and-differences-in-song-lyrics-1820ac713f00?source=rss-c3acc81ee8bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/1820ac713f00</guid>
            <category><![CDATA[visualisation]]></category>
            <category><![CDATA[sentence-embedding]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[music]]></category>
            <dc:creator><![CDATA[Sam Ho]]></dc:creator>
            <pubDate>Wed, 10 Jun 2020 11:45:58 GMT</pubDate>
            <atom:updated>2020-06-18T18:15:16.760Z</atom:updated>
            <content:encoded><![CDATA[<h3>Analyzing lyrics from different music genres with universal sentence encoding</h3><h4>Applying Google’s Universal Sentence Encoder and Principal Component Analysis to identify similarities and differences across music genres</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*laYRStNslkeZUoYt" /><figcaption>Photo by <a href="https://unsplash.com/@annietheby?utm_source=medium&amp;utm_medium=referral">Annie Theby</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FVBddnh_9zUA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DVBddnh_9zUA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FVBddnh_9zUA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8f20ac85ec7e556799708c3c687b216/href">https://medium.com/media/d8f20ac85ec7e556799708c3c687b216/href</a></iframe><p>My enduring love affair with music was ignited in 1992 when on my 12th Christmas, my doting parents stumped up the pennies and bought me an Alba HiFi.</p><p>Belt-drive Turntable? Check! <br>Twin Cassette Players? Check!<br>Graphic Equalizer with <strong>BASS BOOST</strong>? Of course!</p><p>I have been listening to all kinds of music ever since.</p><p>I’m now almost 40 and in those 28 music-infused years I have deepened my relationship with music. I am a <a href="https://youtu.be/OlCw5WQvffI?t=1881">guitarist</a>, a DJ, and a <a href="https://soundcloud.com/honanofficial">dance music producer</a>. Music has punctuated my life in a multitude of joyous ways — as it has for many of you I would expect.</p><p>So though I feel I’m (reasonably) qualified to talk about music genres, I find that it can be quite hard to define them and/or differentiate them from one another.</p><h3>Genres evolve and genres are subjective</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kED3cWpQp4CLa5vw" /><figcaption>Photo by <a href="https://unsplash.com/@jithotw?utm_source=medium&amp;utm_medium=referral">IJ Portwine</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Boundaries that divide genres are fuzzy and the passing of time augments this even more. The Rolling Stones and the Beatles were initially chastised by some as being the work of the devil* yet nowadays are as mainstream as flat-pack furniture.</p><p><em>*</em><a href="https://i2.wp.com/metalinjection.s3.amazonaws.com/wp-content/uploads/2013/01/Slayer-headbang.gif?resize=470%2C353"><em>Slayer</em></a><em> reign supreme for the Devil’s work FYI. \m/</em></p><h3>Genre is manipulated</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oicKYtVWfCXcIeSy" /><figcaption>Photo by <a href="https://unsplash.com/@huntersrace?utm_source=medium&amp;utm_medium=referral">Hunters Race</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When commercial interests overshadow authenticity (almost always sadly), ‘genres’ can be manufactured. These contrived labels are used by record companies to target groups of customers for commercial advantage, sometimes in ways that reflect <a href="https://www.rollingstone.com/music/music-features/labels-ditch-urban-1011593/">deeper flaws in society</a>.</p><h3>So is there any way we can measure genre?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*T9vbOo6Rr2e6YGrk" /><figcaption>Photo by <a href="https://unsplash.com/@wwarby?utm_source=medium&amp;utm_medium=referral">William Warby</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>It is evident that genre classification can be subjective, contentious, and maybe even futile — after all, good music is good music, right?</p><p>However, I would say there are <strong><em>at least two</em></strong> valid ways to differentiate genres from one another: a song’s <strong>musicality</strong> and a song’s <strong>lyrics.</strong></p><h3>What does the music sound like?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qvLCiYBY7xzxEjEA" /><figcaption>Photo by <a href="https://unsplash.com/@www_erzetich_com?utm_source=medium&amp;utm_medium=referral">Blaz Erzetic</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Is it…</p><ul><li>Live or sequenced? (Rock vs. Techno?)</li><li>Loud or quiet? (Dubstep vs. Chillout?)</li><li>Dissonant or melodic? (Thrash metal vs. Soul?)</li><li>Predictable or unexpected? (Pop vs. Jazz?)</li></ul><h3>What is the music saying and how is it being said?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cPVvkQByRk_KVg4h" /><figcaption>Photo by <a href="https://unsplash.com/@vidarnm?utm_source=medium&amp;utm_medium=referral">Vidar Nordli-Mathisen</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><ul><li>Are the lyrics anchored in certain <strong>emotions</strong> (e.g. sadness, happiness, anger)?</li><li>Are the lyrics talking about <strong>topics</strong> (love, loss, war, injustice, oppression, death)?</li></ul><p>For this project, I want to focus specifically on <strong>lyrics</strong> and the <strong>language</strong> that songwriters use in their songs.</p><p><em>Qualitatively</em> we all feel that lyrical content varies by genre. But is there a way we can measure this, <em>quantitatively</em>?</p><h3>Project Aim</h3><blockquote>There are differences between the lyrics of different genres and we can quantify and measure this!</blockquote><h3>Challenges &amp; Approach</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mU7u19x1CSDtaC3f" /><figcaption>Photo by <a href="https://unsplash.com/@pperkins?utm_source=medium&amp;utm_medium=referral">Patrick Perkins</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Where do we get the data?</h4><ul><li>We will scrape lyrics from <strong>Musixmatch.com</strong>, a free website that hosts a tonne of accurate lyric content</li></ul><h4>What kind of method/metric will allow us to quantify lyrical diversity in an intuitive way?</h4><ul><li>We will represent lyrics using high dimensional vectors from <strong>Google’s Universal Sentence Encoder</strong></li><li>We will apply <strong>Principal Component Analysis (PCA) </strong>to reduce these high dimensional representations to n=1,2,3 dimensions</li></ul><h4>How can we visualize this in a meaningful way?</h4><ul><li>We will use <strong>Plotly</strong> and build a combination of simple plots and more sophisticated 2d and 3d scatter plots to see where there are similarities and differences in lyrics</li></ul><p><strong>All notebooks and full raw data are available on my GitHub </strong><a href="https://github.com/kitsamho/songlyrics_univeral_sentence_encoder"><strong>here</strong></a></p><h3>Getting the data</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dGf2udFBWod4C_585gwEYw.png" /><figcaption>Source: <a href="https://www.musixmatch.com/">https://www.musixmatch.com/</a></figcaption></figure><p>In preparation for this project, I discovered that it’s really hard to find an accurate source of lyrics online. Songs are either incomplete or the volume available is less than comprehensive.</p><p><strong>Musixmatch.com</strong> seems to be one of a few sites that :</p><ol><li>Has a lot of content.</li><li>Is reasonably accurate.</li></ol><p>So let’s use that as our data source.</p><p><strong>Musixmatch</strong> have a developer API that we could use to get lyric data but they only allow you to make 2k calls a day and you can only have about 30% of each song’s lyrics to play with.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*4fZDaJeR1MNB9bugAAqJ8A.gif" /><figcaption>Source: Giphy</figcaption></figure><p>Let’s get around this by scraping the site using a combination of <strong>requests</strong> and <strong>HTML parsing</strong>. This is an ‘out-of-browser’ process so we can easily implement multi-threading to speed the process up. This means we can get more content in a shorter period of time.</p><p>I’ve written a Python class below which contains all the methods to extract lyric content for an artist.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/282be15df6c9493c8687e7208cd071ce/href">https://medium.com/media/282be15df6c9493c8687e7208cd071ce/href</a></iframe><h4>Running the scraper</h4><p>All you need to do is to instantiate the class with a Musixmatch artist URL and a genre label…</p><pre>scraper = MusixmatchScraper(&#39;<a href="https://www.musixmatch.com/artist/Jack-Johnson&#39;">https://www.musixmatch.com/artist/Jack-Johnson&#39;</a>,&#39;folk&#39;)</pre><p>..and then call the self.Run() method to start the scraper.</p><p><strong><em>Caveat</em></strong> <em>— if you want to scrape a lot of lyrics, you should rotate your IP address where possible. If you make too many requests to Musixmatch.com your IP will be blocked, albeit temporarily. I find you can get away with scraping c.250 songs before this happens.</em></p><h3>Scraping Multiple Artists</h3><p>MusixmatchScraper() is coded in a way that allows you to scrape the content for <strong>one</strong> artist. If you want to get multiple artists you could create a loop like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e5c8fc8931c0b3ecdb6f2d97fa2e35b/href">https://medium.com/media/2e5c8fc8931c0b3ecdb6f2d97fa2e35b/href</a></iframe><p>The class returns a Pandas DataFrame which looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lyeDxfymTHccTb9c_gzB7g.png" /><figcaption>Example DataFrame output</figcaption></figure><p>Great, now that we have our data. Let’s explore the data to see what we have.</p><h3>Exploratory Data Analysis</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JR8Dz0sAXwklk6hQ" /><figcaption>Photo by <a href="https://unsplash.com/@lukechesser?utm_source=medium&amp;utm_medium=referral">Luke Chesser</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Before we start looking at sentence embedding, let’s fire up some simple plots using Plotly.</p><h3>Pandas &amp; Plotly</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N_nmMH3FexAnHJdYWpxP7A.png" /><figcaption>Source: www.plotly.com</figcaption></figure><p>I generally prefer Plotly visualizations over anything else. They look nicer, are interactive and you can easily curate and share them using <a href="https://plotly.com/chart-studio/">Plotly Chart Studio</a>. The only downside is that it can take quite a lot of code (and a lot of nested dictionaries!) to get something useful out of Plotly which is annoying when all you want to do is to quickly explore the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*863QBXPBBMWumi416-emPA.gif" /><figcaption>Source: Giphy</figcaption></figure><p>One thing I would recommend is <strong>updating Plotly to at least 4.8</strong> as Pandas can now use <strong>Plotly as the library for backend plotting</strong> as opposed to the ‘aesthetically impaired’ Matplotlib.</p><p>In the code block below — we can fire up a simple bar chart from Pandas DataFrame <strong>just</strong> by adding .plot.bar() to a DataFrame object.</p><p>Simple as 123,abc!</p><p>pd.DataFrame([1,2,3],[&#39;a&#39;,&#39;b&#39;,&#39;c&#39;]).plot.bar()</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*auoDqt6cOFipFZlEdz_9kg.png" /><figcaption>Example Plotly backend output</figcaption></figure><p>You can tweak the look and feel of your figure if you want by using the same parameters you’d normally use with a <strong>Plotly Graph Objects</strong>, so there is that added familiar flexibility.</p><p>Ok back to the project...</p><h3>What genres and artists have we got?</h3><p>I decided to get lyrics from a <strong>range</strong> of genres, some more extreme than others in order to see if we can see differences but I also chose very overlapping genres to see if there are commonalities.</p><p>Let’s look at how many songs in each genre we have.</p><pre>#plot genres<br>fig_genre = pd.DataFrame(df.genre.value_counts()).plot.bar(template=&#39;ggplot2&#39;)</pre><pre>#title parameters<br>title_param = dict(text=&#39;&lt;b&gt;Count of Genre&lt;/b&gt;&lt;br&gt;&lt;/b&gt;&#39;, <br>                        font=dict(size=20))</pre><pre>#update layout<br>fig_genre.update_layout(title=title_param,<br>                  width=1000,<br>                  height=500,        <br>                  xaxis = dict(title=&#39;Genre&#39;),<br>                  yaxis = dict(title=&#39;Count&#39;))</pre><pre>#change the colour<br>fig_genre.update_traces(marker_color=&#39;rgb(148, 103, 189)&#39;)</pre><pre>#show plot<br>fig_genre.show()</pre><p>Each genre is reasonably well represented — enough to make meaningful comparisons at least.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*1MetqmAJPjAr8L5WcMiMcQ.png" /><figcaption>Original Plot Here : <a href="https://chart-studio.plotly.com/~kitsamho/240/#/">https://chart-studio.plotly.com/~kitsamho/240/#/</a></figcaption></figure><p>What about artists by genre?</p><p>Let’s go to town with some visualization and create a sunburst map of genre and artist. If you want to interact with the plot, the link to the original plot is in the footnote.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*GKJhko_-uAz6zNrEO0vdTg.png" /><figcaption>Interactive plot here: <a href="https://plotly.com/~kitsamho/254/">https://plotly.com/~kitsamho/254/</a></figcaption></figure><p>I’ve got a range of bands and artists who I feel represent those genres. You might disagree with me. That’s fine, genre definition can be contentious.</p><h3>Are there differences in lyric length?</h3><p>Let’s explore lyric length by genre.</p><pre>#get lyric frequencies for each song<br>df[&#39;lyric_count&#39;] = df[&#39;lyrics&#39;].map(lambda x: len(x.split()))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*Us7JiWXWDEQky_V5Ldqn0Q.png" /><figcaption>Original plot here: <a href="https://chart-studio.plotly.com/~kitsamho/244">https://chart-studio.plotly.com/~kitsamho/244</a></figcaption></figure><p>Hip-hop is a very lyric heavy genre — many of the key descriptive metrics that describe lyric count for hip-hop are different from all other genres.</p><p>It will be interesting to see if the <em>content</em> of those lyrics are also different when we analyze the content of those lyrics. Which conveniently leads me to the next part of the EDA…Part of Speech (PoS) analysis.</p><h3>Part of Speech Analysis</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3Tsxt8Eh0__2IgG4" /><figcaption>Photo by <a href="https://unsplash.com/@brett_jordan?utm_source=medium&amp;utm_medium=referral">Brett Jordan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>So the next thing which would be interesting to look at is to understand the <strong>content</strong> of these lyrics. To do this I will use a spaCy model to classify lyrical content into its relevant parts of speech i.e classifying which words in the lyrics are nouns, verbs, adjectives, and so on. This will enable us to understand a little more about the differences in lyrical content across genres and may allude to where similarities and differences may lie.</p><pre>import spacy</pre><pre>#load spacy model<br>nlp = spacy.load(&#39;en_core_web_sm&#39;)</pre><pre>def pos(string,pos):<br>    <br>    &quot;&quot;&quot;Returns any token that qualifies as a specific part of speech&quot;&quot;&quot;<br>    <br>    doc = nlp(string) #fit model<br>    <br>    return &#39; &#39;.join(list(set([i.text for i in doc if i.pos_ == pos]))) #return any tokens that qualify</pre><p>Let’s call the function above in a loop and get new columns containing all the useful parts of speech.</p><pre>#get nouns<br>pos_of_interest = [&#39;NOUNS&#39;,&#39;VERBS&#39;,&#39;ADJ&#39;,&#39;ADV]</pre><pre>#loop through each PoS<br>for pos in pos_of_interest:<br>      df[pos] = df.lyrics.map(lambda x: pos(x,pos))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aprODhxOzp3j_6pUtyls9Q.png" /><figcaption>Example DataFrame output of PoS</figcaption></figure><h3>Most Common Words</h3><p>Below is a function that will count the most common tokens in a string. We can use this to analyze the most common words in a song— including the PoS we have just made.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c442f80435e84876b30eb3f120f8c30/href">https://medium.com/media/5c442f80435e84876b30eb3f120f8c30/href</a></iframe><pre>#call the function on one gram<br>musixmatch_mostcommon(df.lyrics,token=1).head(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*3M9aLshTokYHHhD0W05Zcw.png" /><figcaption>Example DataFrame output</figcaption></figure><p>It will be more useful to find a way to use this function across all genres and by different parts of speech. An effective way to do this is to use Treemap visualizations. Plotly has a good template for this, so I’ve built a function that can do this for us.</p><h3>Treemap Visualizations</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4024ee9ed229211bc285e6540e3f8b58/href">https://medium.com/media/4024ee9ed229211bc285e6540e3f8b58/href</a></iframe><p>Let’s call the function and look at the output</p><pre>noun_treemap = musixmatch_genremap(df,pos=&#39;nouns&#39;)</pre><p><strong>WARNING</strong> — some of these lyrics are explicit</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*cYxWc_eDN1TjhvKe_TF3SA.png" /><figcaption>Interactive plot here: <a href="https://plotly.com/~kitsamho/246/">https://plotly.com/~kitsamho/246/</a></figcaption></figure><p>If you’re on a desktop I would strongly recommend you visit the link in the treemap footnote (above) in order to interact with it.</p><h3>Universal Sentence Encoding</h3><p>Now we get to the really fun part — using <strong>vectors</strong> to represent our lyrics. We can then use various techniques that can show us which vectors/lyrics are similar or different.</p><h3>What are vector representations?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QyixZ9Y-SsFeX2iR" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Vector representations of words were a significant step-change for natural language processing. Early methods that attempted to ‘understand’ language usually involved counting words (e.g. a bag of words model or weighted models / TFIDF approaches). These were limited in that they failed to capture the <strong>context</strong> of language. After all, the sentence <em>‘kid breaks skateboard’</em> is very different in meaning to <em>‘skateboard breaks kid’ ….</em>despite having the same type and number of words.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*C8ATouZA1OreMnnPTVZz8g.gif" /><figcaption>Source: Giphy — kid breaks skateboard</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*iRbJijG5Q8nZmymfLHUOUQ.gif" /><figcaption>Source: Giphy — skateboard breaks kid</figcaption></figure><p>Word2vec by Tomas Mikolov et al. was game-changer in that words were no longer rudimentarily represented as counts but as high-dimensional vectors. These vectors, or <strong>embeddings</strong>, were created through the training of a simple neural network on a corpus of text. These word embeddings represent a word’s <strong>relationship with a neighboring word</strong> and therefore its context. Therefore the vectors for the word ‘walking’ and ‘walked’ would be more similar than the words ‘swimming’ and ‘swam’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OEmWDt4eztOcm5pr2QbxfA.png" /><figcaption>Source: <a href="https://developers.google.com/machine-learning/crash-course/embeddings/translating-to-a-lower-dimensional-space">https://developers.google.com/machine-learning/crash-course/embeddings/translating-to-a-lower-dimensional-space</a></figcaption></figure><p>If you want to learn more about this I would recommend reading the <a href="https://papers.nips.cc/paper/5021-distributed-representations-of-words-and-phrases-and-their-compositionality.pdf">original whitepaper </a>or a <a href="https://kitsamho.github.io/trustpilot-nlp-explore-content/#">previous project I did</a> with ASOS review on TrustPilot.</p><h3>Google’s Universal Sentence Encoder</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cBLomt7la5i2yREwVH9_kw.png" /><figcaption>Source: <a href="https://tfhub.dev/google/universal-sentence-encoder/1">https://tfhub.dev/google/universal-sentence-encoder/</a>4</figcaption></figure><p>For this project, we will be using<strong> Google’s Universal Sentence Encoder</strong>, a state of the art encoder that has been trained on millions (possibly billions?) of documents.</p><p>It’s like word2vec but on steroids.</p><blockquote>The Universal Sentence Encoder encodes text into high dimensional vectors that can be used for text classification, semantic similarity, clustering and other natural language tasks.</blockquote><blockquote>The model is trained and optimized for greater-than-word length text, such as sentences, phrases or short paragraphs. It is trained on a variety of data sources and a variety of tasks with the aim of dynamically accommodating a wide variety of natural language understanding tasks.</blockquote><p>Source: <a href="https://tfhub.dev/google/universal-sentence-encoder/1">https://tfhub.dev/google/universal-sentence-encoder/</a>4</p><p>If you want to find out more about this model, I would strongly recommend you read the documentation on <a href="https://tfhub.dev/google/universal-sentence-encoder/1">TensorFlow hub</a> as it covers a lot more detail.</p><h3>Using the Google Universal Sentence Encoder on our lyric data</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*QLvZzPvNge4ivYabLXis7w.png" /><figcaption><a href="https://tfhub.dev/google/universal-sentence-encoder/1">https://tfhub.dev/google/universal-sentence-encoder/</a>4</figcaption></figure><p>Let’s use Tensorflow Hub to load the model..</p><pre>#get universal sentence encoder<br>USE = hub.load(&quot;<a href="https://tfhub.dev/google/universal-sentence-encoder/4">https://tfhub.dev/google/universal-sentence-encoder/4</a>&quot;)</pre><p>And let’s write a short function that can get a high dimensional vector for any string input using the model.</p><pre>def getUSEEmbed(_string,USE = USE):<br>    <br>    &quot;&quot;&quot;Function takes a string argument and returns its high dimensional vector from USE&quot;&quot;&quot;<br>    <br>    return np.array(USE([_string])[0])</pre><p>Let’s get the vector for a simple sentence….</p><pre>example = getUSEEmbed(&#39;Hello how are you?&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uZlbZYW2ficYpK3zx7EqjA.png" /><figcaption>High dimensional vector representing ‘Hello how are you?’</figcaption></figure><p>As you can see a simple sentence has now been encoded as a high dimensional vector with a shape of (512,)</p><h3>Assessing similarity and differences between vectors</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UQp0S6Pz2_JGR_9l" /><figcaption>Photo by <a href="https://unsplash.com/@frankiefoto?utm_source=medium&amp;utm_medium=referral">frank mckenna</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The cornerstone of this project is to find a way to <strong>find similarities and differences in song lyrics</strong>. As we are encoding lyrics into vector representations then we need to use techniques that allow us <strong>find similarities and differences in vectors</strong></p><p>We can do this by:</p><ol><li>Using <strong>cosine similarity</strong></li><li>Dimension <strong>reduction and visualization </strong>(using something like Principal Component Analysis)</li></ol><h3>Cosine Similarity</h3><p>Often when we have continuous, low dimensional data we would use something like Euclidean distance to gauge similarity/difference. We would use this distance metric with something like a KNN classifier or even when clustering dimensionally reduced vectors such as after a PCA.</p><p>However, because our vectors from the sentence encoder have very <strong>high dimensionality</strong> then using <strong>cosine similarity</strong> is a better proximity metric to use than Euclidean distance, to begin with at least.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/0*T8voFy16oUOVeK-P.png" /><figcaption>Cosine similarity calculates similarity as the normalized dot product of two vectors / source: <a href="https://en.wikipedia.org/wiki/Cosine_similarity">https://en.wikipedia.org/wiki/Cosine_similarity</a></figcaption></figure><p>A cosine similarity closer to 1 would mean there is minimal variance between the two vectors (the input strings are <strong>similar</strong>) whereas a cosine similarity closer to 0 would mean that two vectors are very different (the input stings are <strong>different</strong>)</p><p>Let me show you an example with four sentences.</p><p>Two of which are about <strong>weather..</strong></p><ul><li><em>“The weather is going to be really warm today”</em></li><li><em>“Today is going to be the sunniest day of the year”</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PCIV-bJqjn6EKj7c" /><figcaption>Photo by <a href="https://unsplash.com/@shimikumi32?utm_source=medium&amp;utm_medium=referral">Kumiko SHIMIZU</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>And another two that are about <strong>breakfast</strong></p><ul><li><em>“I like my eggs sunny side up”</em></li><li><em>“Breakfast is my favourite meal”</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mO5p5TsvDe2bxHa0" /><figcaption>Photo by <a href="https://unsplash.com/@wilhelmgunkel?utm_source=medium&amp;utm_medium=referral">Wilhelm Gunkel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I’ve specifically chosen examples where the word ‘sunny’/’sunniest’ has been <strong>used as a metaphor and as an adjective</strong>. Let’s see if the encoding can capture this difference.</p><pre>#some example sentences<br>example_sentences = [&quot;The weather is going to be really warm today&quot;,<br>                     <br>                     &quot;Today is going to be the sunniest day of the year&quot;,<br>                     <br>                     &quot;I like my eggs sunny side up&quot;,<br>                     <br>                     &quot;Breakfast is my favourite meal&quot;]</pre><pre>#get embeddings for each example sentence<br>embed = [getUSEEmbed(i) for i in example_sentences]</pre><pre>#set up a dictionary where each sentece is a key and its value is its 512 vector embedding<br>dic_ = dict(zip(example_sentences,embed))</pre><pre>#let&#39;s find all the unique pairwise sentence combinations<br>combo = [list(i) for i in itertools.combinations(example_sentences, 2)]</pre><p>Now we need a function to calculate similarity.</p><pre>def cosineSimilarity(vec_x,vec_y):<br>    <br>    &quot;&quot;&quot;Function returns pairwise cosine similarity of two vector arguments&quot;&quot;&quot;<br>    <br>    return cosine_similarity([vec_x],[vec_y])[0][0]</pre><p>Let’s make a DataFrame that maps the cosine similarity for each unique sentence pair.</p><pre>#empty list for data<br>cs = []</pre><pre>#lop through each unique sentence pairing<br>for i in range(len(combo)):<br>    <br>    #get cosine similarity for each<br>    cs_ = cosineSimilarity(dic_[combo[i][0]],dic_[combo[i][1]])<br>    <br>    #append data to list<br>    cs.append((combo[i][0],combo[i][1],cs_))</pre><pre>#construct DataFrame<br>cs_df = pd.DataFrame(cs,columns[&#39;sent_1&#39;,&#39;sent_2&#39;,&#39;cosine_similarity&#39;]).\<br>                    sort_values(by=&#39;cosine_similarity&#39;,ascending=False)</pre><p>Let’s inspect the DataFrame.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3VjkhCWvIzGIVa7UV97ycA.png" /><figcaption>Comparing cosine similarity of four sentences</figcaption></figure><p>This is so cool. The sentences that are <strong>most similar have more similar vectors </strong>(cosine similarity of 0.41 / 0.51). Even with the ambiguity of using a word that functions as a metaphor and an adjective, the encoding is sufficiently differentiated. Let’s see if we can apply this with our song lyrics.</p><h3>Getting Embeddings for each Song</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lwKH5fdg1s17Bbqk" /><figcaption>Photo by <a href="https://unsplash.com/@nosoycesar?utm_source=medium&amp;utm_medium=referral">César Abner Martínez Aguilar</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>First, we need to get the vectors for each song.</p><pre>#get USE embeddings for each song<br>df_embed = pd.DataFrame([getUSEEmbed(df.lyrics[i]) for i in range(df.shape[0])],\<br>                        index=[df.song[i] for i in range(df.shape[0])])</pre><p>Inspect the DataFrame with df_embed.head(5)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZLlVlmRwpmKmgek4PIXPag.png" /><figcaption>Vectors for each song — high dimensions/columns</figcaption></figure><p>Let’s use another data reduction technique — <strong>Principal Component Analysis</strong>, to reduce the dimensionality of these embeddings whilst retaining as much variance as possible.</p><p>I’ve built a comprehensive function to do this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7e63326e9a7f238e071052083cd6678/href">https://medium.com/media/f7e63326e9a7f238e071052083cd6678/href</a></iframe><p>Let’s call this function and get three new DataFrames.</p><pre>pc_1 = musixmatch_PCA(df,df_embed,n_components=1)<br>pc_2 = musixmatch_PCA(df,df_embed,n_components=2)<br>pc_3 = musixmatch_PCA(df,df_embed,n_components=3)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cXa9Wg4wARvsFHhA3Pe8cQ.png" /><figcaption>Example DataFrame output</figcaption></figure><p>Let’s do some grouping to explore which artists have lyrics that are most similar to each other.</p><p>As we can see — even with just one component, artists from genres tend to cluster together. Death metal, heavy metal, and rock differ slightly from one another but vastly different to pop and soul. This makes sense.</p><p>If you are familiar with these bands as you scroll down you will get a strong sense of how genres evolve and that we can see this in the variance across principal component 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*CNouCnbDklt7QpW-FjPxYg.png" /><figcaption>Original plot here: <a href="https://chart-studio.plotly.com/~kitsamho/248">https://chart-studio.plotly.com/~kitsamho/248</a></figcaption></figure><p>Let’s look at the same analysis but <strong>grouped by genre.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*CX9fNaCasIgZqZK0A0arNg.png" /><figcaption>Original Plot here : <a href="https://chart-studio.plotly.com/~kitsamho/248">https://chart-studio.plotly.com/~kitsamho/248</a></figcaption></figure><p>This averaged view confirms what we suspected above.</p><p>Let’s make a more sophisticated visualization that uses scatter plots to show this data, by song.</p><p>We can look at this in two dimensions (PC1,PC2) but also in three dimensions (PC1,PC2,PC3)</p><p>The function below combines a few functions from above with some more complex Plotly functions to generate scatter plots, either in 2d (PC1 / PC2) or in 3D (PC1 / PC2 / PC3)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9928be56db119907673ade0432251e7b/href">https://medium.com/media/9928be56db119907673ade0432251e7b/href</a></iframe><p>Let’s call the function and see what the plot looks like. Again, I would <strong>strongly recommend you click on the plot link</strong> in the footer for the screengrab below if you want to interact with all the genres and where they lie on the plot.</p><pre>scatPlot_2 = musixmatch_scatplot(df,df_embed,n_components=2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*XqVETsAFFYcmhFU57pv6pQ.png" /><figcaption>Click here for the interactive plot: <a href="https://plotly.com/~kitsamho/236/">https://plotly.com/~kitsamho/236/</a></figcaption></figure><p>We can also create a similar plot but utilize the 3 dimensions of the PCA.</p><pre>scatPlot_3 = musixmatch_scatplot(df,df_embed,n_components=3)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*o0ZECpsXZURdKbfpxT0ibA.png" /><figcaption>Click here for the interactive plot: <a href="https://plotly.com/~kitsamho/238/">https://plotly.com/~kitsamho/238/</a></figcaption></figure><h3>Conclusion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1avlqIjtJw36w-7B" /><figcaption>Photo by <a href="https://unsplash.com/@alx_andru?utm_source=medium&amp;utm_medium=referral">Alex</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>We have shown that lyrics from different music genres do vary although what is interesting is that there is quite a clear relationship between lyrical content as we move from one genre to another in a stepwise fashion. I think the visualization below quite clearly brings this to life.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*CX9fNaCasIgZqZK0A0arNg.png" /></figure><p>The <strong>lyrics of different genres aren’t entirely mutually exclusive</strong> — unless you compare the extremes. i.e. there is a huge difference between death metal and soul/r&amp;b but little in the way to differentiate pop and pop/rock.</p><p>These findings reflect the true nature of music in that<strong> music genres are fluid </strong>and that for each genre, there is likely to be a ‘neighbouring’ genre that is similar in its lyrical content.</p><p>After all, many fans of r&amp;b/soul will also like pop…..but maybe not punk and/or metal?</p><h3>Applications</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9q3cMB2g6PJkEm2j" /><figcaption>Photo by <a href="https://unsplash.com/@jeshoots?utm_source=medium&amp;utm_medium=referral">JESHOOTS.COM</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>We have shown that universal sentence encoding/transfer learning is a very powerful and incredibly easy technique that can be used to pull out the differences and similarities in song lyrics across genres.</p><p>Its applications on other problems are numerous:</p><ul><li><strong>Song/lyric recommender systems </strong>— using similarity metrics to find songs with similar lyrics</li><li><strong>Segmenting</strong> large volumes of text by finding similar documents e.g. emails, customer feedback/reviews</li><li>Identifying <strong>plagiarism</strong></li><li>To be used as features for <strong>classification tasks</strong></li></ul><p>Thanks for reading and get in touch if you want to talk further! I’ve saved my notebook on my GitHub with all the code ready to go and be used in other projects. Let me know if you do, I’d love to see.</p><p>Sam</p><h3>References &amp; Links</h3><ul><li>[1] GitHub (containing Jupyter notebook): <a href="https://github.com/kitsamho/songlyrics_univeral_sentence_encoder">https://github.com/kitsamho/songlyrics_univeral_sentence_encoder</a></li><li>[2] Beautiful Soup : <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/">https://www.crummy.com/software/BeautifulSoup/bs4/doc/</a></li><li>[3] Google Universal Sentence Encoder: <a href="https://tfhub.dev/google/universal-sentence-encoder/4">https://tfhub.dev/google/universal-sentence-encoder/4</a></li><li>[4] Plotly: <a href="https://plot.ly/python/">https://plot.ly/python/</a></li><li>[5] Musixmatch.com: <a href="https://www.musixmatch.com/">https://www.musixmatch.com/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1820ac713f00" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/using-sentence-embeddings-to-explore-the-similarities-and-differences-in-song-lyrics-1820ac713f00">Using sentence embeddings to explore the similarities and differences in song lyrics</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Network Science to explore hashtag culture on Instagram]]></title>
            <link>https://medium.com/data-science/using-network-science-to-explore-hashtag-culture-on-instagram-1f7917078e0?source=rss-c3acc81ee8bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f7917078e0</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[culture]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[social-media]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Sam Ho]]></dc:creator>
            <pubDate>Thu, 20 Feb 2020 14:13:23 GMT</pubDate>
            <atom:updated>2020-03-04T05:52:03.343Z</atom:updated>
            <content:encoded><![CDATA[<h4>A practical walk-through of how to scrape hashtags from Instagram and model their relationships with one another using NetworkX</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iQapuGdEadNsoRqJRIJL0A.jpeg" /><figcaption>Source : <a href="https://www.digitalambiance.com/instagram-light-forest-by-hey-hush/">https://www.digitalambiance.com/instagram-light-forest-by-hey-hush/</a></figcaption></figure><h3>Abstract</h3><p>This project proposes that Network Science and graph theory can be used to effectively analyse hashtag culture on Instagram. The relational characteristics of Instagram hashtags can be realised through these techniques and this allows for deeper understanding of conversations and themes found across hashtags.</p><h4>Approach</h4><p>To demonstrate this idea I have written a practical and technical walkthrough of how to do this using Python and NetworkX.</p><p>Around 37,000 Instagram posts all containing at least one mention of #happiness were scraped from Instagram. All unique hashtags in the corpus (other than #happiness) represented <strong>nodes</strong> in the graph. <strong>Edges</strong> were formed between hashtags if they were mentioned together in the same post.</p><p>This yielded an undirected ‘Happiness’ graph which was then analysed using community detection and various centrality measures.</p><h4>Findings</h4><p>Community detection identified three clusters, interpreted as:</p><ul><li>Aspects of happiness that seem to be about what people <strong>do and experience </strong>(e.g. ‘<em>#photography</em>, <em>#summer,</em> <em>#travel</em>,<em>#family</em> )</li><li>Aspects of happiness that broadly seem to be about how people <strong>think and feel</strong> (e.g <em>#life</em>, <em>#motivation</em>, <em>#inspiration, #quotes</em>)</li><li>A third very distinct cluster was entirely about <em>#weddings, #celebrations</em> and <em>#parties</em></li></ul><h4>Conclusion &amp; Applications</h4><p>This approach has shown that graph theory can be a very intuitive and useful way to explore social media metadata such as hashtags. Its application could be in two immediate areas:</p><p>1. We might want to graph thematic entities e.g people posting about sustainability, Brexit, Coronavirus</p><p>2. We could use graphs to model and understand the conversation around specific brands, events and places</p><p><em>(We need to bear in mind the nature of content on Instagram as this will guide what could be a suitable application)</em></p><p>All code for the functionality to replicate this task can be found on my GitHub:</p><p><a href="https://github.com/kitsamho/Instagram_Scraper_Graph">kitsamho/Instagram_Scraper_Graph</a></p><h3>Contents</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*C5wiJF8Kz3GxNVZT" /><figcaption>Photo by <a href="https://unsplash.com/@joannakosinska?utm_source=medium&amp;utm_medium=referral">Joanna Kosinska</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>1) Background &amp; Context</h4><ul><li>Instagram is huge</li><li>Hashtag culture: making life easier for a Data Scientist!</li><li>A picture is worth a thousand words ….or a handful of hashtags?</li><li>What does ‘happiness’ mean to people on Instagram?</li></ul><h4>2) Network Science &amp; Graph Theory</h4><ul><li>What is a Graph?</li><li>What aspects of Graph Theory can we use in our analysis?</li><li>Further Reading on Graphs</li></ul><h4>3) Building Functionality in Python</h4><ul><li>Search for hashtags on Instagram using Selenium WebDriver</li><li>Capture unique Instagram URL’s</li><li>Parse hashtags and other content from html using multi-thread processing</li><li>Feature Generation &amp; Exploratory Analysis</li><li>Data Selection</li><li>Graph Building</li><li>Visualisation / Analysis &amp; Interpretation</li></ul><h3>1) Background &amp; Context</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AjyjhYKW7Zk9OogT" /><figcaption>Photo by <a href="https://unsplash.com/@noiseporn?utm_source=medium&amp;utm_medium=referral">Noiseporn</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Instagram is huge</h3><p>Instagram began life in 2006 as a niche place for creative expression. Early adopters flocked to the app keen to share their pictures of urban graffiti, soy lattes and bowls of ramen. iPhone 1 + Instagram was a stamp of coolness — a golden era for the digitally hip.</p><p>Alas, this didn’t last. Instagram’s gentrification was inevitable and when Facebook bought Instagram in 2012, they swiftly monetised it through advertising and turned Instagram into a <a href="https://www.statista.com/statistics/271633/annual-revenue-of-instagram/">cash cow</a> of gigantic proportions.</p><p>In 2020 Instagram is no longer cool, it’s a commercial behemoth.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*r3vjQIIc51QzTBwjRAhLzQ.png" /><figcaption>Source: <a href="https://www.statista.com/statistics/253577/number-of-monthly-active-instagram-users/">https://www.statista.com/statistics/253577/number-of-monthly-active-instagram-users/</a></figcaption></figure><p>With an estimated <a href="https://instagram-press.com/our-story/"><strong>1 billion active monthly users</strong></a> and <a href="https://instagram-press.com/our-story/"><strong>500 million</strong></a> daily stories, the rise and reach of Instagram is nothing but impressive.</p><p>Subsequently, Instagram has in many ways become a reliable barometer of mainstream consumer culture and this means that it lends itself as a potentially useful tool to find stuff out about people.</p><p>Whilst it would be reasonable to assume that Instagram’s images and videos would be the primary ‘go-to’ sources of data, I’ve found that <strong>analysing Instagram’s hashtag culture</strong> is a more fruitful way to get under the skin of themes and topics that occur on Instagram. Coupled with analytical techniques borrowed from Network Science means that the relationships between themes and topics can be more easily understood.</p><h3>Hashtag culture: making life easier for a Data Scientist!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HRr2bgGan9WcEdDW" /><figcaption>Photo by <a href="https://unsplash.com/@brina_blum?utm_source=medium&amp;utm_medium=referral">Brina Blum</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>One of the more important parts of a Data Scientist’s job is being able to commit the time to ensure that our data is fit for purpose and this involves thorough cleaning of our data. This can take up a lot of time, especially with social media data that tends to be extremely <strong>unstructured</strong> and frequently littered with ‘noise’.</p><blockquote>Without sufficient pre-processing, the natural language processing techniques we use with social media data can lead to outputs that are hard to interpret and light on insight.</blockquote><p>There are various methods we can use to clean and organise the raw language we find on social media but it’s made infinitely easier when users do it for us. <strong>Hashtag culture on Instagram — </strong>which by its very nature is organised, normalised and less noisy — is a cultural phenomenon that does all this hard work for us.</p><h3><strong>A picture is worth a thousand words ….or a handful of hashtags?</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xEswnCMN6Kn3FTxc" /><figcaption>Photo by <a href="https://unsplash.com/@gpthree?utm_source=medium&amp;utm_medium=referral">George Pagan III</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote><a href="https://en.wikipedia.org/wiki/Hashtag">“A <strong>hashtag</strong> — introduced by the octothorpe symbol (#) — is a type of metadata tag used on social networks such as Twitter and other microblogging services. It lets users apply dynamic, user-generated tagging that helps other users easily find messages with a specific theme or content”</a></blockquote><p>People often end an Instagram post with a series of hashtags. Hashtags can provide a succinct summary of what that person was thinking, feeling and observing in that moment. Hashtags provide context and meaning that the image alone is unable to.</p><p>Let’s find an example to illustrate this.</p><h3>What does ‘happiness’ mean to people on Instagram?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lGBQdNfBvr0bglIx" /><figcaption>Photo by <a href="https://unsplash.com/@timmossholder?utm_source=medium&amp;utm_medium=referral">Tim Mossholder</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Social media is increasingly likely to get bashed as being something that makes people miserable….and sadly there is truth in this.</p><p>Let’s be contrarian, flip this truth and explore <strong>HAPPINESS</strong> on Instagram.</p><p>The following Instagram post contains <strong>#happiness</strong> in the body of the post. What can we interpret from this post by the image alone?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*dn1KxEQW-VeYMKfIPHTMEQ.png" /><figcaption><a href="https://www.instagram.com/thatdesivegangal/">https://www.instagram.com/thatdesivegangal/</a> — public post containing #happiness</figcaption></figure><p>Not much. Maybe something to do with music?</p><p>Other than the obvious there is little to go on from the image alone. What else were they thinking/feeling when they posted this?</p><p>Now when we look at all the hashtags this person made <strong>alongside</strong> their post, we learn a lot more about this person and what they associated with <strong>#happiness </strong>at that moment in time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0G8fhkhcypW0uwVbZxvJcg.png" /><figcaption><a href="https://www.instagram.com/thatdesivegangal/">https://www.instagram.com/thatdesivegangal/</a> — public post containing #happiness</figcaption></figure><p>For this person, happiness has an association with positivity, motivation, change and weight loss.</p><blockquote><strong>Whilst Instagram images can tell us something, the hashtags people use tell us </strong>considerably<strong> more</strong>.</blockquote><h4>Scaling up the hashtag analysis</h4><p>Now, this is just one Instagram post containing <strong>#happiness</strong>. What happens when we look at the surrounding hashtags for other people’s posts mentioning <strong>#happiness?</strong></p><p>What happens if we scale this analysis up and look at <em>thousands upon thousands </em>of posts containing <strong>#happiness</strong>?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P3YhJnARZG9TCElVturnow.png" /><figcaption>Instagram posts all containing #happiness</figcaption></figure><p>Pretty soon we would be in a position where we have a vast number of hashtags to navigate. What scalable approach will allow us to make sense of all this data?</p><p>This is where we can use <strong>Network Science and Graph Theory </strong>to help us.</p><h3>2) Network Science &amp; Graph Theory</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fn_D-Ke-WNVtx0FJ" /><figcaption>Photo by <a href="https://unsplash.com/@dulgier?utm_source=medium&amp;utm_medium=referral">Anastasia Dulgier</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote><a href="http://tuvalu.santafe.edu/~aaronc/courses/5352/">Network science is a thriving and increasingly important cross-disciplinary domain that focuses on the representation, analysis and modelling of complex social, biological and technological systems as networks or graphs</a>”</blockquote><p>Source: <a href="http://tuvalu.santafe.edu/~aaronc/courses/5352/">http://tuvalu.santafe.edu/~aaronc/courses/5352/</a></p><p>I like to think of Network Science and graph theory as methods that allow us to understand <strong>how things are connected. </strong>We can borrow some basic principles from Network Science and graph theory to understand <strong>how hashtags on Instagram are connected.</strong></p><p>The subject matter relating to Network Science and graph theory is incredibly dense and would take a very long time to cover. This would distract from the practical focus of the project. There are however some simple but fundamental concepts that need explaining.</p><h3>What is a Graph?</h3><p>A <strong>graph</strong> <strong><em>(G)</em> </strong>is the abstract representation of a network. Graphs are made up of <strong>vertices <em>(V) </em></strong>and<strong><em> edges (E) </em></strong>where<strong><em> 𝐺=(𝑉,𝐸)</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*Y4g2Qtdg0q91snzDZjSnoA.jpeg" /><figcaption>Source: <a href="https://www.computerhope.com/jargon/n/node.htm">https://www.computerhope.com/jargon/n/node.htm</a></figcaption></figure><ul><li><strong>Nodes <em>(V) </em></strong>in a graph represent the unique data points that exist in our data. In the case of hashtag analysis, it makes sense for hashtags to represent the nodes in our network. So if our <strong>#happiness</strong> dataset only had two hashtags — <strong>#A </strong>and <strong>#B</strong> we would have two nodes</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*clrFQMF5VdlqT0L2-8na4w.png" /><figcaption>Two nodes representing two hashtags</figcaption></figure><ul><li><strong>Edges <em>(E)</em> </strong>are connections that represent some kind of relationship between nodes. In the case of analysing hashtags, it might make sense to represent this relationship as some kind of occurrence i.e. if the hashtag <strong>#A</strong> was mentioned in the <strong>same</strong> post as #<strong>B</strong>, we would assume that there is a relationship between <strong>#A</strong> and <strong>#B</strong> and therefore we would <strong>create an edge </strong>between these two nodes</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PXn9zTCjLaknjaM7cFAFRA.png" /><figcaption>An edge is formed between two hashtags if they are mentioned together in the same post</figcaption></figure><p>As we add hashtags from other posts to the graph and model their relationships with all previous posts we begin to see structure form.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vIunYLOk_pf6T31eondLFQ.png" /><figcaption>As more hashtags are added to the graph and we see where there are connections, we can begin to see structure form</figcaption></figure><h3>What aspects of Graph Theory can we use in our analysis?</h3><ul><li><strong>Community Detection</strong>. We can use algorithms to identify and label <strong>clusters of topics/themes</strong> that are associated with <strong>#happiness. </strong>In this example we have 14 hashtags, all connected in various ways but with distinct clusters forming.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X4KX46aL7RZoZtsD3bwsOw.png" /><figcaption>Identifying communities of hashtags in the graph</figcaption></figure><ul><li><strong>Degree Centrality / Betweenness Centrality. </strong>We can calculate what hashtags in the network are particularly <strong>important</strong> in linking the whole network. Much like Heathrow Airport links up a lot of the world, what hashtags link up the <strong>#happiness </strong>‘landscape’?</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S0kNEDN33HBOGnTDG4tAVw.png" /><figcaption>Identifying which hashtags have a central role in the graph</figcaption></figure><ul><li><strong>Visualisation. </strong>If we plot the network using scatterplots, it’s a very compelling way to <strong>visualise a huge amount of information</strong> about <strong>#happiness</strong> that would be cumbersome to do otherwise</li></ul><h3>Further Reading on Graphs</h3><p><a href="https://medium.com/u/ddcee06de4c8"><em>Maël Fabien</em></a><em> has written a whole series which covers the content around graph theory really well. I strongly recommend you have a read of this at some point if you find this topic interesting.</em></p><p><a href="https://towardsdatascience.com/introduction-to-graphs-part-1-2de6cda8c5a5">Introduction to Graphs (Part 1)</a></p><p>Let’s now look at the practical steps we need to take to build our network.</p><h3>3) Building Functionality in Python</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kFsaWG5Arqgqqk_Z" /><figcaption>Photo by <a href="https://unsplash.com/@ikukevk?utm_source=medium&amp;utm_medium=referral">Kevin Ku</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I have built two Python classes that handle all the processes needed to go from capturing the data all the way through to building, visualising and analysing the <strong>#Happiness</strong> graph. The key pipelines within each class are outlined below.</p><pre><strong>class InstagramScraper()</strong></pre><ul><li><strong>Search for hashtags on Instagram using Selenium WebDriver</strong></li><li><strong>Capture unique Instagram URL’s</strong></li><li><strong>Parse hashtags and other content from post html using multi-thread processing</strong></li></ul><pre><strong>class InstagramGraph()</strong></pre><ul><li><strong>Feature generation &amp; exploratory analysis</strong></li><li><strong>Data selection</strong></li><li><strong>Graph building</strong></li><li><strong>Visualisation</strong></li></ul><p>You can access the full code for these classes and their relevant readme documentation here:</p><p><a href="https://github.com/kitsamho/Instagram_Scraper_Graph">https://github.com/kitsamho/Instagram_Scraper_Graph</a></p><h3>class InstagramScraper()</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N4ZNL18TtZ1ogq5-zDIDWA.jpeg" /><figcaption>Source: <a href="https://hackernoon.com/how-to-scrape-a-website-without-getting-blacklisted-271a605a0d94">https://hackernoon.com/how-to-scrape-a-website-without-getting-blacklisted-271a605a0d94</a></figcaption></figure><pre><strong>class InstagramScraper()</strong></pre><ul><li><strong>Search for hashtags on Instagram using Selenium WebDriver</strong></li><li><strong>Capture unique Instagram URL’s</strong></li><li><strong>Parse hashtags and other content from html using multi-thread processing</strong></li></ul><p>This stage uses a combination of automated web browsing and html parsing to scrape content from Instagram posts. I have built a custom Python class <em>InstagramScraper t</em>hat contains a pipeline of scraping and data extraction methods that returns a Pandas DataFrame of scraped Instagram data.</p><p>I will walk you through the main processes below with a few example code blocks to highlight the main steps involved.</p><h4>Search for hashtags on Instagram using Selenium WebDriver</h4><p>There is functionality on Instagram where a user can search for specific hashtags and Instagram returns all the posts that contain that hashtag. This is our first step in getting the data we need; get Instagram to do the work for us using <a href="https://chromedriver.chromium.org/downloads">Selenium webdriver</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Of7PAzO-7aLkd-oZSz4CEg.png" /><figcaption>Search for Instagram posts containing #Happiness hashtags on Instagram</figcaption></figure><h4>Capture unique Instagram URL’s</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*syoNuc2yS_FvPHJsuFoYNw.png" /><figcaption>Use Selenium WebDriver to capture unique Instagram URLs</figcaption></figure><p>Every post on Instagram has its own <strong>unique URL</strong>. After we have searched for all the posts containing a specific hashtag, the first step is to capture all of these unique URL’s for posts that contain that hashtag.</p><p>I found the best way to do this is through using a combination of Selenium WebDriver and parsing the html on the fly, extracting each posts href attributes to a data structure as we scroll through all the content.</p><p>As this part of the Instagram site is highly dynamic requiring consistent scrolling to load new images, using some kind of browser based automation such as Selenium WebDriver is the only feasible way of capturing the data. This means it can take a little while to get all the links.</p><h4>Capture unique Instagram URL’s — Example Code</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87f892ae4f468691d236b02ca78ecb6e/href">https://medium.com/media/87f892ae4f468691d236b02ca78ecb6e/href</a></iframe><h4>Parse hashtags and other content</h4><p>Once you have a list of all the links, you can then use a combination of <strong>urlopen</strong> and html parsing (I use <strong>Beautiful Soup</strong>) to get the data for each Instagram post.</p><p>Once you have the html for each post and parse its content, you will find that data for Instagram posts has a consistent structure resembling a dictionary / JSON style format</p><h4>Parsing hashtags and other content — Example Code</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/677cd8c7fb66b6f450a83cc432484f86/href">https://medium.com/media/677cd8c7fb66b6f450a83cc432484f86/href</a></iframe><h3><em>InstagramScraper</em> Output</h3><p>The main output of the <em>InstagramScraper</em> class is a Pandas DataFrame containing a host of variables by post.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AivEUt5pqODcBYodln7f6w.png" /><figcaption>Pandas DataFrame output from InstagramScraper class</figcaption></figure><p>Most of these variables are self explanatory and offer all kinds of options for exploratory analysis beyond hashtags.</p><p>Now that we have our scraped data and have a nice and tidy Pandas DataFrame we can begin to think about processing our data in preparation for building our network and visualising our graph, which is where things get really fun.</p><h3>class InstagramGraph()</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*azUZIv_Ugeuj4TEYtfJsBw.png" /><figcaption>Source: <a href="https://techcrunch.com/wp-content/uploads/2017/12/instagram-hashtags.png?w=730&amp;crop=1">https://techcrunch.com/wp-content/uploads/2017/12/instagram-hashtags.png?w=730&amp;crop=1</a></figcaption></figure><p>I have built a second python class called <em>InstagramGraph </em>which also contains a pipeline of methods that allow you to analyse an Instagram dataset and ultimately model the hashtag data as an instance of a NetworkX graph object using Plotly visualisations.</p><pre><strong>class InstagramGraph()</strong></pre><p>The key processes within this class are:</p><ul><li><strong>Feature Generation &amp; Exploratory Analysis</strong></li><li><strong>Data Selection</strong></li><li><strong>Graph Building</strong></li><li><strong>Visualisation / Analysis &amp; Interpretation</strong></li></ul><h3><strong>Feature Creation &amp; Exploratory Analysis</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jQtWGOjI3dWQv-V9" /><figcaption>Photo by <a href="https://unsplash.com/@madebyvadim?utm_source=medium&amp;utm_medium=referral">Vadim Sherbakov</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The code block below outlines a pipeline from the <em>InstagramGraph</em> class which contains a suite of methods that create new features in our data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1fc9a0c1bf263b7eb6f5fda43dfb476/href">https://medium.com/media/a1fc9a0c1bf263b7eb6f5fda43dfb476/href</a></iframe><p>There are several methods here, some are linguistic (e.g. determining the language of a post) although most of the processes within this method generate extra descriptive metrics such as median post count by user, total hashtag count by post and median hashtag use by user.</p><p>Whilst some of these new features/metrics aren’t directly related to graph building it’s alway worth generating more data points where you can as it offers a chance to do some exploratory analysis of the subject matter which might provide more context about what our graph model reveals. It also might inspire some other ideas for analysis that you hadn’t initially considered.</p><p>Let’s explore some of these.</p><h4>Language</h4><p>The <a href="https://pypi.org/project/langdetect/">langdetect</a> library in Python allows us to access the Google Translation library over an API and gives us the ability to identify language in our text.</p><p><strong><em>Note — due to a limit on Google Cloud API requests this can run quite slow when processing a large volume of data. For the purposes of example, this is fine; if you want to productionise this you may want to think about a faster alternative and consider paying.</em></strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplot.ly%2F%7Ekitsamho%2F146.embed%3Fautosize%3Dtrue&amp;display_name=Plotly&amp;url=https%3A%2F%2Fplot.ly%2F%7Ekitsamho%2F146%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=plot" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/47c7dc04512b6a2fb9c77df0c3d4a05f/href">https://medium.com/media/47c7dc04512b6a2fb9c77df0c3d4a05f/href</a></iframe><p>As we can see the majority of the Instagram posts for <strong>#happiness</strong> are in English — over 80% of our data set.</p><h4>User Post Frequency</h4><p>A look at some distributions show that the data on user post frequency is extremely positively skewed; there are handful of outlier accounts that post very frequently (up to 140 times) whereas the majority of posters are posting only once.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplot.ly%2F%7Ekitsamho%2F148.embed%3Fautosize%3Dtrue&amp;display_name=Plotly&amp;url=https%3A%2F%2Fplot.ly%2F%7Ekitsamho%2F148%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=plot" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/9866f713f4bf18b6a0041ae73328fc47/href">https://medium.com/media/9866f713f4bf18b6a0041ae73328fc47/href</a></iframe><h4><strong>Extracting Hashtags</strong></h4><p>To extract our hashtags I have created two methods that do the job for us. One method takes a string input and returns a list of hashtags. If people have failed to include a space between their string of hashtags, the code can account for this and ‘unpack’ them into individual hashtags.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c0d2b4c72a341cf0c16d113e29d884a/href">https://medium.com/media/8c0d2b4c72a341cf0c16d113e29d884a/href</a></iframe><h4>Analysis</h4><p>Analysis of hashtag frequency by post indicates that whilst frequency by post tends to follow a <em>uniform distribution</em> , there are some outlier posts that contain an unusually high number of hashtags. Further exploration shows that this partially seems to be driven by people who have posted multiple times across the dataset (high frequency posters). So <em>broadly</em> <em>speaking</em>, those that post more often also tend to use more hashtags in their posts.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplot.ly%2F%7Ekitsamho%2F150.embed%3Fautosize%3Dtrue&amp;display_name=Plotly&amp;url=https%3A%2F%2Fplot.ly%2F%7Ekitsamho%2F150%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=plot" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/db807e2581863e9d59b2d7984b7da580/href">https://medium.com/media/db807e2581863e9d59b2d7984b7da580/href</a></iframe><h4>Lemmatising Hashtags</h4><p>A second method then takes this list of hashtags and looks to <strong>lemmatise</strong> the input, where appropriate. For those unfamiliar with lemmatisation, this is the process where we can reduce a word to its root lexical form. For instance if we have the hashtags <strong>#happiest</strong> and <strong>#happier</strong> — these are both inflections of the verb <strong>#happy.</strong> Therefore lemmatisation reduces these inflections back to <strong>#happy. </strong>I’ve used an instance of a spaCy model to perform the lemmatisation.</p><h4>Lemmatising Hashtags — Example Code</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c804c01096af8b2e94cae88ba64f120/href">https://medium.com/media/6c804c01096af8b2e94cae88ba64f120/href</a></iframe><h3>Data Selection</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SQl3lPclPbGLe1_x" /><figcaption>Photo by <a href="https://unsplash.com/@victoriano?utm_source=medium&amp;utm_medium=referral">Victoriano Izquierdo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Ok, so the next step is to select the data we want to model. The code outlines a pipeline from the <em>InstagramGraph</em> class which contains a suite of methods that allow us to <strong>select</strong> the data we want.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc8a0abc48ba2bb4f50580266a2d2574/href">https://medium.com/media/fc8a0abc48ba2bb4f50580266a2d2574/href</a></iframe><h4>Select Language</h4><p>Whilst Instagram is an international platform, for simplicity we might want to consider filtering out non-English posts. As we saw previously, over 80% of the data for <strong>#happiness</strong> is in English so it makes sense to focus on this subset of the data.</p><h4>Removing verified users</h4><p>Verified users tend to be either brands, celebrities or online shops i.e. ‘people’ who likely don’t represent the average Instagram user. Depending on your objectives for this analysis, you might want to consider removing verified users from your data.</p><h4>Removing high frequency posters</h4><p>A cursory inspection of high frequency posters reveals that these are sometimes unverified accounts that are using Instagram to sell stuff under a non-verified status. Do we feel this represents that audience we are interested in understanding? If so we can leave them in, if not — we can filter them out prior to building our graph.</p><h4>Use lemmatised hashtags?</h4><p>I thought it made sense to have the option to lemmatise the scraped hashtags where possible as it reduces the amount of data needed to build the graph — we don’t necessarily need all that extra data.</p><h3><strong>Graph Building</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fBoEMJVthMsbsFRq" /><figcaption>Photo by <a href="https://unsplash.com/@randyfath?utm_source=medium&amp;utm_medium=referral">Randy Fath</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Now that we we have selected the data we want to model, we can build the graph. The pipeline we use for this is below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11c13484178eaaaaf73e2fc5dd4b8331/href">https://medium.com/media/11c13484178eaaaaf73e2fc5dd4b8331/href</a></iframe><p>There are <strong>three</strong> main processes that take place in this pipeline:</p><h3>Compile a list of lists</h3><p>This simply extracts hashtags from our DataFrame into a list of lists — each sub-list representing a post from our <strong>#Happiness</strong> data set. By having the input as a simple list of lists, we can easily re-purpose this graph building approach to other sources of data in future where we can wrangle the raw data in a similarly structured / list of list format</p><h4><em>Compile a list of lists — Example Code</em></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4b9c7eee588f84641f21bd81bbd945f/href">https://medium.com/media/e4b9c7eee588f84641f21bd81bbd945f/href</a></iframe><h4>Compile a list of lists — Example Output</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cbtr7ppRQNj5nujbjlZsug.png" /><figcaption>Extract a list of lists from a series of hashtags</figcaption></figure><h3>Identify edges and nodes</h3><p>The next step is to take our list of lists and use this to generate the nodes and edges that exist across the entire data set. Remember the nodes are the unique hashtags in the dataset and an edge is created if any two hashtags are mentioned together in the same post.</p><h4>Identify edges and nodes — Example Code</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f525f3ad07e83f317aaf1de7fbc2d18/href">https://medium.com/media/6f525f3ad07e83f317aaf1de7fbc2d18/href</a></iframe><h4>Identify edges and nodes — Example Output</h4><p>The method saves two generated DataFrames as attributes — a DataFrame containing all the nodes and a DataFrame containing all the edges.</p><h4>Node DataFrame</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kssuXeQLV8XNgJtkAiLjXQ.png" /><figcaption>The node DataFrame — each row represents a unique hashtag that exists in #Happiness dataset</figcaption></figure><h4><strong>Edge DataFrame</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-ZFxanJESNLQ3CKIctb5Aw.png" /><figcaption>The edge DataFrame — each row represents a unique edge that exists in the #Happiness dataset. Edge frequency is a count of how many times that pairing exists in the #Happiness dataset</figcaption></figure><h3>Build the graph</h3><p>The next stage is to add these nodes and edges into an instance of a NetworkX graph object (G).</p><h4>Build the graph — Example Code</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f7ce67b2b4106f25e015c919dafb062/href">https://medium.com/media/9f7ce67b2b4106f25e015c919dafb062/href</a></iframe><h4>Build the graph — Example Output</h4><p>Once we have created our NetworkX graph object — we can then use various calculated graph attributes to enhance our node data even further.</p><ul><li><strong>Betweeness Centrality</strong></li><li><strong>Adjacency Frequency</strong></li><li><strong>Clustering Coefficient</strong></li><li><strong>Community</strong></li></ul><h4><strong>Node DataFrame Enhanced with Graph Attributes</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g6ClJzDyqyM7DnfPH4YxPw.png" /><figcaption>Node DataFrame enhanced with new metrics from NetworkX</figcaption></figure><h3><strong>Visualisation</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9QaGpd3Iab6qt7Ux" /><figcaption>Photo by <a href="https://unsplash.com/@russn_fckr?utm_source=medium&amp;utm_medium=referral">russn_fckr</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Now we have an instance of a NetworkX graph object that has been built with our node and edge data that we extracted from our <strong>#Happiness</strong> dataset.</p><h4><strong>Graph Plot</strong></h4><p>We can now use Plotly to visualise the hashtag graph as a connected scatter plot.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f65b8c23a598098738809de56d6a80e5/href">https://medium.com/media/f65b8c23a598098738809de56d6a80e5/href</a></iframe><p>There are a few arguments that I have set up that allow for a degree of customisation to the visualisation.</p><pre><strong>def plotGraph</strong>(node_size=’adjacency_frequency’,colorscale=’Viridis’)</pre><p>I think it makes sense to use node size to convey some other variable — the default is ‘adjacency_frequency’ i.e. how many other nodes a node has edge connections with. In this instance a smaller node would represent a hashtag with fewer edges and contrastingly a larger node would have more edges. We can emphasise this point even further by applying a colour scale that is correlated with node size.</p><pre><strong>def plotGraph</strong>(layout=nx.kamada_kawai_layout)</pre><p>NetworkX has a few different graph layouts. The <strong>kamada kawai layout</strong> arranges nodes in a way so that there are as few overlapping edges as possible. Therefore this has a tendency for the nodes to be arranged in a way that conveys clusters …but most importantly tends to be the easiest layout to interpret. There are alternatives such as the <strong>circular layout </strong>or <strong>random layout </strong>but these are harder to make sense of in my experience.</p><pre><strong>def plotGraph</strong>(light_theme=True)</pre><p>There are two colour themes, light and dark.</p><h3>Call the plotGraph function…</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplot.ly%2F%7Ekitsamho%2F161.embed%3Fautosize%3Dtrue&amp;display_name=Plotly&amp;url=https%3A%2F%2Fplot.ly%2F%7Ekitsamho%2F161%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=plot" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/cee96403b3d3d2d2d2bd2a67f618235f/href">https://medium.com/media/cee96403b3d3d2d2d2bd2a67f618235f/href</a></iframe><p>We can see quite easily how there are several well connected hashtags in the <strong>#happiness</strong> graph(hashtags that have more node connections). <strong>Smile</strong>, <strong>life</strong>, <strong>family</strong>, <strong>motivation, party</strong>…these are all hashtags that are frequently mentioned across the network.</p><p>As we can see, the force directed layout has a tendency to push groups of hashtags together that are well connected . If we plot the graph again but colour nodes using their community label we can better visualise how communities fall out.</p><pre><strong>def plotGraph(</strong>community_plot=True)</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplot.ly%2F%7Ekitsamho%2F142.embed%3Fautosize%3Dtrue&amp;display_name=Plotly&amp;url=https%3A%2F%2Fplot.ly%2F%7Ekitsamho%2F142%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=plot" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa430e013fa5b8bd1663069c961131f4/href">https://medium.com/media/aa430e013fa5b8bd1663069c961131f4/href</a></iframe><h4>Sunburst Plot</h4><p>There seems to be three easily identifiable communities in the <strong>#happiness</strong> network. We can explore which specific hashtags contribute to each of the communities using sunburst visualisations. Click on the wheel to interact with the clusters.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplot.ly%2F%7Ekitsamho%2F159.embed%3Fautosize%3Dtrue&amp;display_name=Plotly&amp;url=https%3A%2F%2Fplot.ly%2F%7Ekitsamho%2F159%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=plot" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/d503ec661b64bc730976d10d3e7dad2a/href">https://medium.com/media/d503ec661b64bc730976d10d3e7dad2a/href</a></iframe><p>Community detection identified three clusters interpreted as:</p><ul><li>Aspects of happiness that seem to be about what people <strong>do and experience </strong>(e.g. ‘<em>#photography</em>, <em>#summer,</em> <em>#travel</em>,<em>#family</em> ) (Segment 0)</li><li>Aspects of happiness that broadly seem to be about how people <strong>think and feel</strong> (e.g <em>#life</em>, <em>#motivation</em>, <em>#inspiration, #quotes</em>) (Segment 1)</li><li>A third very distinct cluster was entirely about <em>#weddings, #celebrations</em> and <em>#parties </em>(Segment 3)</li></ul><h3>Closing Notes</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BX7CQIaAjUI_Ghby" /><figcaption>Photo by <a href="https://unsplash.com/@belart84?utm_source=medium&amp;utm_medium=referral">Artem Beliaikin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I hope you enjoyed this practical walk through on how to extract hashtag data from Instagram and analyse it using principles borrowed from Network Science.</p><p>My main aims with this project were:</p><ol><li>To try and demonstrate that there is an abundance of accessible and potentially insightful content buried in social media data.</li><li>To show you that there are almost always interesting patterns in places you might not have expected</li></ol><p>I chose <strong>#happiness </strong>as a case study because hopefully this is something that we can all relate to. However the code works for any hashtag. As long as you can gather sufficient volumes of data to model — there are observable relationships for anything. You could consider brands, places, events and even people.</p><p>You don’t even need to use Instagram; the code can easily be repurposed to use all kinds of meta data beyond Instagram….Twitter, LinkedIn even TikTok could be a possibility.</p><p>As I mentioned before, the code is available on my <a href="https://github.com/kitsamho/Instagram_Scraper_Graph">GitHub</a> so please feel free to <strong>take</strong>, <strong>use,</strong> <strong>evolve</strong> and<strong> improve</strong>. I’d love to see what people do with this.</p><p>Until next time! 🚀</p><p>Cheers <br>Sam</p><h3>References &amp; Links</h3><ul><li>My GitHub: <a href="https://github.com/kitsamho/Instagram_Scraper_Graph">https://github.com/kitsamho/Instagram_Scraper_Graph</a></li><li>Introduction to Graphs by Maël Fabien: <a href="https://maelfabien.github.io/machinelearning/graph_1/#">https://maelfabien.github.io/machinelearning/graph_1/#</a></li><li>Instagram: <a href="https://www.instagram.com/">https://www.instagram.com</a></li><li>Selenium WebDriver: <a href="https://chromedriver.chromium.org/downloads">https://chromedriver.chromium.org/downloads</a></li><li>Beautiful Soup : <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/">https://www.crummy.com/software/BeautifulSoup/bs4/doc/</a></li><li>NetworkX : <a href="https://networkx.github.io/documentation/stable/">https://networkx.github.io/documentation/stable/</a></li><li>Plotly: <a href="https://plot.ly/python/">https://plot.ly/python/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f7917078e0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/using-network-science-to-explore-hashtag-culture-on-instagram-1f7917078e0">Using Network Science to explore hashtag culture on Instagram</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>