<?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 Siena Duplan on Medium]]></title>
        <description><![CDATA[Stories by Siena Duplan on Medium]]></description>
        <link>https://medium.com/@sienaduplan?source=rss-da2b12dafd38------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*3JwDeXPPVhmiScwWac0ViQ.jpeg</url>
            <title>Stories by Siena Duplan on Medium</title>
            <link>https://medium.com/@sienaduplan?source=rss-da2b12dafd38------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 11:50:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sienaduplan/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[LLM-Powered Topic Modeling]]></title>
            <link>https://sienaduplan.medium.com/llm-powered-topic-modeling-fdd1de8e4c1d?source=rss-da2b12dafd38------2</link>
            <guid isPermaLink="false">https://medium.com/p/fdd1de8e4c1d</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[topic-modeling]]></category>
            <dc:creator><![CDATA[Siena Duplan]]></dc:creator>
            <pubDate>Thu, 26 Sep 2024 22:33:28 GMT</pubDate>
            <atom:updated>2024-09-26T22:33:28.104Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*eKkNp7YE3EsbGRdkHCGkxQ.png" /><figcaption>DALL-E 3 generated representation of an embedding space (prompt in footnote¹)</figcaption></figure><p>Before Large Language Models (LLMs), data scientists like myself relied on what now feels like primitive techniques to perform Natural Language Processing (NLP) on text data. As recently as 2019, I was using guided-LDA models to extract topics from large unstructured text data. Maybe you wouldn’t call a guided-LDA AI now, but it seemed pretty smart back then.</p><p>While LDA (Latent Dirichlet Allocation) still has its place, in this post, I’ll share how I recently updated my approach and significantly improved my outcomes in topic modeling with LLMs.</p><p>The LLM-powered approach to topic modeling follows this basic recipe:</p><ol><li><strong>Ingest and clean data</strong></li><li><strong>Generate text embeddings</strong></li><li><strong>Dimensionality reduction</strong></li><li><strong>Clustering</strong></li><li><strong>Extract representative documents</strong></li><li><strong>Label clusters with an LLM, passing in only representative docs</strong></li><li><strong>Review / Reinforce / Repeat</strong></li><li><strong>Weighted Log-Odds</strong></li></ol><p>Let’s go into more detail and code for each step.</p><h3>1. Ingest and Clean Data</h3><p>Begin pre-processing your text data to remove noise and add consistency. Typically in this step, I will perform Exploratory Data Analysis (EDA) with some of the following techniques and tips:</p><ul><li><strong>Missing Data Detection: </strong>It’s an unwritten rule of data science that your dataset will always have at least one “#NAME?” value.</li><li><strong>Duplicate Detection: </strong>Decide which instance you want to keep or merge.</li><li><strong>Outlier Detection: </strong>Check across all your columns and decide how to handle.</li><li><strong>Normalization:</strong> Standardize text by converting all to lowercase, removing punctuation or stop-words, expanding contractions, and applying stemming or lemmatization, tokenization, etc.</li><li><strong>Translation: </strong>Use<strong> </strong>langdetect + googletrans packages for free language detection, labeling, and translation rather than costly LLM API calls.</li><li><strong>Summarization:</strong> Simple statistical methods like 5-number summaries on numeric data or word counting on text data.</li><li><strong>Visualization:</strong> Histograms for numeric columns, bar charts for discrete data.</li></ul><p>At this stage, I also perform some simpler NLP tasks that will be useful when paired with the topic model output:</p><ul><li><strong>Sentiment Analysis:</strong> VADER scoring for sentiment</li><li><strong>Flesch-Kincaid:</strong> scoring for readability</li><li><strong>Discretization:</strong> Convert continuous values into discrete categories like “positive”, “neutral”, “negative”</li><li><strong>Visualization:</strong> Word clouds are good despite popular opinion, and likert plots are well-suited for discrete sentiment values</li></ul><h3>2. Generate Text Embeddings</h3><p>The script below processes large data in chunks or batches to prevent overload. The main loop fetches vector embeddings for each batch and handles any errors that occur during the API calls. If using the OpenAI API, it can go down frequently so you will want to save any embeddings for the chunk you are processing <em>before</em> hitting this snag. When the API crashes, waiting a minute before retrying usually works. Power naps are all you need!</p><pre>## embedding.py ##<br><br>from datetime import datetime<br>import logging<br>import os<br>import sys<br>import time<br><br>from dotenv import load_dotenv<br>import openai<br>import swifter<br>import numpy as np<br><br>logging.basicConfig(format=&#39;%(asctime)s: %(levelname)s: %(message)s&#39;, level=logging.INFO)<br><br>CURRENT_DIR = os.getcwd()<br>PROJECT_ROOT = os.path.abspath(os.path.join(CURRENT_DIR,&#39;..&#39;))<br>sys.path.append(PROJECT_ROOT)<br><br># Batch size for processing data in chunks<br>BATCH_SIZE = 1000<br><br><br>def load_openai():<br>    load_dotenv()<br>    openai.api_key = os.environ[&quot;OPENAI_KEY&quot;] # YOUR OpenAI key<br><br><br>def get_embedding(text) -&gt; list:<br>    default = []<br>    response = openai.Embedding.create(<br>        model = &quot;text-embedding-3-large&quot;, # most recent embedding model as of this writing<br>        input = str(text),<br>        n = 1,<br>        stop = None,<br>        temperature = 0, # deteministic output<br>    )<br><br>    if not response:<br>        return default<br>    return response.get(&#39;data&#39;, [{}])[0].get(&#39;embedding&#39;, default)<br><br><br>load_openai()<br><br># Process dataset in chunks to get embeddings<br>def run():<br>    formatted_datetime = datetime.now().strftime(&quot;%d_%b_%Y_%H_%M_%S&quot;)<br>    df = &quot;data.csv&quot; # YOUR data<br>    n = len(df)<br>    df[&#39;embedding&#39;] = np.nan<br><br>    df_start = 0<br>    while df_start &lt; n:<br>        sleep = False<br>        <br>        # Get subset of df for current batch<br>        # Filter rows without embeddings<br>        df_intermediate = df[df_start:df_start + BATCH_SIZE].loc[df[&#39;embedding&#39;].isnull()]<br>        unprocessed_rows = len(df_intermediate)<br>        <br>        while unprocessed_rows:<br>            logging.info(f&quot;Running embeddings on {unprocessed_rows} rows&quot;)<br>            try:<br>                # Apply get_embedding function on column of text data<br>                df_intermediate[&quot;embedding&quot;] = df_intermediate[&quot;TEXT&quot;].swifter.apply(<br>                    get_embedding, axis=1<br>                )<br>                df[&#39;embedding&#39;].loc[df_start: min(df_start + BATCH_SIZE - 1, n)] = df_intermediate[&#39;embedding&#39;]<br>            <br>            # Handle errors and sleep if necessary<br>            except openai.error.ServiceUnavailableError as exc:<br>                sleep = True<br>                logging.error(exc)<br>            except Exception as exc:<br>                logging.exception(exc)<br>            finally:<br>                unprocessed_rows = len(df_intermediate.loc[df_intermediate[&#39;embedding&#39;].isnull()])<br>                logging.info(f&quot;{unprocessed_rows} rows remaining of intermediary {df_start}&quot;)<br><br>                if sleep:<br>                    logging.error(&quot;Sleeping...&quot;)<br>                    time.sleep(60)<br>                    sleep = False<br>        <br>        # Save partially processed df to pickle file for checkpointing<br>        df.to_pickle(f&quot;../data/embeddings_partial_{df_start}_{formatted_datetime}.pkl&quot;)<br>        df_start += BATCH_SIZE<br>    <br>    # Save full df to pickle file once all batches are processed<br>    df.to_pickle(f&quot;../data/intermediate/embeddings_full_{formatted_datetime}.pkl&quot;)<br><br>run()</pre><p>The code above does the following:</p><ul><li><strong>Load OpenAI API Key:</strong> The load_openai() function loads the OpenAI API key from environment variables (OPENAI_KEY=“yourkey” stored in a .env file).</li><li><strong>Batch Processing: </strong>Processes the data in chunks of 1,000 rows.</li><li><strong>Generate Embeddings:</strong> For each batch, the get_embedding() function is called to generate embeddings using the OpenAI API and text-embedding-large-3 model.</li><li><strong>Error Handling: </strong>Handle OpenAI&#39;s ServiceUnavailableError by sleeping for 60 seconds before retrying. It will repeat this step if not resolved.</li><li><strong>Save Intermediate Results:</strong> Intermediate results are saved as pickle files to avoid data loss in case of interruptions.</li></ul><h3>3. Dimensionality Reduction</h3><p>This step is not strictly necessary for topic modeling, but it’s something a good data scientist will want to do. Visually inspecting the embedding space shows you a birds-eye view of the structure and relationships in your corpus. I enjoy this step as a <strong>visual diagnostic of my embedding model</strong>. You can quickly see if similar documents will cluster together as you expect by coloring embeddings based on other categorical features in your dataset.</p><pre>## tsne.py ##<br><br>embeddings = np.array(df[&#39;embedding&#39;].tolist())<br>categorical_var = df[&#39;categorical_var&#39;].values<br><br>tsne = TSNE(n_components=2, random_state=42)<br>embeddings_2d = tsne.fit_transform(embeddings)<br><br>CATEGORICAL_COLORS = [<br>  &quot;#a1def0&quot;,<br>  &quot;#1c5872&quot;, <br>  &quot;#ca6285&quot;,<br>  # ...add more here<br>]<br><br># Build plot<br>plt.figure(figsize=(25, 18))<br>scatter = sns.scatterplot(<br>  x=embeddings_2d[:, 0],<br>  y=embeddings_2d[:, 1],<br>  hue=categorical_var,<br>  palette=CATEGORICAL_COLORS,<br>  legend=&#39;full&#39;,<br>  alpha=0.7<br>)<br>plt.title(&#39;t-SNE Visualization of Embeddings&#39;, loc=&#39;left&#39;)<br>handles, labels = scatter.get_legend_handles_labels()<br>legend = plt.legend(handles, labels, title=&#39;Category&#39;, loc=&#39;upper left&#39;)<br><br>for lh in legend.get_lines():<br>    lh.set_alpha(1)<br><br>plt.xlabel(&#39;Dimension 1&#39;)<br>plt.ylabel(&#39;Dimension 2&#39;)<br>plt.legend(title=&#39;Category&#39;, markerscale=3)<br><br>dpi_value = 300<br>plt.savefig(<br>  f&quot;../figs/embeddings/tsne_{formatted_datetime}.png&quot;,<br>  dpi=dpi_value<br>)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aG5DcCL_KwWczsUIa4TxmQ.jpeg" /><figcaption>2-D Representation of whole corpus embeddings using t-SNE. Read more about the beauty and pitfalls of t-SNE from Google’s Martin Wattenberg, Fernanda Viegas, and Ian Johnson here: <a href="https://distill.pub/2016/misread-tsne/">https://distill.pub/2016/misread-tsne/</a></figcaption></figure><h3>4. Clustering, i.e. Topic Modeling</h3><p>I’m using a BERTopic model to cluster similar documents based on their embeddings. BERTopic uses UMAP for dimensionality reduction and HDBSCAN for clustering. BERTopic automatically labels each topic with a number and assigns documents with low topic probability to a default topic labeled “-1”. There are a few options to reduce outliers, like forcing “-1” documents to their closest neighbor by cosine similarity. In this case, I’m using topic distributions to assign outliers to the most frequent topic in each document’s distribution.</p><pre>## bertopic.py ##<br><br>from bertopic import BERTopic<br>import joblib<br>import numpy as np<br>import pandas as pd<br>from sklearn.preprocessing import normalize<br><br># Normalize embeddings and store them in a new column<br>df[&#39;embedding_normalized&#39;] = df[&#39;embedding&#39;].apply(<br>  lambda x: normalize([x], norm=&#39;l2&#39;)[0]<br>)<br>embeddings_array = np.array(df[&#39;embedding_normalized&#39;].tolist())<br>df[&#39;text&#39;] = df[&#39;text&#39;].astype(str)<br>docs = df[&#39;text&#39;].tolist()<br><br># Initialize BERTopic model<br>bertopic_model = BERTopic()<br><br># Fit model<br>topics, probs = bertopic_model.fit_transform(docs, embeddings_array)<br><br>df[&#39;topic&#39;] = topics<br>df[&#39;probs&#39;] = probs<br><br># Reduce outliers (optional)<br>new_topics = bertopic_model.reduce_outliers(<br>  docs, topics, strategy=&quot;distributions&quot;<br>)<br>df[&#39;new_topic&#39;] = new_topics<br><br># Save dataframe with topics and probabilities<br>df.to_csv(<br>  f&quot;../data/embeddings/feedback_embeddings_bertopic_{formatted_datetime}.csv&quot;,<br>  index=False<br>)<br><br># save the model for future use on unseen data<br>joblib.dump(<br>  bertopic_model,<br>  f&quot;../models/bertopic_model_{formatted_datetime}.joblib&quot;<br>)</pre><p>While on this step, here are a few built-in visualizations to explore the latent topics:</p><pre>## bertopic.py ##<br><br># Run each chunk in its own cell if in a notebook env<br><br>bertopic_model.visualize_topics() # intertopic distance map, shown below<br><br>bertopic_model.visualize_hierarchy()<br><br>hierarchical_topics = bertopic_model.hierarchical_topics(docs)<br>bertopic_model.visualize_hierarchy(hierarchical_topics=hierarchical_topics)<br><br>bertopic_model.visualize_barchart(top_n_topics=20, n_words=8, height=400, width=600)<br><br>bertopic_model.visualize_heatmap()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EJpqR1_BXxVfB6NLEspLxg.png" /></figure><h3>5. Extract Representative Documents</h3><p>I next want to extract a handful of documents per each topic because it is too costly to send every document to an LLM API. In practice, you can often send much less information to an LLM provider than you’d expect and still get high-quality results. BERTopic’s built-in get_representative_docs() selects a subset of documents that best capture the key themes of each topic. The representative documents have the highest probabilities of belonging to their respective topics, acting like the “centroids” of the topic clusters in the 2D embedding space. These are what we will send to an LLM to get nice, human-friendly labels for all of our topics.</p><pre>## bertopic.py ##<br><br># Returns { topic_number: List[str] , ...}<br>rep_docs = bertopic_model.get_representative_docs()<br><br>rep_docs_df = pd.DataFrame.from_dict(rep_docs)<br>rep_docs_df.to_csv(<br>  f&quot;../data/embeddings/representative_docs_{formatted_datetime}.csv&quot;,<br>  index=False<br>)</pre><h3>6. <strong>Label Topic Clusters with an LLM</strong></h3><p>After extracting the representative documents (rep_docs) from each cluster, the next step is to label the topic clusters. Here comes your opportunity to <a href="https://www.youtube.com/watch?v=T9aRN5JkmL8">get good at prompt engineering</a>. By sending only the rep_docs to an LLM, instead of every document in the corpus, we can drastically cut down time and cost while still getting accurate and descriptive topic labels and detailed topic descriptions.</p><p>One current limitation when making LLM calls is managing token limits. The code below tracks token count to make sure we don’t go over the model’s limit, while also formatting the input properly for the LLM.</p><p>The gen_prompt_text(input_str) function generates the formatted prompt that will be sent to the LLM for labeling and summarizing. Broadly, the function sets up some useful (and honest) context for the LLM, includes the pre-formatted input_str of rep_docs in the prompt, defines the task for the LLM to perform, handles edge cases / uncertainty, and returns the final prompt.</p><p>Here are some tips for prompt engineering:</p><ul><li><strong>Provide Context</strong>: Contrary to current popular belief, it’s unnecessary to assign roles, such as telling the model that it is an “expert in <em>x</em>”, which is misleading. I find that performance improves when I honestly describe the problem I’m solving.</li><li><strong>Communicate Clearly</strong>: Test your prompt on a human. If they can’t understand what you are trying to achieve, refine the prompt until it’s easy for them to understand.</li><li><strong>Iteration</strong>: Run tests on a small sample of your corpus and iteratively improve the prompt. In my case, it took around 30 iterations before the prompt produced consistent results, though I still had occasional encounters with hallucination and the model randomly “going rogue”. (This happened mostly with the output structure I gave the model, not the topic labels themselves.)</li><li><strong>Format for Code</strong>: Use value placeholders in your output example rather than specific instances (see below).</li><li><strong>Give the LLM an Out</strong>: Sometimes the model is not confident in its response. If it can’t confidently find a topic, give it the option to say “No topic identified”.</li><li><strong>Be Polite and Honest</strong>: It’s a good heuristic to treat things well around you. And we don’t yet know what risks lie in not being polite and honest.</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=twitter&amp;url=https%3A//x.com/zswitten/status/1829360423914840481&amp;image=" width="500" height="281" frameborder="0" scrolling="no"><a href="https://medium.com/media/2160d084662f796a904dabb33473c18d/href">https://medium.com/media/2160d084662f796a904dabb33473c18d/href</a></iframe><pre>## llm.py ##<br>import tiktoken<br>import json<br><br>from functions.utils import get_llm_client # call to your chosen LLM provider<br><br>CONTEXT = (<br>    &quot;I have a dataset of employee reviews about compensation packages &quot; +<br>    &quot;at various companies. The feedback consists of free-text responses, &quot; +<br>    &quot;ranging from short comments to detailed reviews.&quot;<br>)<br><br>TEXT_DELIMITER = &#39;####&#39;<br><br># Change this to your model&#39;s context length<br>MODEL_CONTEXT_LENGTH = 4000<br><br>TOKEN_LIMIT = MODEL_CONTEXT_LENGTH - 256 # 256 is taken from the prompt token length<br><br><br>def count_tokens(string: str, encoding_name: str) -&gt; int:<br>    &quot;&quot;&quot;<br>       Returns the number of tokens in a text string<br>       e.g. &quot;i love your t-shirt&quot; -&gt; 5<br>    &quot;&quot;&quot;<br>    encoding = tiktoken.get_encoding(encoding_name)<br>    return len(encoding.encode(string))<br><br><br>def generate_prompt_text(input_str: str) -&gt; str:<br>    &quot;&quot;&quot;<br>      Generates the full prompt text<br>    &quot;&quot;&quot;<br>    # 256 tokens in prompt without input_str<br>    user_message = f&#39;&#39;&#39;<br>    Below is a representative set of customer feedback comments delimited with {TEXT_DELIMITER}.<br><br>    Please identify the single main topic mentioned in these comments. Return a topic name and topic description.<br>    The topic name should be short, but descriptive. <br>    The topic description should not be a complete sentence. A good topic description looks like this: <br>    &quot;Concerns about fair compensation compared to market rates&quot; <br><br>    Return the topic name and description as a python dictionary with a single key-value pair like this:<br><br>    {{&quot;topic_name&quot;: &quot;&lt;topicName&gt;&quot;, &quot;topic_description&quot;: &quot;&lt;topicDescription&gt;&quot;}}<br><br><br>    If you cannot find a good topic label, just say, &quot;No topic identified&quot;.<br><br>    Employee feedback:<br>    {input_str}<br>    &#39;&#39;&#39;<br>    return CONTEXT + user_message<br><br><br># prepare input_collections <br>input_collections = {}<br>results = {}<br><br>ENCODING_NAME = &#39;cl100k_base&#39;<br><br># rep_docs is a dictionary with key <br>for topic_int, topic_rep_docs_list in rep_docs.items():<br>    # join all topic rep_docs with a delimiter<br>    topic_rep_docs_string = TEXT_DELIMITER.join([<br>      str(x) for x in topic_rep_docs_list<br>    ])<br><br>    input_collections[f&quot;{topic_int}&quot;] = {<br>        &quot;s&quot;: topic_rep_docs_string,<br>        # token count of string, if needed for token limit<br>        &quot;t&quot;: count_tokens(topic_rep_docs_string, ENCODING_NAME)<br>    }<br><br># Pass representative docs to LLM <br>for topic_int, prompt_obj in input_collections.items():<br>    prompt_text = generate_prompt_text(prompt_obj[&quot;s&quot;])<br>    try:<br>        gpt_res = get_llm_client(prompt_text) # this is up to you to connect to your chosen LLM provider<br>        results[topic_int] = gpt_res<br>    except Exception as e:<br>        print(f&quot;Failed to process topic {topic_int} with error: {e}&quot;)<br>        pass<br><br><br># Save results<br>with open(f&#39;../data/topics/prompt_results_{formatted_datetime}.json&#39;, &#39;w+&#39;) as fpout:<br>    json.dump(results, fpout)<br><br>print(&quot;Written to file&quot;)</pre><h3>7. Review / Reinforce / Repeat</h3><p>The next logical step is to review the model’s performance and make improvements where necessary. More importantly at this stage though is to apply the model on new data to see if it generalizes well on something it has not seen before. Earlier we saved the model locally using the joblib package. Now it’s time to re-load it. You’ll need to process new data similarly to how you processed the original data (generating embeddings and normalizing them). Below is an example workflow:</p><pre>## new_data.py ##<br><br># Load model &amp; new data<br>bertopic_model = joblib.load(<br>  f&quot;../models/bertopic_model_{formatted_datetime}.joblib&quot;<br>)<br>new_docs = [<br>  &quot;New employee feedback 1&quot;,<br>  &quot;Another new feedback comment, blah, blah&quot;,<br>  &quot;Even more feedback data...&quot;<br>]<br><br># Repeat same embedding and pre-processing steps from above on new_docs...<br><br># Apply the model to new data<br>new_topics, new_probs = bertopic_model.transform(<br>  new_docs,<br>  new_embeddings_normalized<br>)</pre><p>You may want to periodically re-train your model if you expect topics to change significantly over time. In that case, you can re-train the BERTopic model with a combination of old and new data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QeIG2_z7op230JnMPBY6JQ.png" /><figcaption>Example of ChatGPT o1-preview assessing its own confidence in a previous answer and correcting itself. Amazing. (Question is from the Three Body Problem!)</figcaption></figure><h3>8. Weighted Log-Odds</h3><p>With a full dataset of labeled topics and categorical features, the first instinct is to create bar charts of the most frequent topics by categories like sentiment or another feature. <strong>I am here to tell you not to waste your time doing this!</strong> A more insightful technique I learned from my coworker, data scientist and linguist <a href="https://www.linkedin.com/in/kate-a-lyons/">Kate Lyons</a>, is <strong>weighted log-odds (WLO)</strong>.</p><p>Using a <a href="https://github.com/lyons7/tidylopy/blob/main/src/tidylopy/tidylopy.py">python adaptation of the WLO function from R’s </a><a href="https://github.com/lyons7/tidylopy/blob/main/src/tidylopy/tidylopy.py">tidylopy package</a> by <a href="https://juliasilge.com/">Julia Silge</a> (via the tidylopy library), you can extract the most unique words per category, rather than just the most frequent ones. This is especially useful when you’re analyzing categories like sentiment, where common frequent topics might appear across both positive and negative sentiments, making it hard to discern what’s actually distinctive.</p><p>Weighted log-odds highlight the words that are the most specific or unique to a category and differentiate that category from others. See a few examples below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AeZW0Xwk6I8v8Ugf_ptG5Q.png" /><figcaption>Thank you Julia Silge! Source: <a href="https://juliasilge.com/blog/introducing-tidylo/">https://juliasilge.com/blog/introducing-tidylo/</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*hBjiLmNmef6m3ktrW5GxaA.jpeg" /><figcaption>Words Known Better by Males than Females, and Vice Versa. Similar technique to WLO. Much more interesting than raw frequency. Source: <a href="https://observablehq.com/@yurivish/words">https://observablehq.com/@yurivish/words</a></figcaption></figure><p>¹ DALL-E 3 prompt to generate cover image: “A 2D t-SNE embedding space with thicker yarn points, forming more obvious clusters on a white background. The points are made from intertwined strands of yarn in bold purples, blues, oranges, reds, and pinks. The clusters are clearly distinct, with some regions densely packed with yarn points and others more spaced out. The thicker yarn creates a strong visual presence, making the clusters stand out while maintaining a soft, textured appearance. The arrangement reflects relationships and distances in the embedding space with a vibrant design, now contrasted against a clean white background.”</p><p><em>Thank you </em><a href="https://www.linkedin.com/in/charlie-oxborough/"><em>Charlie Oxborough</em></a><em> for the coding collab and proofreading.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fdd1de8e4c1d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Texting Yourself With Code: How to Automate a Web Scraping Script and Get Notified via SMS]]></title>
            <link>https://sienaduplan.medium.com/texting-yourself-with-code-how-to-automate-a-web-scraping-script-and-get-notified-via-sms-1f3bf68511a?source=rss-da2b12dafd38------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f3bf68511a</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[twilio]]></category>
            <category><![CDATA[cronjob]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[web-scraping]]></category>
            <dc:creator><![CDATA[Siena Duplan]]></dc:creator>
            <pubDate>Wed, 17 Feb 2021 04:31:48 GMT</pubDate>
            <atom:updated>2021-07-12T20:18:27.816Z</atom:updated>
            <content:encoded><![CDATA[<h3>Web Scraping Tutorial | Texting Yourself With Code: How to Automate a Web Scraping Script and Get Notified via SMS</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HeuGGyc19YrNpnsECuEZQQ.png" /><figcaption>“”It’s like when you finally get a text back and it’s just your [code]” — Fletcher</figcaption></figure><p>Perhaps the only thing more embarrassing than the thrill of a new notification only to find it’s a text from your mom is the false excitement over a text notification from your own code.</p><p>This tutorial will teach you how to integrate software like cron jobs, Twilio’s REST API, and Selenium WebDrivers to send yourself notifications of updates on <em>whatever</em> websites you may be keeping tabs on <em>whenever</em> you want.</p><h4>You will need</h4><ul><li>A good grip of Python, operating your command line, and Chrome Developer Tools</li><li><a href="https://chromedriver.chromium.org/downloads">chromedriver</a> suitable for your version of Google Chrome, and/or</li><li><a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/">Python’s bs4 Beautiful Soup package</a></li><li><a href="https://www.twilio.com/sms">Twilio</a> account with auth token for Programmable Messaging</li></ul><h4>Scrape</h4><p>I regularly listen to the <a href="https://open.spotify.com/show/5RllMBgvDnTau8nnsCUdse">Snacks podcast</a> and noticed the hosts always disclose ownership of shares in companies they discuss on the show. I wanted a way to corral all those disclosures into a list and get notified when a new episode or newsletter airs with a new disclosure.</p><p>The code below uses Selenium and a chromedriver to visit the first few pages of Snacks <a href="https://snacks.robinhood.com/newsletters/">newsletters</a> and search for the paragraph element in the html where disclosures are… disclosed. I am using a lot of try/except statements because after all, I won’t be running my code in a terminal and debugging, but getting a text notification so it’s important any failures are communicated via text. And with constantly-changing and dynamically-updating elements across the web, web-scraping scripts usually have a short lifespan before they need to be repaired.</p><pre>from <strong>bs4</strong> import <strong>BeautifulSoup</strong> as <strong>bs</strong><br>import <strong>requests</strong><br>from <strong>selenium</strong> import <strong>webdriver</strong> # may not need if <strong>bs4</strong> sufficient<br>from <strong>twilio.rest</strong> import <strong>Client</strong></pre><pre><strong>article_links_list</strong> = []<br><strong>disclosures</strong> = []<br><strong>text_to_send</strong> = &#39;&#39;<br><strong>apple</strong> = False<br><strong>apple_string</strong> = &#39;&#39;</pre><pre># get list of URLs to visit and plunder!<br>try:<br>   for page in range(1,5):<br>      url = &#39;https://snacks.robinhood.com/newsletters/page/%s/&#39;%page<br>      r = requests.get(url)<br>      soup = bs(r.content, &#39;html.parser&#39;)<br>      for a in soup.find_all(&#39;a&#39;,attrs={&#39;class&#39;:&#39;css-k4v2t0&#39;}):<br>         print(&#39;grabbing &#39;,url.split(&#39;/newsletters&#39;)[0]+a[&#39;href&#39;])<br>         <strong>article_links_list</strong>.append(url.split(&#39;/newsletters&#39;)[0]+a[&#39;href&#39;])<br>except:<br>   <strong>text_to_send</strong> = &#39;🚨 Failed on bs4 execution&#39;</pre><pre># visit URLs and dig for gold!<br>try:<br>   for url in <strong>article_links_list</strong>:<br>      driver =   webdriver.Chrome(executable_path=&#39;path/to/chromedriver&#39;)<br>      driver.get(url)<br>      p_element = (driver.find_element_by_xpath(&#39;//*[@id=&quot;__next&quot;]/div[1]/div/div/div[10]/p[1]&#39;)).text</pre><pre>      driver.quit()<br>      if &#39;own&#39; in p_element.lower().split(&#39; &#39;):<br>         <strong>companies</strong> = p_element.lower().split(&#39;:&#39;)[1]<br>         <strong>disclosures</strong>.append(<strong>companies</strong>)<br>except:<br>   <strong>text_to_send</strong> = &#39;🚨 Failed on chromedriver execution&#39;</pre><pre><strong><br></strong># ugly but efficient way to clean the list in a one-liner<strong><br>disclosures_clean</strong> = sorted(list(set([item for i in <strong>disclosures</strong> for item in i.replace(&#39;,&#39;,&#39;&#39;).split(&#39; &#39;) if item != &#39;and&#39; and item != &#39;&#39;]))) </pre><pre>print(<strong>disclosures_clean</strong>)</pre><pre>if &#39;apple&#39; in <strong>disclosures_clean</strong>: <strong>apple</strong> = True<br>if <strong>apple</strong>: <strong>apple_string</strong> = &#39;Found 🍎 in list!\n\n&#39;</pre><pre><strong>text_to_send</strong> = &quot;Hello from Siena&#39;s bot 🤖 \n\n&quot; + <br>               &#39;Here is the latest list of companies the Snacks hosts are talking about and own shares of 💰\n\n&#39; + <br>apple_string + &#39;\n&#39;.join(<strong>disclosures_clean</strong>) + &#39;\n\nThis script used to generate this message runs every Monday-Friday at 8:08AM PST. Cool.&#39;</pre><p>There are many ways to grab elements from html; in this example, I found using the xpath to be the most direct way to get the text I was looking for on the page. I found the xpath by selecting the text on the page with Chrome’s Dev Tools &gt; right-clicking on the corresponding html tag &gt; Copy &gt; XPath.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b8zX0sArbVodjZ-yK_X2HA.png" /></figure><p>The next step is to connect to your Twilio account and instantiate a message. Depending on your Twilio credentials, you may have to pay a <em>very small</em> fee per message (like $0.0075/message as of this writing), so you may want to use them sparingly in testing.</p><pre><strong>account_sid</strong> = &quot;[insert account ID here]&quot;<br><strong>auth_token</strong> = &quot;[insert auth token here]&quot;</pre><pre>try:<br>   client = Client(<strong>account_sid</strong>, <strong>auth_token</strong>)<br>   message = client.messages.create(body=<strong>text_to_send</strong>, to=&#39;<strong>+your mobile #</strong>&#39;, from_=&#39;<strong>+your twilio #</strong>&#39;)</pre><pre>except:<br>   print(&#39;🚨 Error connecting to Twilio client&#39;)</pre><h4>Automate</h4><p>Next, create a cron job on your computer scheduled to run the python script above on a regular cadence. I want the script to run every Monday-Friday morning so using cron nomenclature, I inserted 8 8 * * 1-5 python3 /path/to/script.py 1&gt;/tmp/stdout.log 2&gt;/tmp/stderr.log using vim. In my terminal, I ran crontab -l to list any current jobs I had running, and crontab -e to edit a new job.</p><p>The keyboard commands in my terminal looked something like this:</p><pre>crontab -e</pre><pre>i</pre><pre>8 8 * * 1-5 python3 /path/to/script.py 1&gt;/tmp/stdout.log 2&gt;/tmp/stderr.log</pre><pre>esc</pre><pre>:wq</pre><pre>crontab -l</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aqT853JGxG_hR0D_6sA6BA.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*fnOitAKFLUpUvytWR7XuWA.jpeg" /><figcaption><a href="https://crontab.guru/">https://crontab.guru/</a> if you are confused</figcaption></figure><p>For my own sake, I added the log outputs in case there were any complications — and of course, there were. At this point, the most likely obstacle you will have is that your terminal has not been granted full disk access. I granted my terminal with full disk access by following the steps outlined <a href="https://osxdaily.com/2020/04/27/fix-cron-permissions-macos-full-disk-access/">here</a>.</p><p>That’s it. That’s all you have to do to automate texting yourself when you want to receive updates about anything on the world wide 🕸.🤘.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*RVizZPB1zkLBEO5-KP2gUQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f3bf68511a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Sync Your Hue Lights to the Stock Market]]></title>
            <link>https://sienaduplan.medium.com/how-to-sync-your-hue-lights-to-the-stock-market-7f6a736a9442?source=rss-da2b12dafd38------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f6a736a9442</guid>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[stock-market]]></category>
            <dc:creator><![CDATA[Siena Duplan]]></dc:creator>
            <pubDate>Sun, 17 May 2020 21:34:42 GMT</pubDate>
            <atom:updated>2021-07-12T20:16:49.728Z</atom:updated>
            <content:encoded><![CDATA[<h3>IoT Tutorial: How to Sync Your Hue Lights to the Stock Market</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*th3SNLegsE5l4AQ_KUrZtQ.png" /><figcaption><a href="https://9to5mac.com/2020/01/10/bluetooth-philips-hue-lightstrip-revealed-in-fcc-docs-to-work-without-bridge/">Source</a> and <a href="https://www.videoblocks.com/video/3d-stock-market-profit-loss-results-display-on-led-screen-with-red-green-text-version-3-seamless-loop-full-hd-ss6bqpoteize38r74">Source</a></figcaption></figure><p>Let’s be real — you paid a pretty penny for your Philips Hue lights. Why not put that money to work and take control of your lights? Let’s bring the stock market to life by plugging it into your physical world. In this tutorial you will learn how to connect to your Philips Hue API and control your lights with Python directly from your computer.</p><h3>What you will need:</h3><ul><li>Philips Hue Lights and Bridge</li><li>Intermediate Python knowledge</li><li>Free time</li></ul><h3>Step 1</h3><p>Install the <a href="https://github.com/studioimaginaire/phue"><em>phue</em> package by studioimaginaire on Github</a>. From your terminal run:</p><p>pip install phue</p><h3>Step 2</h3><p>Ensure you are connected to the same network as your Philips Hue Bridge. Opening the following link on your browser will populate a JSON like the one in the image below if you are properly connected: <a href="https://discovery.meethue.com/">https://discovery.meethue.com/</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fCGelqKKX6fNKJLoTrUoaA.png" /></figure><p>If you are not on the same network, you will see empty brackets. Make sure you are not connected to any VPN and/or try switching between 2.4GHz and 5GHz wifi.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*c5wMSbtZ5i55Fts7LPCvIw.png" /></figure><h3>Step 3</h3><p>Create a Python environment of your choice. I am using Jupyter Notebooks and running Python 3.6.4.</p><p>Immediately before running the following code, press the main button on your Philips Bridge. You will only need to do this once the first time you are running this script.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RWlRlgJv4hq97wYoY393uA.png" /></figure><pre>from phue import Bridge</pre><pre># use your own IP<br>b = Bridge(&#39;192.168.1.2&#39;) </pre><pre>b.connect()</pre><p>If you have avoided or debugged errors up to this point, congratulations! The fun begins now!</p><h3>Step 4</h3><p>At this point, you have made a connection with your lights from your scripts and will probably want to play around and familiarize yourself with the API.</p><p>Here are some fun commands to try out:</p><p><em>Getting information</em></p><pre>b.get_api( )           # explore properties you can change</pre><pre>b.get_light(1, ‘on’)   # returns True or False </pre><pre>b.get_light(1, &#39;name&#39;) # returns name of light if you have named it</pre><pre>b.get_light(1, &#39;hue&#39;)  # returns current color of light</pre><p><em>Setting properties</em></p><pre>b.set_light(1, ‘bri’, 255)</pre><pre>b.set_light(1, &#39;hue&#39;, 0)</pre><pre>b.set_light(1, &#39;sat&#39;, 255)</pre><p>Loop through the entire rainbow 100 times. Because once is not enough. 🌈</p><pre>for _ in range(100):<br>    for i in range(65535):<br>        if i % 1000 == 0:<br>            b.set_light(1, ‘hue’, i)</pre><p>(Notice there’s no references to discrete colors like ROY G. BIV. Philips uses a wide continuous spectrum of 65,535 unique hues to generate their colors.)</p><h3>Step 5</h3><p>To gather stock information, import the following packages:</p><pre>import pandas as pd<br>import pandas_datareader.data as web<br>import numpy as np<br>import datetime as dt</pre><p>Let’s also create a function that will be useful later for converting the 65,535 hues (colors) to colors we know by RGB inputs.</p><pre>def toRGB(R,G,B):<br>    X = 0.4124*R + 0.3576*G + 0.1805*B # Thank you Stack Overflow<br>    Y = 0.2126*R + 0.7152*G + 0.0722*B<br>    Z = 0.0193*R + 0.1192*G + 0.9505*B</pre><pre>    x = X / (X + Y + Z)<br>    y = Y / (X + Y + Z)</pre><pre>    b.set_light(1, &#39;xy&#39;, [x,y]) # modify light number as necessary</pre><p>Pick a stock, any stock. I am using $AAPL from Jan, 2000 to Jan, 2020. Twenty years of daily Apple stock prices (OHLC) will be stored in the dataframe <em>df</em>.</p><pre>start = dt.datetime(2000,1,1)<br>end = dt.datetime(2020,5,15)<br>df = web.DataReader(‘AAPL’,’yahoo’, start, end)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*5UfbAkAMArHVleIRNWn3MA.png" /></figure><h3>Step 6</h3><p>Normalize, normalize, normalize!</p><p>In this particular case, I’m using the Adjusted Close price and creating another column in the dataframe to store the normalized value (between 0 and 1).</p><pre>from sklearn import preprocessing</pre><pre>min_max_scaler = preprocessing.MinMaxScaler()</pre><pre>df[‘Adj Close Normalized’] = min_max_scaler.fit_transform(df[[‘Adj Close’]])</pre><h3>Step 7</h3><p>Because I am using Jupyter Notebooks, I have the option to beautify my printed output. This won’t work if you are running a Python script from your command line.</p><pre>from IPython.display import Markdown, display</pre><pre>def printmd(string):<br>    display(Markdown(string))</pre><p>I am choosing to only visualize Apple’s stock price at the start of each year since 2000. I will have my lights display a total of 21 colors in sequential order for each year.</p><pre>years=[]<br>for idx, row in df.iterrows():<br>    if idx.year not in years:<br>        years.append(idx.year)<br>        value = row[‘Adj Close Normalized’]<br>        price = round(row[‘Adj Close’],2)<br>        <br>        G = round(value*255,0)<br>        R = 255-G</pre><pre>        # use a simple print statement if not in a notebook env             <br>        printmd(“&lt;span style=’font-size:30px’&gt;{} &lt;span style=’color:rgb({},{},0)’&gt;${}&lt;/span&gt; &lt;/span&gt;”.format(idx.year,R,G, price)) </pre><pre>        toRGB(R,G,0)<br>        time.sleep(.25) # pause between each year</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*aqFNWJRVvLKU-dW8X9bI_w.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*kt_PXVwByktK6p9bIrEtng.gif" /></figure><h3>Future work</h3><p>Connect with Alexa to have her read out the years!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f6a736a9442" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Visualizing Topic Models with Scatterpies and t-SNE]]></title>
            <link>https://medium.com/data-science/visualizing-topic-models-with-scatterpies-and-t-sne-f21f228f7b02?source=rss-da2b12dafd38------2</link>
            <guid isPermaLink="false">https://medium.com/p/f21f228f7b02</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[text-analytics]]></category>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[Siena Duplan]]></dc:creator>
            <pubDate>Mon, 04 Nov 2019 21:21:02 GMT</pubDate>
            <atom:updated>2019-11-06T19:36:40.782Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MvI1_GSUZito7WPjtanPFw.png" /></figure><p>For better or worse, our language has not yet evolved into George Orwell’s 1984 vision of <a href="https://www.sparknotes.com/lit/1984/section11/">Newspeak</a> (<em>doubleplus ungood</em>, anyone?). But had the English language resembled something like Newspeak, our computers would have a considerably easier time understanding large amounts of text data. Present-day challenges in natural language processing, or NLP, stem (no pun intended) from the fact that natural language is naturally ambiguous and unfortunately imprecise.</p><p>Text data is under the umbrella of unstructured data along with formats like images and videos. According to <a href="https://books.google.com/books?id=0-9lDwAAQBAJ&amp;pg=PA241&amp;lpg=PA241&amp;dq=dama+international+unstructured+data+Any+document,+file,+graphic,+image,+text,+report,+form,+video,+or+sound+recording+that+has+not+been+tagged+or+otherwise+structured+into+rows+and+columns+or+records&amp;source=bl&amp;ots=tjVlGGZcl0&amp;sig=ACfU3U1lQ4_8ZX6lLzG_YkHhI2KkIkI3vw&amp;hl=en&amp;sa=X&amp;ved=2ahUKEwiSraarm_zkAhVQqZ4KHfP1CHYQ6AEwAHoECAkQAQ#v=onepage&amp;q=dama%20international%20unstructured%20data%20Any%20document%2C%20file%2C%20graphic%2C%20image%2C%20text%2C%20report%2C%20form%2C%20video%2C%20or%20sound%20recording%20that%20has%20not%20been%20tagged%20or%20otherwise%20structured%20into%20rows%20and%20columns%20or%20records&amp;f=false">Dama</a>, “unstructured data is technically any document, file, graphic, image, text, report, form, video, or sound recording that has not been tagged or otherwise structured into rows and columns or records.” The label “unstructured” is a little unfair since there is usually still some structure. Images break down into rows of pixels represented numerically in RGB or black/white values. Text breaks down into sentences, paragraphs, and/or chapters within documents and a collection of documents forms a corpus.</p><p>For a computer to understand written natural language, it needs to understand the symbolic structures behind the text. Using some of the NLP techniques below can enable a computer to classify a body of text and answer questions like, What are the themes? Is the tone positive? Subjective? <a href="https://twitter.com/SienaDuplan/status/717420808759476224">How easily does it read</a>?</p><p>Below are some NLP techniques that I have found useful to uncover the symbolic structure behind a corpus:</p><ul><li>Topic modeling (themes, clustering)</li><li>Word/phrase frequency (and “keyword searching”)</li><li>Text visualization (<a href="https://www.jasondavies.com/wordtree/">Word Trees</a>, <a href="https://www.jasondavies.com/wordcloud/">Word Clouds</a> both by @Jason Davies)</li><li>Embeddings (e.g. Word2Vec)</li><li>Sentiment analysis (positive/negative, subjective/objective, emotion-tagging)</li><li>Text similarity (e.g. “cosine similarity”)</li><li>TF-IDF (term frequency/inverse document frequency)</li><li>Part-of-speech tagging</li></ul><p>In this post, I am going to focus on the predominant technique I’ve used to make sense of text: topic modeling, specifically using <a href="https://github.com/vi3k6i5/GuidedLDA">GuidedLDA</a> (an enhanced LDA model that uses sampling to resemble a semi-supervised approach rather than an unsupervised one). <strong>One of the difficulties I’ve encountered after training a topic a model is displaying its results.</strong> The output from the topic model is a document-topic matrix of shape <em>D x T</em> — <em>D</em> rows for <em>D</em> documents and <em>T</em> columns for <em>T</em> topics. The cells contain a probability value between 0 and 1 that assigns likelihood to each document of belonging to each topic. The sum across the rows in the document-topic matrix should always equal 1. In optimal circumstances, documents will get classified with a high probability into a single topic. With fuzzier data — documents that may each talk about many topics — the model should distribute probabilities more uniformly across the topics it discusses. Here is an example of the first few rows of a document-topic matrix output from a GuidedLDA model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*moA-msQBO9mC2JnRUMi2_A.png" /><figcaption>Document 0 belongs to topic 0 with 71% probability and topic 1 with 29% probability. Document 1 belongs to topic 0 with almost 100% probability. And so on.</figcaption></figure><p>Document-topic matrices like the one above can easily get pretty massive. Unless the results are being used to link back to individual documents, analyzing the document-over-topic-distribution as a whole can get messy, especially when one document may belong to several topics. <strong>This is where I had the idea to visualize the matrix itself using a combination of a scatter plot and pie chart: behold the scatterpie chart!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FnsTVrgcH6MyFYkj0zvU9Q.png" /><figcaption>Each bubble is a document. Bubbles are colored by topic probability and sized by #1 topic probability (argmax of each row/document in the document-topic matrix). Where there is a pie chart, the document belongs to multiple topics with varying probabilities. The scatterpie chart shows which topics tend to co-occur and how topics overlap with each other. Individual bubbles (documents) are pulled in the direction of the “center of mass” of another topic they may also belong to. Note: to simplify the chart, you may need to filter out documents with #1 topic probability less than some threshold. In this example, I removed documents with #1 topic probability &lt; 0.3 to clean up the visualization.</figcaption></figure><p>But not so fast — you may first be wondering how we reduced <em>T</em> topics into a easily-visualizable 2-dimensional space. For this, I used t-Distributed Stochastic Neighbor Embedding (or t-SNE). Taking the document-topic matrix output from the GuidedLDA, in Python I ran:</p><pre>from sklearn.manifold import TSNE</pre><pre>tsne_model = TSNE(n_components=2, verbose=1, random_state=7, angle=.99, init=’pca’)</pre><pre># 13-D -&gt; 2-D<br>tsne_lda = tsne_model.fit_transform(doc_topic) # doc_topic is document-topic matrix from LDA or GuidedLDA </pre><p>After joining 2 arrays of t-SNE data (using tsne_lda[:,0] and tsne_lda[:,1]) to the original document-topic matrix, I had two columns in the matrix that I could use as X,Y-coordinates in a scatter plot.</p><p>For the plot itself, I switched to R and the ggplot2 package. The dataframe <em>data</em> in the code snippet below is specific to my example, but the column names should be more-or-less self-explanatory. <em>x_tsne</em> and <em>y_tsne</em> are the first two dimensions from the t-SNE results. <em>row_id</em> is a unique value for each document (like a primary key for the entire document-topic table). <em>x_1_topic_probability</em> is the #1 largest probability in each row of the document-topic matrix (i.e. the topic that document is most likely to represent). <em>topic_names_list</em> is a list of strings with <em>T</em> labels for each topic.</p><pre>library(ggplot2)<br>library(scatterpie)</pre><pre># high resolution tiff image<br>tiff(“scatterpie.png”, units=”in”, width=12, height=9, res=500)</pre><pre># plot<br>p &lt;- ggplot() + <br> geom_scatterpie(aes(x=x_tsne, y=y_tsne, group=row_id, r=x_1_topic_probability), data=data, cols=topic_names_list, color=NA, alpha=0.7) + <br> coord_equal() + <br> geom_label(...) + <br> ggtitle(“Scatterpie Chart”) + <br> xlab(“”) + ylab(“”) + labs(subtitle=”t-SNE Representation of Guided-LDA Topics Colored and Sized by Topic Probability”) +<br> scale_fill_manual(values=colors) + <br> theme_minimal() + <br> theme(text = element_text(color=”white”),<br> legend.position = “none”,<br> panel.background = element_rect(fill = “gray17”, colour = “gray17”), <br> plot.background = element_rect(fill = “gray17”),<br> panel.grid.major = element_line(colour = “gray25”),<br> panel.grid.minor = element_line(colour = “gray25”),<br> axis.text = element_text(color=”white”))<br></pre><pre># shut down graphics device<br>dev.off()</pre><p>And voilà, there you have the nuts and bolts to building a scatterpie representation of topic model output. In the future, I would like to take this further with an interactive plot (looking at you, <a href="https://d3js.org/">d3.js</a>) where hovering over a bubble would display the text of that document and more information about its classification.</p><p>If you’re interested in more cool t-SNE examples I recommend checking out <a href="https://lvdmaaten.github.io/tsne/">Laurens Van Der Maaten’s page</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jRId_vMTOCVA2z7eucDzYQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*-iM-ATFuGn59l64H1ALChw.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Q6Cd3Citrt40CRF7ZBa2g.jpeg" /><figcaption>Left &amp; middle: 2D &amp; 3D t-SNE visualization of 6,000 digits from the <a href="https://en.wikipedia.org/wiki/MNIST_database">MNIST</a> dataset. Right: t-SNE visualization of image data. <a href="https://lvdmaaten.github.io/tsne/">Source</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f21f228f7b02" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/visualizing-topic-models-with-scatterpies-and-t-sne-f21f228f7b02">Visualizing Topic Models with Scatterpies and t-SNE</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[Weather Data, Plot, and Code]]></title>
            <link>https://medium.com/data-science/pgh-weather-data-plot-and-code-19d8e8b670f?source=rss-da2b12dafd38------2</link>
            <guid isPermaLink="false">https://medium.com/p/19d8e8b670f</guid>
            <category><![CDATA[climate-change]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[rstats]]></category>
            <category><![CDATA[analytics]]></category>
            <dc:creator><![CDATA[Siena Duplan]]></dc:creator>
            <pubDate>Mon, 02 Oct 2017 21:31:53 GMT</pubDate>
            <atom:updated>2017-10-02T23:37:33.435Z</atom:updated>
            <content:encoded><![CDATA[<p>Adapted from a <a href="http://austinwehrwein.com/data-visualization/it-brings-me-ggjoy/">blog post</a> by Austin Wehrwein and <a href="https://cran.r-project.org/web/packages/ggridges/vignettes/gallery.html">Cran page</a> by Claus O. Wilke. Data from Weather Underground.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MnIXFjOR8IbjWUdG0vY7hg.png" /></figure><p>The R code for generating a plot like the above can be found on both Austin Wehrwein’ <a href="http://austinwehrwein.com/data-visualization/it-brings-me-ggjoy/">blog</a> and this <a href="https://cran.r-project.org/web/packages/ggridges/vignettes/gallery.html">Cran page</a>, but I have included it below as well, with some minor modifications and details on how to retrieve your own data from the Weather Underground.</p><h4>Data:</h4><p>Select region and custom time period on this <a href="https://www.wunderground.com/history/airport/KAGC/2017/1/1/CustomHistory.html?dayend=17&amp;monthend=9&amp;yearend=2017&amp;req_city=&amp;req_state=&amp;req_statename=&amp;reqdb.zip=&amp;reqdb.magic=&amp;reqdb.wmo=&amp;MR=1">Weather Underground</a> page. Copy/paste tabular data into Excel (may need to remove additional column headers). Relabel dates to follow format “%d-%b-%y” or “1-Jan-2016”. Relabel column headers. Save as CSV.</p><p>Note: you can try scraping directly from R with <a href="https://topbullets.com/2017/04/12/how-to-download-data-from-weather-underground-topbullets-com/">this tutorial</a>, but WU recently changed their URL scheme, so this technique may not work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P0a30dY6Akf6PdQeB_1gNA.png" /><figcaption>Your data should look something like this. Mean Temp (Col C) is what I plotted, but pretty much any numeric variable can be used.</figcaption></figure><h4>Libraries:</h4><pre>library(viridis)     ## color palette<br>library(ggjoy)       ## ridges<br>library(hrbrthemes)  ## plot theme</pre><h4>Import and minor data cleaning:</h4><pre>pgh_weather &lt;- read.csv(&quot;weather_data.csv&quot;) ## setwd() to your own<br>months &lt;- c(&quot;December&quot;,&quot;November&quot;,&quot;October&quot;,&quot;September&quot;,&quot;August&quot;,&quot;July&quot;,&quot;June&quot;,&quot;May&quot;,&quot;April&quot;,&quot;March&quot;,&quot;February&quot;,&quot;January&quot;) ## need this string vector for sorting later</pre><pre>pgh_weather$months &lt;- as.Date(pgh_weather$CST, format = &quot;%d-%b-%y&quot;) %&gt;%<br>  months() %&gt;%<br>  as.factor() %&gt;%<br>  factor(., levels = months)</pre><pre>#scales<br>mins &lt;- min(pgh_weather$Min.TemperatureF)<br>maxs &lt;- max(pgh_weather$Max.TemperatureF)</pre><h4>Plots:</h4><pre>## black and white<br>ggplot(pgh_weather,aes(x = Mean.TemperatureF,y=months,height=..density..))+<br>  geom_joy(scale=3) +<br>  scale_x_continuous(limits = c(mins,maxs))+<br>  theme_ipsum(grid=F)+<br>  theme(axis.title.y=element_blank(),<br>        axis.ticks.y=element_blank(),<br>        strip.text.y = element_text(angle = 180, hjust = 1))+<br>  labs(title=&#39;Temperatures in Pittsburgh&#39;,<br>       subtitle=&#39;Median temperatures (Fahrenheit) by month for 2016\nData: Original CSV from the Weather Underground&#39;, x = &quot;Mean Tempterature [ºF]&quot;)</pre><pre>## in color<br>ggplot(pgh_weather, aes(x = `Mean.TemperatureF`, y = `months`, fill = ..x..)) +<br>  geom_density_ridges_gradient(scale = 3, rel_min_height = 0.01, gradient_lwd = 1.) +<br>  scale_x_continuous(expand = c(0.01, 0)) +<br>  scale_y_discrete(expand = c(0.01, 0)) +<br>  scale_fill_viridis(name = &quot;Temp. [ºF]&quot;, option = &quot;C&quot;) +<br>  labs(title = &#39;Temperatures in Pittsburgh&#39;,<br>       subtitle = &#39;Mean temperatures (Fahrenheit) by month for 2016\nData: Original CSV from the Weather Underground&#39;, <br>       x = &quot;Mean Temperature&quot;) +<br>  theme_ridges(font_size = 13, grid = TRUE) + theme(axis.title.y = element_blank())</pre><h4>Next steps:</h4><p>Download yearly data and trace rising temperatures with GIF or fading ridges.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*RJ7niP49gZ1EBLY0K36rLg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19d8e8b670f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/pgh-weather-data-plot-and-code-19d8e8b670f">Weather Data, Plot, and Code</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[Degrees of separation on a tree algorithm]]></title>
            <link>https://sienaduplan.medium.com/degrees-of-separation-on-a-tree-algorithm-802d3deb7680?source=rss-da2b12dafd38------2</link>
            <guid isPermaLink="false">https://medium.com/p/802d3deb7680</guid>
            <category><![CDATA[network]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Siena Duplan]]></dc:creator>
            <pubDate>Thu, 28 Jul 2016 00:38:33 GMT</pubDate>
            <atom:updated>2016-07-28T00:38:33.504Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nPXXZqU5b_CoGj0HfTKHcw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YayL_uL7THww_dlsTLvnzA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qd0OtmwB5IzkMlZ4c04XwA.png" /></figure><p>Imagine that you are like me and looking for an algorithm to compute degrees of separation along a hierarchical tree like the ones pictured below. Your tree could represent any data — let’s pretend it’s a company orgchart with node A as the CEO, nodes B and I are execs, and so on. <strong>The distance, or degrees of separation, between any two nodes is the number of links along the shortest path that separates them.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*tOxK0m4LYE-B9rGH6mESeQ.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*lVKquQ5o7watvJhxBX_a-Q.gif" /></figure><h4>Concept</h4><p>Intuitively, it seems quite easy to count up and down a tree as in the pictures above. But when your data is a flat CSV, the pattern is a little tricky to see. The computation depends on whether one person is a manager, directly or indirectly, of the other person.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Hz8mcI70aCBvlbyiJ8FbQ.png" /><figcaption>X = <em>m</em>’s distance from A, Y = <em>n</em>’s distance from A, Z = number of nodes that <em>m</em> and <em>n</em> share</figcaption></figure><p>Say we have selected two nodes <em>m</em> and <em>n</em>, where <em>m</em> = node B and <em>n</em> = node F. Notice that B is F’s eventual manager (via node D). In this case, B’s distance from A, or X, = 1; F’s distance from A, or Y, = 3. The only node B and F have in common is A, so their intersection Z = 1. B and F’s degrees of separation = 2 because 1+3–2(1) = 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ZZZUboGpyarHwTblRXk2g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5dZnpe537qyJjs5bbAV9Dw.png" /><figcaption>Case 1: One node is the (eventual) manager of the other</figcaption></figure><p>Now let’s select two nodes which are not eventual managers of each other — nodes F and H. Both node F’s and H’s distance from A, or X and Y, = 3. Their intersection Z = 3 because they have nodes A, B, and D in common. F and H’s degrees of separation = 2 because 3+3–2(3–1) = 2.</p><p>Wait a second, where did that minus 1 come from?! Well, <em>technically</em> it’s minus 2 once you distribute the 2, and it comes from eliminating the double-counting that happens when links are shared by both <em>m</em> and <em>n</em> on their paths to A. I urge you to trace some paths of your own and compute the math to make evident this concept.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QW0F9sQaX1s2aXM1JAbVhg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OEMk6nl-lK3zXcmMDGM7IA.png" /><figcaption>Case 2: Neither node falls in the management chain of the other</figcaption></figure><h4>Data Structure</h4><p>If your tree data exists as a nested JSON, consider converting it to a flat CSV for the purpose of this tutorial. I used a CSV and R to achieve my goal along with d3.js collapsible trees to visualize my trees. Ideal data structure for the algorithm looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*ksIGzXvIZR81HFvc6Lcezw.png" /></figure><h4>Code</h4><pre>degrees &lt;- function(m,n){</pre><pre>     ## compute m &amp; n&#39;s distance from A<br>     ## subtract 1 to remove &quot;person&quot; column     <br>     mFromA &lt;- sum(!is.na(data[m, ])) — 1<br>     nFromA &lt;- sum(!is.na(data[n, ])) — 1</pre><pre>     ## compute how many nodes m and n have in common<br>     ## in many cases, m and n only have A in common<br>     overlap &lt;- intersect(data[m, which(!is.na(data[m, ]))], data[n, which(!is.na(data[n, ]))])</pre><pre>     ## (optional) print above values <br>     print(paste(“Distance”, data[m,1] ,”to A: “, mFromA))<br>     print(paste(“Distance”, data[n,1] ,”to A: “, nFromA))<br>     print(paste(“length of overlap: “, length(overlap)))<br>     print(overlap)</pre><pre>     ## ok, algorithm time: </pre><pre>     ## but first, let&#39;s check if the user entered the same person <br>     ## i.e. does m == n? if so, degrees of separation = 0<br>     if(m == n){<br>          degreesOfSep &lt;- 0<br>     }<br> <br>     ## check if m or n is (eventual) manager of n or m<br>     ## i.e. check if higher node manages lower node<br>     ## if so, compute distance as X+Y-2*Z<br>     else if(mFromA != nFromA){<br>          if(mFromA &gt; nFromA){ lower &lt;- m; higher &lt;- n }<br>          if(nFromA &gt; mFromA){ lower &lt;- n; higher &lt;- m }<br>          for (i in 2:length(data[lower, ])) {<br>               if(grepl(data[higher,1], data[lower,i])){<br>                    manager &lt;- TRUE<br>                    print(paste(data[higher,1], “is an (eventual) manager of”, data[lower,1]))<br>                    break<br>               }<br>               else{<br>                    manager &lt;- FALSE<br>               }<br>          }<br>          if(manager){<br>               degreesOfSep &lt;- mFromA + nFromA — 2*(length(overlap))<br>          }<br>          ## if one is not (eventual) manager of other, <br>          ## compute as X+Y-2*(Z-1)<br>          else {<br>               degreesOfSep &lt;- mFromA + nFromA — 2*(length(overlap) — 1)<br>          }<br>     }<br>     else {<br>          degreesOfSep &lt;- mFromA + nFromA — 2*(length(overlap) — 1)<br>     }<br>     print(paste(“Degrees of Separation: “, degreesOfSep))<br>}</pre><h4>Cool! Now, what?</h4><p>Now we have an algorithm that accepts any two nodes as arguments and spits out their degrees of separation! Yay!</p><p>Perhaps a degrees of separation metric could help you <em>predict</em> attrition—how does a manager’s resignation ripple-effect through his or her network? Are a manager’s direct reports (+1 degree of separation) more likely to leave than his or her skip-level reports (2+ degrees of separation)?</p><p>Degrees of separation make all sorts of team analyses possible—do we perform better as teams or as individuals?</p><p>In the future, I’d like weight degrees of separation based on external data, like email communications and LinkedIn connections. In the case of the orgchart, I believe the future lies in networks, not trees. Tree orgcharts are simple which is why we use them, but in reality teamwork and collaboration can happen even amongst those with the highest degrees of separation. Fortunately, there’s a lot more literature online about network algorithms than single-parent tree algorithms.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=802d3deb7680" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[10 Takeaways from 22 Data Visualization Practitioners at #OpenVisConf]]></title>
            <link>https://medium.com/free-code-camp/10-takeaways-from-22-data-visualization-practitioners-at-openvisconf-a4a3a5b96fcd?source=rss-da2b12dafd38------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4a3a5b96fcd</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[women-in-tech]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[design]]></category>
            <dc:creator><![CDATA[Siena Duplan]]></dc:creator>
            <pubDate>Sun, 01 May 2016 20:44:16 GMT</pubDate>
            <atom:updated>2016-12-29T05:51:21.209Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*69AxS6dkqsOc0ycRORlRoA.jpeg" /></figure><p><em>Update | May 13, 2016: </em><a href="http://openvisconf.com/#videos"><em>Videos of all talks are officially live!</em></a></p><h4><strong>1. “Data visualization is not your creative outlet; data visualization is making data understandable.”</strong></h4><p><a href="https://medium.com/u/39b196537c54">rachel binx</a> from NASA’s Jet Propulsion Laboratory eloquently described every data viz practitioner’s struggle: compromising between art and utility.</p><p>Visualization literacy and data literacy take time. In fact, <a href="https://medium.com/u/dd52dd16f023">Tony Chu</a> taught us how data visualization is the use of <em>space</em> to control <em>time </em>(spacetime pun?).</p><p>Intuitive data exposition is constrained by attention — what Daniel Kahneman, author of <a href="https://en.wikipedia.org/wiki/Thinking,_Fast_and_Slow"><em>Thinking, Fast and Slow</em></a><em>,</em> would call our System 2 thinking.</p><p>Tony advocates using techniques like animation and pacing (think <a href="http://www.r2d3.us/visual-intro-to-machine-learning-part-1/">scrollytelling</a>) to feed bite-size bits of information (pun intended) to those digesting our visualizations, while Rachel focuses on using data viz to render tools instead of to tell stories or paint a picture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*Tv5_eWfGqkHSOClKrJjmxA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*4AnzSrEWojQ_qT4ulEE4nw.png" /><figcaption>Left/Top: <a href="https://speakerdeck.com/binx/designing-for-spacecraft-operations">Slides by Rachel Binx</a>. Right/Bottom: <a href="https://docs.google.com/presentation/d/1GOSyl4-iklcO0kIBFy-31zylaLC1R3uTwxX89bWt5D0/edit#slide=id.g11e8900888_0_2">Slides by Tony Chu</a></figcaption></figure><h4><strong>2. Yet, so much creativity is involved in finding solutions to visualizing complex data problems.</strong></h4><p>Every speaker probed the realms of creativity in their mesmerizing visuals and approaches to technical rigor. <a href="https://medium.com/u/12579b0cb1b5">Mariko Kosaka</a> transformed polynomial functions into “pixel playgrounds” and brought kernel convolution to life with a “pixel social graph.”</p><p><a href="https://medium.com/u/4607b4069d83">Shirley Wu</a> <a href="http://vallandingham.me/force_talk/#0">abused the force</a> (d3’s force-directed graph layout) in a number of ways to simplify <a href="https://medium.com/u/38aa4df03855">Illumio</a>’s Illumination product (<a href="http://slides.com/shirleywu/building-data-visualizations-for-product#/">Shirley’s slides</a> distill this complex idea into beautiful, understandable simplicity).</p><p><a href="https://twitter.com/AmeliaMN">Amelia McNamara</a> sneakily taught us some statistics — particularly, a creative solution to distinguishing real patterns in data from randomly generated data.</p><p><a href="https://twitter.com/ncasenmare">Nicky Case</a> cleverly applied systems thinking to real-world phenomena like disease proliferation, ecosystem regeneration, and racial segregation. Nicky employed emojis in simulations to show that the world is not linear; it’s loopy. (Side note: emojis made a record-breaking number of appearances in this year’s talks.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*I7zeBT76W1Qgy9iYtKRPLw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*-o_GLc-amAi9vtOMPp2EMw.png" /><figcaption><a href="http://kosamari.com/presentation/openvis-2016">Slides by Mariko Kosaka</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*Ph5ttYRP3Hs80JjazCn10Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*FNWMpCWQMOetFtRtFJq8uw.png" /><figcaption>Left/Top: <a href="http://www.science.smith.edu/~amcnamara/OpenVisConf/assets/player/KeynoteDHTMLPlayer.html#52">Slides by Amelia McNamara</a>. Can you spot the real data from the fake data? Right/Bottom: <a href="http://ncase.me/OVC2016/">Slides by Nicky Case</a></figcaption></figure><p>And <a href="https://medium.com/u/2c47aca9abda">Nadieh Bremer</a> meticulously decoded SVG properties like gradient, animation, the glow filter, motion blur, the gooey filter, and color blending. These eye candy features spruce up even the most basic data visualizations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*uhV8oWELVBrf6EoX3IQwUg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*fBE-Vz_NM2oOnfXuNYKceA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*MqFPzAgjFjgYvko-sV7_AQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*-17XoxUtQg-xwddSiweF5g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*aCEdvUzzqNqKvO0aztRJxA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/1*GNESihCDvzFMjEjmnoBjQA.gif" /><figcaption><a href="http://www.visualcinnamon.com/2016/04/svg-beyond-mere-shapes.html">Nadieh’s blog post</a> on <a href="http://visualcinnamon.com/">Visual Cinnamon</a>. <a href="http://nbremer.github.io/openvis2016/slides/">Slides by Nadieh Bremer</a>.</figcaption></figure><h4><strong>3. The future of data visualization is virtual, physical, and sonic.</strong></h4><p>“Data <em>visualization”</em> is quickly becoming an understatement for the field. The OpenVis Conference exploited much more than just our visual cortexes. Our ears sampled the building blocks of music in <a href="https://medium.com/u/ecf50d0b8c5">Kyle McDonald</a>’s talk and we experienced a physics lesson in <a href="https://medium.com/u/33e11ced9932">Ana Asnes Becker</a>’s 3D <a href="http://graphics.wsj.com/3d-nasdaq/">ride along the Nasdaq</a>.</p><p>Virtual reality is building a new playground for data visualization — side effects may include nausea. <a href="https://twitter.com/patriciogv">Patricio Gonzalez Vivo</a> showcased the future of 2D and 3D mapmaking using shaders (check out <a href="https://mapzen.com/projects/tangram/">Mapzen’s Tangram</a>).</p><p>We also witnessed robots produce physical data visualizations and data art during breaks at the conference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*Iyc2V7Zkikmh7R_CPHoKbQ.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*YI_IXq2970H3_IkpDR4Q-w.gif" /><figcaption>Left/Top: <a href="http://www.anabeckerdesign.com/vr_talk.pdf">Slides by Ana Asnes Becker</a> Right/Bottom: <a href="http://patriciogonzalezvivo.github.io/openVis16/#/">Slides by Patricio Gonzalez Vivo</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Z3OzBtOBbHnZB6cDDKdKuw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*9Jg3X7uX_gu-7103K1K6Zw.png" /><figcaption>Left/Top: Machine-drawn emoji generated by deep learning. Source: <a href="https://www.flickr.com/photos/kylemcdonald/18630280464">Kyle McDonald</a> Right/Bottom: Robot drawings</figcaption></figure><h4><strong>4. Feature engineering is major </strong>🔑.</h4><p>At the foundation of every well-fit model, successful predictive algorithm, and effective data visualization is hours of feature engineering and data scrubbing.</p><p>Oftentimes, the visualization is just the tip of the iceberg. Sometimes, a single line of code is just the tip of the iceberg (*cough, cough* <a href="https://medium.com/u/39b196537c54">rachel binx</a>)! Data visualizers are all under-the-hood engineers as well as designers and artists.</p><p><a href="https://medium.com/u/bc1eb71ae1c0">Zan</a> Armstrong taught us how to explore time series data to select the appropriate seasonality before modeling. Fernanda Viégas and Martin Wattenberg heavily reinforced the importance of wise feature selection and engineering prior to building a successful machine learning algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*jM7g3v_6e4jEUZ4BTvu4Uw.png" /><figcaption><a href="http://slides.com/zanarmstrong/everything-is-seasonal#/">Slides by Zan Armstrong</a></figcaption></figure><h4><strong>5. Neural networks are 2016’s sexiest algorithm and they are part math, part magic</strong> ✨.</h4><p><a href="http://fernandaviegas.com/">Fernanda Viégas</a> and <a href="http://www.bewitched.com/">Martin Wattenberg</a> from Google’s data visualization group demystified neural nets by demo-ing their recently released <a href="http://playground.tensorflow.org/#activation=tanh&amp;batchSize=10&amp;dataset=circle&amp;regDataset=reg-plane&amp;learningRate=0.03&amp;regularizationRate=0&amp;noise=0&amp;networkShape=4,2&amp;seed=0.41037&amp;showTestData=false&amp;discretize=false&amp;percTrainData=50&amp;x=true&amp;y=true&amp;xTimesY=false&amp;xSquared=false&amp;ySquared=false&amp;cosX=false&amp;sinX=false&amp;cosY=false&amp;sinY=false&amp;collectStats=false&amp;problem=classification">TensorFlow playground</a>.</p><p>With the right amount of hidden layers, nodes, and training data, a neural net can classify just about anything… well, except for images of mugs (again, feature engineering is key).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YSp19XdEWTMs1CThjtrarA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*ezkhhcJXPuTPz4fxxAhrAw.png" /><figcaption>Step 1: drink two glasses of wine</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*kF9aC_ACLeXEP1lURODvFw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*mJhYM104V77b1hOgY52q5Q.png" /><figcaption>Step 2: Build neural net</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*_tfPkwkI9oBZEvUwEk890w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*-9WpuMYRm-WtrNCShhdAOQ.png" /><figcaption>Step 3: ✨</figcaption></figure><h4><strong>6. Text analysis is about to blow up beyond word clouds.</strong></h4><p><a href="https://medium.com/u/dde94a022abc">Christopher Collins</a> led us through a text analysis and visualization <em>spree</em>. In the limited time he had, Christopher whisked us through parallel tag clouds of our country’s legal cases, sunburst diagrams of barbie’s lexicon, and how anomalous information spreads across the web. Christopher’s techniques are novel and mark the launch of a new era of text analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EKASCGLFLVZDpTmSnxaM4Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pRNNUL8e-K5YBiNo2paz6A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gGWRNojMknG8KrKkE3GpJg.png" /><figcaption>Source: <a href="http://vialab.science.uoit.ca/portfolio/christopher-m-collins">Christopher Collins</a></figcaption></figure><h4>7. <strong>Automation is inevitable</strong>.</h4><p>One seventh of the 21 talks focused on components of automation in data visualization. <a href="https://medium.com/u/f4872da040b0">Adam Pearce</a>’s tiny tools developed at Bloomberg Graphics drastically reduce the time spent in iterative tasks like writing redundant lines of code.</p><p><a href="https://medium.com/u/8af35e3f2b62">David Yanofsky</a>’s charting platform uses d3.js and react.js to create brutally simple point-and-click dashboards and charts. <a href="https://medium.com/u/674c27ced68b">Arvind Satyanarayan</a> demo’ed Vega, the reactive programming tool that allows users to declaratively define interactivity and describe features of a visualization directly in a JSON.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3WbjZHlwsKIhwlE1RXaoeQ.png" /><figcaption><a href="http://1wheel.github.io/talks/tiny-tools/#/">Slides by Adam Pearce</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tvLe_kpg5U4SfX2ozohwmg.png" /><figcaption><a href="http://arvindsatya.com/talks/ReactiveVega-OpenVisConf2016.pdf">Slides by Arvind Satyanarayan</a>. <a href="http://vega.github.io/">Vega</a>!</figcaption></figure><h4><strong>8. Data visualization leaves no stone left unturned</strong>.</h4><p>By stone, I mean field of study. We saw disruptive data visualization techniques in a breadth of fields from wine and song to outer space and tennis. We, as data visualization experts, get to play in everyone’s backyard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*dzuQcPvdiKqzWdHft8iaGg.gif" /><figcaption><a href="http://untangling-tennis.net/">Untangling Tennis</a> by Kim Albrecht</figcaption></figure><p><a href="https://medium.com/u/bcb41dfb44a5">Kim Albrecht</a> deconstructed the relationship between performance and popularity in professional tennis. Kim explained the intersection between data science and data visualization and how visualization unites scientists and sparks public dialogues.</p><p><a href="https://www.linkedin.com/in/chriswaigl">Christine Waigl</a> launched us into orbit around the planet and probed into regions of the world affected by climate change and natural disaster. We voyaged through her visualization trajectory from retrieving satellite data to generating quality raster images.</p><h4><strong>9. Good data visualization nods to principles from psychology, neuroscience, and philosophy about how our visual cortex communicates with the rest of our brain and about how we ethically communicate uncertainty.</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*UHm5krylSVNoi8Ze7p0U8A.png" /><figcaption><a href="https://medium.com/@kennelliott/39-studies-about-human-perception-in-30-minutes-4728f9e31a73#.ou753v17e">From Kennedy Elliott’s talk</a></figcaption></figure><p><a href="https://medium.com/u/f3374405c87b">kennedy elliott</a> showed us how pre-attentive processing of image attributes like color, shape, angles, position, curvature, volume, shading, area, length, and direction deeply impacts how humans interpret graphics.</p><p>As designers and data experts, our job requires us to be aware of the inherent biases in graphics to produce accurate and useful tools.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*81ksyNwotgV_-Dyuwv62JQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*F8ysuO_klnWK4N8GNseWcg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*7JoPCVFYMFYYto1NIJLASQ.jpeg" /><figcaption>From Mona Chalabi’s slides</figcaption></figure><p><a href="https://twitter.com/MonaChalabi">Mona Chalabi</a> reminded us to humanize our data and to be receptive to channels of critique like comment sections. Mona would agree that <em>the medium is both the message and the messenger</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*Drozuax4FGfgZk-eu-l4LA.gif" /><figcaption><a href="http://faculty.washington.edu/jhullman/openvis2016_nonotes.pptx.zip%C2%A0%E2%80%A6">Slides by Jessica Hullman</a>. <a href="https://medium.com/hci-design-at-uw/hypothetical-outcomes-plots-experiencing-the-uncertain-b9ea60d7c740#.abd6zuodl">Read more about hypothetical outcome plots here.</a></figcaption></figure><p>In real life, we learn to navigate uncertainty from repeated experiences. <a href="https://twitter.com/JessicaHullman">Jessica Hullman</a> used hypothetical outcome plots to place us in the midst of uncertainty. According to Jessica, “HOPs enable a user to experience uncertainty in terms of countable events, just like we experience probability in our day to day lives.”</p><h4><strong>10. Data nerds are my people!</strong></h4><p>The handsdown most valuable part of the conference was meeting the wildly accomplished and equally curious data visualization and data science explorers.</p><p>I am so grateful to <a href="https://medium.com/u/798242488b19">Irene Ros</a>, the rest of the team at Bocoup, and the sponsors for putting together an outstandingly organized conference. Post-conference depression is a real thing, I learned. Thank you for the knowledge, friends, skills, and ideas. Also, huge thank you to <a href="https://medium.com/u/f4fb2a348280">Salesforce</a> for sponsoring me and my awesome manager Ernest for supporting my attendance!</p><p>One of my favorite stories from the conference happened at the party. I was standing near <a href="https://medium.com/u/12579b0cb1b5">Mariko</a> who prefaced her talk by sharing <a href="http://kosamari.github.io/sweaterify/">how she married her love for knitting sweaters with her love for coding</a>. A data viz engineer at Apple turned to me and asked if I was a knitter myself. Being the R queen that I am, I assumed he was wondering if I was a k<em>nitr</em> user — as in R’s report-generating package ‘knitr’ — to which I responded positively, “Yes! I am a big knitr slash sweave fan.”</p><p>At any other party, I probably would have received a strange look and spent the rest of the night wondering why no one would talk to me. But a data nerd party is different. He understood me immediately, laughed at my misunderstanding, and followed up with more questions about knitr 😂.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4a3a5b96fcd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/10-takeaways-from-22-data-visualization-practitioners-at-openvisconf-a4a3a5b96fcd">10 Takeaways from 22 Data Visualization Practitioners at #OpenVisConf</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>