<?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 Alfred Tang on Medium]]></title>
        <description><![CDATA[Stories by Alfred Tang on Medium]]></description>
        <link>https://medium.com/@alfredtangsw?source=rss-b1b5b8ee7b48------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*cFF1ubKNaPGH6u0E.jpg</url>
            <title>Stories by Alfred Tang on Medium</title>
            <link>https://medium.com/@alfredtangsw?source=rss-b1b5b8ee7b48------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 05:12:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alfredtangsw/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[A Study in RAG]]></title>
            <link>https://medium.com/@alfredtangsw/a-study-in-rag-f59a7c500094?source=rss-b1b5b8ee7b48------2</link>
            <guid isPermaLink="false">https://medium.com/p/f59a7c500094</guid>
            <category><![CDATA[guides-and-tutorials]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <dc:creator><![CDATA[Alfred Tang]]></dc:creator>
            <pubDate>Mon, 18 Aug 2025 14:18:02 GMT</pubDate>
            <atom:updated>2025-08-18T14:19:39.562Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-z4sD5Fy6cGcVPri9GetkA.png" /></figure><p>If you’re already familiar with prompting LLMs, you may have heard of RAG (Retrieval-Augmented Generation).</p><p>But what is it? Why would anyone use it, especially if powerful LLMs like ChatGPT get better and better at giving precise, correct answers?</p><p>There are 3 simple reasons:</p><ol><li>You may get results faster.</li><li>The RAG chain enables you to cite the exact reference pages used to get the answer.</li><li>You want to limit the range of answers to your approved answers/knowledge base.</li></ol><p>This is very useful if your business needs to cite policy documents when responding to customers, but you don’t have the time or manpower to sift through a mountain of information to get the correct answer… and if I know anything about customer service, it’s that customers are generally tremendously short on patience.</p><p>Now that I’ve sung its praises, allow me to show you an example I coded using Sir Arthur Conan Doyle’s first Sherlock Holmes novel, “A Study In Scarlet” as the main document.</p><h3>Requirements</h3><ol><li>Langchain library (and related community packages)</li><li>LLM API key (I used Gemini because it has a free tier)</li><li>Guardrails (optional if you just want to learn RAG and are not concerned about protecting against bad user behaviours)</li></ol><h3>Key Components of an RAG Pipeline</h3><ol><li>Document and Loader</li><li>Text Splitter</li><li>Vector Store</li><li>LLM object</li><li>Chat Prompt Template</li><li>Retrieval Chain</li><li>Guardrails (optional)</li></ol><h3>RAG At A Glance</h3><p>Here is all the code I have used to set up the core RAG pipeline (sans guardrails and invocation; I will cover that later).</p><pre># Basic RAG (Retrieval-Augmented Generation) Project Template with LangChain<br>from langchain.text_splitter import RecursiveCharacterTextSplitter<br>from langchain_huggingface import HuggingFaceEmbeddings<br>from langchain.vectorstores import FAISS<br><br># https://medium.com/towards-agi/how-to-use-gemini-with-langchain-a-step-by-step-guide-6f79c229505e<br>from langchain_google_genai import ChatGoogleGenerativeAI<br><br>from langchain import hub<br>from langchain.chains import create_retrieval_chain<br>from langchain.chains.combine_documents import create_stuff_documents_chain<br><br># use langchain community package to read in PDF<br>from langchain_community.document_loaders import PyPDFLoader<br><br># load the context document<br>loader = PyPDFLoader(&#39;./study_in_scarlet.pdf&#39;)<br>document = loader.load()<br><br># split the text<br>text_splitter = RecursiveCharacterTextSplitter(<br>    separators=[&#39;\n&#39;, &#39;- &#39;], # this is because of the 2-column format of the PDF I use<br>    chunk_size= 500,<br>    chunk_overlap= 100<br>)<br><br>split_text = text_splitter.split_documents(document)<br><br># clean up all the chunked text since we no longer need all the extra &#39;\n&#39;s in-line<br>for doc in split_text:<br>    doc.page_content = doc.page_content.replace(&#39;\n&#39;,&#39; &#39;) # unneeded newlines<br>    doc.page_content = doc.page_content.replace(&#39;- &#39;,&#39;&#39;) # uneeded continuation hyphens<br>    <br># recreate the embeddings and vector store with the new split text<br>embeddings = HuggingFaceEmbeddings(model_name=&quot;sentence-transformers/all-MiniLM-L6-v2&quot;) # redundant code, but good to keep for clarity<br>vector_store = FAISS.from_documents(split_text, embeddings)<br>retriever = vector_store.as_retriever(search_kwargs={&#39;k&#39;:5})<br><br># create the chat prompt for the retrieval chain<br>retrieval_qa_chat_prompt = hub.pull(&quot;langchain-ai/retrieval-qa-chat&quot;)<br><br># create a retrieval chain with the LLM and the chat prompt<br># this passes the context documents to the prompt, which is then passed to the LLM to get a response<br>combine_docs_chain = create_stuff_documents_chain(llm, retrieval_qa_chat_prompt)<br>rag_chain = create_retrieval_chain(retriever, combine_docs_chain)</pre><p>One really good thing about Langchain is that it abstracts away a lot of steps I would have done manually when doing NLP, whether using pure Python or using packages like spaCy. Tokenisation is a breeze with Huggingface Embeddings!</p><p>Now, let’s go over the code step by step.</p><h3>1. Document and Loader</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*iiV4wYoSWyZUAUqzfbARyw.png" /><figcaption>Chapter 1, Page 1 of A Study In Scarlet</figcaption></figure><p>I used a digitally typeset version of A Study In Scarlet from <a href="https://sherlock-holm.es/stories/pdf/a4/2-sided/stud.pdf">https://sherlock-holm.es/stories/pdf/a4/2-sided/stud.pdf</a>.</p><p>The type of input matters, because if you use a flat image PDF, you will have to use OCR (optical character recognition) to extract the text in a machine-readable form. That in itself can be a monumental task.</p><p>Here’s what it looks like when read into Python:</p><pre># load the context document<br>loader = PyPDFLoader(&#39;./study_in_scarlet.pdf&#39;)<br>document = loader.load()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6MdBGfRvPEl5SpC9T12sAA.png" /></figure><h3>2. Split Text</h3><pre># split the text<br>text_splitter = RecursiveCharacterTextSplitter(<br>    separators=[&#39;\n&#39;, &#39;- &#39;], # this is because of the 2-column format of the PDF I use<br>    chunk_size= 1000,<br>    chunk_overlap= 200<br>)<br><br>split_text = text_splitter.split_documents(document)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CewzNvjCY5PmOYKXOCttNQ.png" /></figure><p>If you print out the text as-is, it will print in the same manner that you saw in the screenshot above. Notice that the right side column is not printed here (yet another convenient abstraction thanks to the Langchain developers and community)!</p><p>Also, we don’t need the ‘\n’ and ‘- ’ linebreaks and continuation hyphens anymore so we remove them.</p><pre># clean up all the chunked text since we no longer need all the extra &#39;\n&#39;s in-line<br>for doc in split_text:<br>    doc.page_content = doc.page_content.replace(&#39;\n&#39;,&#39; &#39;) # unneeded newlines<br>    doc.page_content = doc.page_content.replace(&#39;- &#39;,&#39;&#39;) # uneeded continuation hyphens</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JB9K41-B6T1dABVxbeWYmw.png" /></figure><h3>3. Vector Store</h3><pre>embeddings = HuggingFaceEmbeddings(model_name=&quot;sentence-transformers/all-MiniLM-L6-v2&quot;)<br>vector_store = FAISS.from_documents(split_text, embeddings)</pre><p>The above code stores the split text as vectors into a “vector store”. Think of it as a series of numbers representing the characters found in each line of the whole document.</p><h3>4. LLM Object</h3><pre>retriever = vector_store.as_retriever(search_kwargs={&#39;k&#39;:5})<br>llm = ChatGoogleGenerativeAI(<br>        model=&#39;gemini-2.5-pro&#39;,<br>        google_api_key=os.getenv(&#39;GEMINI_API_KEY&#39;), #call Gemini key from dotenv file<br>        temperature=0.5<br>    )</pre><p>Here, we create the Python object that enables us to interact with the LLM API (in this case, I chose to use gemini-2.5-pro for testing purposes). You can set the temperature to 0.0 to get essentially get the same results every query or set a moderate temperature to introduce some variability that may get you better (or worse) answers.</p><p>The search_kwargs will also let you choose how many documents to include in the context, but we will leave it at 5 for now.</p><h3>5. Chat Prompt Template</h3><pre>retrieval_qa_chat_prompt = hub.pull(&quot;langchain-ai/retrieval-qa-chat&quot;)</pre><p>The chat prompt template is taken from <a href="https://smith.langchain.com/hub/langchain-ai/retrieval-qa-chat">https://smith.langchain.com/hub/langchain-ai/retrieval-qa-chat</a>, which looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*WXHtWDeA7k3taRtGsY-WnQ.png" /></figure><p>This means you don’t have to manually enter the prompt and context every time you send a query to the LLM API.</p><h3>6. Retrieval Chain</h3><pre># create a retrieval chain with the LLM and the chat prompt<br>combine_docs_chain = create_stuff_documents_chain(llm, retrieval_qa_chat_prompt)<br>rag_chain = create_retrieval_chain(retriever, combine_docs_chain)</pre><p>create_stuff_documents_chain will take the documents most relevant to the user’s prompt and “stuff” them into the context section in the ChatPromptTemplate above, then send the context and prompt together to the LLM API to get the result.</p><h3>RAG In Action</h3><p>Now that we have a functional RAG pipeline, let’s do some prompting!</p><p>Here’s the code for using the RAG chain (the .invoke() method is key):</p><pre>response = rag_chain.invoke({&quot;input&quot;: &quot;Is Sherlock Holmes well-versed in chemistry?&quot;})</pre><p>We are mainly interested two things:</p><ol><li>Can the LLM answer the question?</li><li>How fast does the response come?</li></ol><h4>First, let’s test prompting Gemini with no context whatsoever.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M5RcvOf33e0nvly2dNWIAQ.png" /><figcaption>Test 1 — Who introduced John Watson to Sherlock Holmes?</figcaption></figure><pre>AIMessage(content=&quot;Dr. Watson was introduced to Sherlock Holmes by **Stamford**.\n\nIn the first Sherlock Holmes story, *A Study in Scarlet*, Watson has just returned to London from the Second Anglo-Afghan War and is looking for affordable lodging. He runs into his old friend and former surgical dresser, Stamford, who mentions that he knows someone else in the same situation: Sherlock Holmes.\n\nStamford then takes Watson to the chemical laboratory at St. Bartholomew&#39;s Hospital, where the famous introduction takes place.&quot;, additional_kwargs={}, response_metadata={&#39;prompt_feedback&#39;: {&#39;block_reason&#39;: 0, &#39;safety_ratings&#39;: []}, &#39;finish_reason&#39;: &#39;STOP&#39;, &#39;model_name&#39;: &#39;gemini-2.5-pro&#39;, &#39;safety_ratings&#39;: []}, id=&#39;run--4f55ca68-54d0-4103-9981-a86c6a2fbe98-0&#39;, usage_metadata={&#39;input_tokens&#39;: 9, &#39;output_tokens&#39;: 700, &#39;total_tokens&#39;: 709, &#39;input_token_details&#39;: {&#39;cache_read&#39;: 0}, &#39;output_token_details&#39;: {&#39;reasoning&#39;: 598}})</pre><p>The answer was good, but the response time was 8.5 seconds and the text read like it was quoting from a synopsis of Chapter 1.</p><h4>Second, we use RAG to ask the same question.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MREYArkqrVY_O8RJ8Pb7Vw.png" /></figure><p>The answer is correct, and the answer comes within 4 seconds. It’s fast and accurate! But is this always the case?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZSKHdHHzOCMaVab5Lwy_tw.png" /></figure><p>With some variation of the question, the LLM becomes unable to answer the question under the current setup. The answer is clearly wrong, since the previous (similar) question was correctly answered.</p><p>This question is more complex and expects specific references to a first meeting. While we readers understand it was their first meeting, the supporting documents are scored by relevance. If no text is related to a “first meeting”, then we may not get the result we want.</p><p>What can we do then?</p><h4>Third, we re-split the text under new settings.</h4><pre>text_splitter = RecursiveCharacterTextSplitter(<br>    separators=[&#39;\n&#39;, &#39;- &#39;],<br>    chunk_size= 500, # originally 1000, will try 500 to see if shorter context is better<br>    chunk_overlap= 100 # originally 200, will try 100 to see if shorter overlap is better<br>)</pre><p>LLMs are trained to look at the entire prompt, so if there is too much extra information, it may get confused. The similarity scores for document retrieval will also be different if the chunk sizes are too large.</p><p>So, I cut both chunk size and chunk overlap in half so the sentences would be shorter and some of them could have higher relevance scores. This time, the same challenging question was answered correctly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1v7mto-_NxteA9vHDY-_pg.png" /></figure><p>It did, however, take just over 8 seconds to answer this question.</p><h4>Fourth, we test the impact of using more documents.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xJyrhmxectECjV3uVJifRA.png" /></figure><p>With 5 documents, the answer given is that Sherlock Holmes is knowledgeable about poisons, but does not state that he is addicted to narcotics (as depicted in the TV series).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p-YIe4Vgvytct8vXw0FTMA.png" /></figure><p>With 10 documents, we receive a more detailed answer which suggests that he may know a lot about poisons, but it is not possible to determine that he has an addiction to narcotics. The answer takes longer to arrive as well.</p><h3>Citations</h3><p>It is also possible to cite the documents used in the context when you receive the response from the LLM:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*9hbopowUrMGAL2gC7MI9GQ.png" /></figure><h3>Bonus: Guardrails</h3><p>For those who are still reading here, I have a gem for you. We’re going to try out guardrails to prevent processing bad prompts that are unrelated to Sherlock Holmes!</p><pre>from guardrails import Guard<br>from guardrails.hub import CompetitorCheck, ToxicLanguage<br>competitors_list = [&#39;detective conan&#39;, &#39;nancy drew&#39;, &#39;dick tracy&#39;, <br>                    &#39;hercule poirot&#39;, &#39;miss marple&#39;, &#39;phryne fisher&#39;, <br>                    &#39;veronica mars&#39;]<br>guard = Guard().use_many(<br>    CompetitorCheck(competitors=competitors_list, on_failure=&quot;fix&quot;),<br>    ToxicLanguage(threshold=0.5, <br>                  validation_method=&#39;sentence&#39;, on_failure=&quot;fix&quot;)<br>    )</pre><p>Using Guardrails AI takes fair bit of setup, but with it we are able to block unrelated prompts such as those asking about other famous fictional detectives (competitors_list) or toxic language.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*BRKPK6lNu6gcKcLh-7ti2w.png" /><figcaption>Asking about Detective Conan throws an exception!</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*aCMOwoUxOz8S_ZsTdAhJ4A.png" /><figcaption>Both a competitor and insulting language are used here, resulting in an exception.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*aC3MEdMrdCa5AR55-RNEfA.png" /><figcaption>Insulting prompts are not welcome.</figcaption></figure><p>By using guardrails, we can validate that the prompt is safe before we even send it to the LLM for a response!</p><h3>RAG In Summary</h3><p>RAG is great for use cases where you need answers a little faster, without a huge risk of hallucinated information. It is also useful when you need to cite the exact pages used as well, in case users want to see the related policy.</p><p>RAG is quite simple to set up as well. This project took me about 2 working days of effort to complete, thanks to the many conveniences Langchain and the community packages that have been developed for it.</p><p>Are you ready for your Study in RAG? Give it a shot!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f59a7c500094" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Honey, I Shrank the Holiday Photos!]]></title>
            <link>https://blog.stackademic.com/honey-i-shrank-the-holiday-photos-aa0052fcd13f?source=rss-b1b5b8ee7b48------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa0052fcd13f</guid>
            <category><![CDATA[georgia-tech]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[study]]></category>
            <category><![CDATA[linear-algebra]]></category>
            <category><![CDATA[numpy]]></category>
            <dc:creator><![CDATA[Alfred Tang]]></dc:creator>
            <pubDate>Sun, 14 Apr 2024 15:31:40 GMT</pubDate>
            <atom:updated>2024-04-18T00:23:01.613Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>A self-declared capstone project for Georgia Tech’s CSE6040: Computing for Data Analysis: Image Compression with Linear Algebra SVD.</em></h4><p>I’m two modules into my Master’s in Analytics at Georgia Tech now.</p><p>For my final assignment in CSE6040 Computing for Data Analysis course, we were tasked to answer a number of linear algebra questions aimed at helping us understand some concepts.</p><p>The theme was Singular Value Decomposition, which has famous applications in…would you have guessed it? Image compression!</p><p>In this article, I will apply some of the concepts I learnt as my own personal capstone project. (I can’t share the answers to the assignment online, so I decided to create my own project instead.)</p><p>My Python Notebook can be found here: <a href="https://github.com/alfredtangsw/GATech_01_CSE6040_CDA/blob/main/image_comp_linalg_svd.ipynb">https://github.com/alfredtangsw/GATech_01_CSE6040_CDA/blob/main/image_comp_linalg_svd.ipynb</a></p><pre>import os<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import matplotlib.image as mImage<br>from PIL import Image</pre><h3>Concept</h3><p>Image compression is something we are all familiar with as people who live in the era of social media. But how is it done?</p><p>First, let’s look at an image and how it can be represented in a computing environment.</p><pre>cwd = os.getcwd()<br>img = Image.open(os.path.join(cwd,&#39;svd_demo.jpg&#39;))<br>plt.figure(figsize=(9,6))<br>plt.imshow(img)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oSwluW-drN-Oc9IgVXn41g.jpeg" /></figure><p>I took the above image during a trip to Osaka, Japan in 2023.</p><p>I have lots of fond memories from that trip! It was my first time in Japan and I spent a good 18 days there.</p><p>Osaka was the last leg and I wanted to capture some cyberpunk-inspired pictures before I left for home.</p><p>Now, can I turn these memories into numbers? And how?</p><pre># Images come as 3D numpy arrays, 1 array for each colour channel (R, G, B)<br>print(np.array(list(img.getdata())).shape) # (6705000, 3)<br>print(img.size) # (2250, 2980)</pre><pre># We&#39;ll get just the 0th band (R) and turn it into a numpy array with the same dimensions as the image<br>mat = np.array(list(img.getdata(band=0)), float).reshape(img.size[1], img.size[0])<br>mat<br>-------------------------------------------------------------------------<br>array([[29., 33., 36., ..., 14., 13., 13.],<br>       [31., 34., 37., ..., 10., 10., 10.],<br>       [31., 33., 38., ...,  5.,  6.,  6.],<br>       ...,<br>       [22., 25., 21., ...,  2.,  0.,  0.],<br>       [26., 28., 23., ...,  1.,  0.,  0.],<br>       [37., 39., 33., ...,  0.,  0.,  0.]])</pre><pre># Visualise the one-channel matrix as an image<br>plt.figure(figsize=(9,6))<br>plt.imshow(mat)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*orqIrQyN2BRnwAja_I_7Iw.png" /></figure><h3><strong>Basic Properties of Matrices</strong></h3><p>To understand how compression is done on a matrix, first, we have to understand a matrix.</p><p>First, here are some basic properties of matrices.</p><ol><li>Matrices can be factorised into 3 component matrices by Singular Value Decomposition (SVD):</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/181/0*DCPyCWwEsWYgR_ec" /></figure><p>2. Every matrix of real numbers has a Singular Value Decomposition.</p><pre>U, sigma, VT = np.linalg.svd(mat)</pre><h3><strong>Intuition: Compressing an Image with Truncated SVD</strong></h3><p>Now, how do we use U, Sigma, and VT?</p><p>If we multiplied them back together, we would get the exact same image back again, 100%, pixel for pixel, because mathematically, M = U * Sigma * VT.</p><p>In compressing an image, we know that we lose some resolution.</p><p>How is it that we lose resolution but still retain the essential information (shapes and colours) of the image?</p><p>Similar to principal component analysis (PCA), we select a certain number (K) of rows and columns from each decomposed factor of the matrix.</p><p>This will approximate the original matrix using the truncated SVD:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/0*PFrgLSoA987AKA1l" /></figure><pre># Let&#39;s set K=1 and see what we get out of it<br>k = 1<br>uncompress = np.matrix(U[:,:k]) @ np.diag(sigma[:k]) @ np.matrix(VT[:k,:])<br>plt.imshow(uncompress)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*ZcpBhhU34D-1GvAyYoBdzw.png" /><figcaption>We got a very rough idea of what the image should look like, but not much else.</figcaption></figure><h4><strong>What’s Sigma? Why is it not a matrix? Why did you apply np.diag() to it?</strong></h4><p><strong>Sigma</strong></p><p>Imagine two arrows orthogonal to each other. These two arrows represent U (left singular vectors) and VT (right singular vectors).</p><p>Sigma tells you how strong the relationship is between U and VT.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HZ_hm5MJ265vE4F_.png" /><figcaption>Credit: Gregory Gundersen (<a href="https://gregorygundersen.com/blog/2018/12/10/svd/">https://gregorygundersen.com/blog/2018/12/10/svd/</a>)</figcaption></figure><p>You can see a full worked example here as this is not the focus of my article: <a href="https://medium.com/intuition/singular-value-decomposition-svd-working-example-c2b6135673b5">https://medium.com/intuition/singular-value-decomposition-svd-working-example-c2b6135673b5</a></p><p><strong>Why apply np.diag()?</strong></p><p>np.diag() is necessary because Sigma is meant to be a diagonal matrix, e.g.:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/62/0*th5uUsxmvusqTZEa.png" /></figure><p>Now, since…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/0*PFrgLSoA987AKA1l" /></figure><p>and M (the image) is a matrix with dimensions (2980, 2250)…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/287/0*W_j_0Eq_F-HwIZm8.png" /></figure><p>… you must apply np.diag() on Sigma to make it (k,k) dimensions and enable the output to be the same dimensions as the original picture.</p><p><strong>Why is Sigma not a matrix?</strong></p><p>As output by Numpy, Sigma is a 1D vector. Why?</p><p>Say the image from my below-average phone camera is a 2980 x 2250 matrix. A diagonal Sigma matrix has to be (2250, 2250) in shape with a lot of 0 values.</p><p>This sparse matrix has 5,062,500 values (0.6 to 1 MB) and is very expensive and wasteful to hold in memory or storage for no additional information gained.</p><p>It may not be a big deal for an image from my phone, but imagine using images from an ultra-high-res camera which gives you 100,000 x 100,000 pixel images.</p><p>Your Sigma has to be (100,000 x 100,000) in shape, again with a lot of 0 values: 10,000,000,000 (10 billion bits, 1.16GB++).</p><p>You’ll run out of memory and space really fast if you keep a lot of sparse matrices!</p><p><strong>Compression</strong></p><p>The first value of Sigma is always the largest. The same goes for U and VT.</p><p>By selecting the first K of each and multiplying them together, we can reconstruct the images in varying levels of detail.</p><pre>limit = 5<br>max_vectors = 150<br>step = 10<br>fig, ax = plt.subplots(int(max_vectors/step/limit), limit, figsize=(25, 20))<br><br>curr_fig=0<br>for k in range(0, max_vectors, step):<br>    uncompress = np.matrix(U[:,:k]) @ np.diag(sigma[:k]) @ np.matrix(VT[:k,:])<br>    title = f&quot;Number of vectors = {k}&quot;<br>    fignum = int(curr_fig/limit)<br>    subplot_num = curr_fig%limit<br>    ax[fignum][subplot_num].imshow(uncompress, cmap=&#39;gray&#39;,)<br>    ax[fignum][subplot_num].set_title(title)<br>    ax[fignum,subplot_num].axis(&#39;off&#39;)<br>    curr_fig += 1<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HpE4EURGcDSNUFwwp-rypA.png" /></figure><p><strong>Compression successful!</strong></p><p>We have managed to compress the image successfully using only 140 of the original 2250 vectors.</p><p>What’s the current image’s percentage of the original image size?</p><pre># Check compressed image vs. original image size<br>original_size = np.product(mat.shape)<br><br>chosen_k = 140<br>compressed_size = chosen_k/len(sigma) * mat.shape[0] + chosen_k + chosen_k/len(sigma) * mat.shape[1]<br>compressed_size/original_size * 100<br>---------------------------------------------------------------------<br>0.006941420167370951</pre><p>We’re using an incredibly low 0.007% of the original image’s data!</p><p>Granted, the 140-vector image is still grainy… but it’s clear enough that it’s the same image I took in Osaka.</p><p>This is not how we would use it in real life. The point of the exercise so far was to just demonstrate how much storage space compression can save.</p><p>Now, I’m going to try and do the same for a coloured image!</p><pre>def compress_image(U, S, VT, k):<br>    return (U[:,:k] @ np.diag(S[:k])) @ VT[:k]</pre><pre># Read the image in as a 3-dimensional array (3 dimensions corresponding to the R, G, B colour channels)<br>A = mImage.imread(&#39;svd_demo.jpg&#39;)<br>A<br>------------------------------------------------------------------<br>array([[[29, 57, 78],<br>        [33, 61, 82],<br>        [36, 64, 85],<br>        ...,<br>        [14, 30, 45],<br>        [13, 29, 44],<br>        [13, 29, 44]],<br><br>       [[31, 59, 80],<br>        [34, 62, 83],<br>        [37, 65, 86],<br>        ...,<br>        [10, 26, 41],<br>        [10, 26, 41],<br>        [10, 26, 41]],<br><br>       [[31, 62, 83],<br>        [33, 64, 85],<br>        [38, 66, 88],<br>        ...,<br>        [ 5, 23, 37],<br>        [ 6, 22, 35],<br>        [ 6, 22, 35]],<br><br>       ...,<br>...<br>        [33, 64, 84],<br>        ...,<br>        [ 0,  2,  1],<br>        [ 0,  2,  1],<br>        [ 0,  2,  1]]], dtype=uint8)</pre><pre># Normalise the image matrices so that all values lie within range 0.0 to 1.0<br>R = A[:,:,0] / 255<br>G = A[:,:,1] / 255<br>B = A[:,:,2] / 255<br><br># Get the SVD vectors of the 3 colour channels<br>R_U, R_S, R_VT = np.linalg.svd(R)<br>G_U, G_S, G_VT = np.linalg.svd(G)<br>B_U, B_S, B_VT = np.linalg.svd(B)</pre><pre>def compress_by_rank(relative_rank:float=1.0):<br>    &quot;&quot;&quot;<br>    This function compresses my Osaka image by &quot;relative_rank&quot;. <br>    Basically, this parameter stands for how many % of the data do you want to use.<br>    &quot;&quot;&quot;<br>    assert 0.0 &lt;= relative_rank &lt;= 1.0, &quot;Relative rank must be a number between 0.0 and 1.0!&quot;<br>    max_rank = int(relative_rank * min(R.shape[0], R.shape[1]))<br>    print(&quot;max rank = %d&quot; % max_rank)<br>    R_comp = compress_image(R_U, R_S, R_VT, max_rank)<br>    G_comp = compress_image(G_U, G_S, G_VT, max_rank)<br>    B_comp = compress_image(B_U, B_S, B_VT, max_rank)<br>    compressed_float = np.dstack((R_comp, G_comp, B_comp))<br>    compressed = (np.minimum(compressed_float, 1.0) * 255).astype(np.uint8)<br>    return compressed</pre><pre># Let&#39;s test 1% of the data<br>compressed = compress_by_rank(0.01)<br>plt.figure(figsize=(9,6))<br>plt.imshow(compressed)<br>-----------------------------------------------<br>max rank = 22</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*B62-W3wFsB4oqMWSwdCWXw.png" /><figcaption>K = 22</figcaption></figure><p>Trying the compress_by_rank() function with 5% of the data results in:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*Zu6dYaC8AaGTOcMWKIabAw.png" /><figcaption>K=112</figcaption></figure><p>Lots of red and yellow spots around. The image is still very noisy. Let’s try 20% of the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*6cTmO9lEoAKDMKPtu-iESg.png" /><figcaption>K=450</figcaption></figure><p>There are still noticeable spots. Let’s try 40%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*mymky4cWgbDKjl0m_AY1-w.png" /><figcaption>K=900</figcaption></figure><h3><strong>Finding the best K or best relative rank</strong></h3><p>It seems that we needed more vectors (900, or 40% of all the data) to get a nice coloured image with no red or green spots.</p><p>This is a big difference from greyscale, where just 100 could produce an acceptable image.</p><p>This goes to show that I have more to learn and that the same rules won’t always apply to every transformation.</p><p>Also, there seem to have been no weird blue spots — this is probably due to the image being very dominated by blue and also blue’s similarity to black. Maybe the spots are there but it’s not noticeable.</p><h3><strong>Objective vs. Heuristic Compression</strong></h3><p>We’ve managed to find some sweet spots (900 for colour images) by trial and error.</p><p>Is there a mathematical, objective way to find the exact rank that minimises the error and maximises the compression?</p><p>Yes!</p><pre>def find_best_k(target_err:float, S:np.ndarray):<br>    &quot;&quot;&quot;<br>    Finds best K from a given Sigma array<br>    &quot;&quot;&quot;<br>    assert 0.0 &lt;= target_err &lt;= 1.0<br>    squared_err = S**2                  # Sigma is already from largest to smallest... [8, 4, 0]... square it --&gt; [64, 16, 0]<br>    sorted_err = squared_err[::-1]      # Sort Sigma so that the smallest error will be first and the largest will be last... [0, 16, 64]<br>    ranks = np.cumsum(sorted_err)[::-1] # Sum all the errors cumulative from smallest to largest... [0, 16, 80]... then reverse them... [80, 16, 0] --&gt; get a list of descending squared error values<br>    sq_rel_err = ranks/ranks[0]         # Divide all the squared errors by the largest squared error. This lets us find the point at which the error drops sufficiently to meet the target error.<br>    rel_error = np.sqrt(sq_rel_err)     # Square root all the errors so they can be compared to target error<br>    return np.min(np.where(rel_error &lt; target_err)) # Get the smallest value of K that meets the targeted error</pre><p>We will also need to modify the existing function that puts together the colour image, because the optimal K for each colour channel is not necessarily the same.</p><pre>def compress_by_best_rank(target_err=0.10):<br>    &quot;&quot;&quot;<br>    This function finds the best K for each colour channel.<br>    &quot;&quot;&quot;<br>    best_R_k = find_best_k(target_err, R_S)<br>    best_G_k = find_best_k(target_err, G_S)<br>    best_B_k = find_best_k(target_err, B_S)<br>    print(f&#39;Best K --- R:{best_R_k} | G:{best_G_k} | B:{best_B_k}&#39;)<br>    <br>    R_comp = compress_image(R_U, R_S, R_VT, best_R_k)<br>    G_comp = compress_image(G_U, G_S, G_VT, best_G_k)<br>    B_comp = compress_image(B_U, B_S, B_VT, best_B_k)<br>    compressed_float = np.dstack((R_comp, G_comp, B_comp))<br>    compressed = (np.minimum(compressed_float, 1.0) * 255).astype(np.uint8)<br>    return compressed</pre><pre># Let&#39;s try allowing 5% error<br>compressed = compress_by_best_rank(0.05)<br>plt.figure(figsize=(9,6))<br>plt.imshow(compressed)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*9Qv_-pDBkpib2UN-0xhjIg.png" /><figcaption>Best K — — R:282 | G:239 | B:197</figcaption></figure><p>Hmm. Still lots of red and green spots. Let’s target a 2% relative error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*sXrehiJCmn28VgAppsCNNA.png" /><figcaption>Best K — — R:542 | G:474 | B:417</figcaption></figure><p>There are still obvious red and green spots! Let’s finally target a 1% relative error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*ihP_n4AMOzyHdVObgab8VQ.png" /><figcaption>Best K — — R:801 | G:711 | B:647</figcaption></figure><h3><strong>Conclusion</strong></h3><p>1. Compression saves a ton of space vs. the original data (99% is possible)</p><p>2. It’s also possible to compress a colour image in the same way, but you need to do the same process for all 3 colour channels.</p><p>3. There is an objective, mathematical way to find the best number of vectors for minimising error to your desired level while maximising the compression effect.</p><p>4. It’s much easier to compress a greyscale image than a coloured image! The optimal K may differ for each colour channel, and low mathematical error does not mean an acceptable image to the human eye.</p><h3><strong>CSE6040 Course Review</strong></h3><p>I greatly enjoyed CSE6040 at Georgia Tech.</p><p>It gave me a better appreciation of the power of Numpy, the weakness of for loops (especially nested for loops), and the need for alternative storage formats for sparse matrices [e.g. Compressed Sparse Row Format (CSR), Coordinate Format (COO)]</p><p>The content was rigorous and required a lot of thinking to resolve challenges intentionally set to prevent you from using “hacky” methods to resolve them. A lot of the time, I had to go and find my own answers (which suits my personality well).</p><p>Some practise problems even had us implementing classic data science algorithms such as Continuous Bag of Words, K Means Clustering, and Neural Network forward passes from scratch using just Numpy.</p><p>What excited me, though, was being able to put the skills into practise by compressing my own pictures using the skills I just learnt.</p><p>Even with my 4 years of experience in data science and programming, I learnt a lot from this module. I’ve gotten full marks thus far, and all that remains for this module is the final exam.</p><p>I’m looking forward to everything else that Georgia Tech has to offer!</p><h3>References</h3><ol><li><a href="https://zerobone.net/blog/cs/svd-image-compression/">https://zerobone.net/blog/cs/svd-image-compression/</a></li><li><a href="https://www.frankcleary.com/svdimage/">https://www.frankcleary.com/svdimage/</a></li><li><a href="https://medium.com/intuition/singular-value-decomposition-svd-working-example-c2b6135673b5">https://medium.com/intuition/singular-value-decomposition-svd-working-example-c2b6135673b5</a></li><li><a href="https://gregorygundersen.com/blog/2018/12/10/svd/">https://gregorygundersen.com/blog/2018/12/10/svd/</a></li></ol><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa0052fcd13f" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/honey-i-shrank-the-holiday-photos-aa0052fcd13f">Honey, I Shrank the Holiday Photos!</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[4 Steps for Mastering New Skills… or Switching Careers]]></title>
            <link>https://medium.com/@alfredtangsw/4-steps-for-mastering-new-skills-or-switching-careers-ea2fc612bd83?source=rss-b1b5b8ee7b48------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea2fc612bd83</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[martial-arts]]></category>
            <category><![CDATA[determination]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[career-change]]></category>
            <dc:creator><![CDATA[Alfred Tang]]></dc:creator>
            <pubDate>Thu, 31 Aug 2023 15:39:51 GMT</pubDate>
            <atom:updated>2023-08-31T15:44:56.083Z</atom:updated>
            <content:encoded><![CDATA[<p>What do learning frameworks and career switches have to do with Brazilian Jiu-Jitsu? Surprisingly, a lot! At least, it does for me.</p><p>Let me share a gem I found today. I came across this video by Monash University’s top graduate (Master’s in Education) and a learning expert, Justin Sung.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F3Z7frfjiEcM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D3Z7frfjiEcM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F3Z7frfjiEcM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b36017ffa68a89ab95fbcd39fa433f70/href">https://medium.com/media/b36017ffa68a89ab95fbcd39fa433f70/href</a></iframe><p>This video was a timely find, since I recently started studying a Master’s in Analytics at Georgia Tech. It also helps with my work. The ability to learn fast is really important for a data scientist, since technology keeps evolving.</p><p>To summarise Justin Sung’s 4-Step Framework, I’ve condensed this video into 4 key points here in my own words.</p><h3>1. Aim High</h3><p>Aim to fully understand what you’re learning. Even if you don’t get 100% of it, you’ll get pretty close.</p><h3>2. Cram Early, Not Late</h3><p>Learn as much as possible at the early stage of each module. This gives you a push to learn fast and still gives you time flexibility. Cramming at the end, towards exams and deadlines, creates negative and unhelpful stress.</p><p>Reading alone will not be enough. Practise builds your understanding and retention, because the brain retains what it uses and prunes everything else. Leave details for later; the brain tends to glaze over those initially.</p><h3>3. Build on Prior Knowledge</h3><p>Learn in cycles. It’s how the brain works.</p><p>First, build a general understanding. Come back for more rounds later to fill in any details as needed.</p><p>Consolidate what you learn regularly, not just at the end. You will likely have forgotten what you learned if you leave it for too long.</p><h3>4. Use Limited Resources Strategically</h3><p>Time is limited for everyone, including yourself. Just like filling in details at later stages, asking an expert about finer points helps you learn more advanced topics faster. While you could also ask them for help with basic ones, it would not be the best use of time for both you and the expert.</p><h3>How I Learnt to Learn Fast</h3><p>When I made my career switch in 2019, I had been an analyst for about a year. I only knew Excel and VBA, had very little background in programming, and the last time I had done some serious calculus was 10 years ago when I studied mechanical engineering.</p><p>To successfully switch careers, I had to <strong><em>learn how to learn fast</em></strong>.</p><p>Fortunately, as a writer, I’ve learnt that you can find inspiration and important lessons from your entire human experience, and sometimes from the most unexpected places.</p><p>The one memory that sticks out where learning is concerned is a Brazilian Jiu-Jitsu training session from 15 years ago. We were discussing what the “best” technique would be to use in a given situation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/0*Q5zVeGG9CX-3Qduo" /><figcaption>Time really flies.</figcaption></figure><p>Aware that our discussion would never end, our instructor gathered us to share a valuable lesson:</p><blockquote>Guys, don’t obsess over techniques. I’ve learned all kinds of advanced sweeps, rubber guard, spider guard, and so on… but in the end, what I rely on most is the basic full guard and scissor sweep. Everything comes from the basics.</blockquote><p>It so happened that I needed to revise a whole semester’s worth of thermodynamics for an upcoming exam, so I thought I’d try it out. I collected all my tutorials and drilled myself in every topic, from the most basic to the most challenging questions.</p><p>By the time exams came around, I was confidently attempting past-year exam papers. I was no longer focused on passing; now I wanted to ace the exam!</p><p>The last two days of cramming were physically painful. I had 5 cups of milk tea each day and sat at my desk the whole time except for meals and sleep. Right after the paper, I had a massive headache so I went home and slept for over 12 hours straight. (Seriously, cram early, not late!)</p><p>I did well in the end, scoring an A for the paper and the module. Ever since then, I’ve held these lessons close to my heart:</p><ol><li>You can teach yourself something from scratch if you want to. The information is available on the Internet. The rest is up to you.</li><li>Everything comes from the basics. Start from there and keep drilling with progressively tougher and more varied tasks.</li></ol><h3>Applying the Lessons to my Career Switch</h3><p>It goes without saying. Career switches are scary, because you’re leaving behind everything you know for new territory. At the same time, they may just be the best thing you’ll ever do for yourself… so what’s the best way to prepare and ensure your career change is successful?</p><p>Let me share some steps I took:</p><ol><li><strong>Prepare while the stakes are low. </strong>I took about 2 years to decide to switch careers. While working a stable writing job, I finished my Master’s in Finance and took on a data analyst role so I could figure my direction out efficiently.</li><li><strong>Get expert opinions. </strong>I was able to work closely with a data scientist and asked him I needed to learn to become one too. He said, and I quote: “You want to be data scientist? Learn maths. Learn programming. Do projects. You will be okay.”</li><li><strong>Pick up the basics early .</strong> I knew there wouldn’t be time to catch up once the course began, so I studied basic statistics, probability, and programming at night after work and on weekends.</li><li><strong>Fully immerse yourself. Get the necessary qualification. </strong>I joined General Assembly to study data science. I fully committed to my new career, leaving my job after ensuring that I had enough cash to survive a year without income. That was the time limit; beyond that, I would have to seriously reconsider my career switch.</li><li><strong>Learn by practising. </strong>At GA, we gained a lot of practical experience and learned to design solutions because of the daily programming challenges and the key projects assigned to us. Experience is the best teacher.</li><li><strong>Improve in iterations.</strong> As long as it works and solves the problem, you can move on to the next iteration. Done is better than perfect. Improved is better than done. Deliver your product!</li></ol><p>I’ve managed to get into a data scientist role since then, but it was a struggle. If I’d learnt about the methods Justin Sung teaches, I might have been able to better strategise how I learn.</p><p>But hey, it’s never too late. I’ll start today!</p><h3>TL;DR: Simple Steps for Learning Effectively</h3><p>Start early. Go over the content and get some context before you go deep into it during lessons.</p><p>Start small. Practise a simpler version of the skill you’re picking up. Scale up with each iteration.</p><p>Consistency and relevance are key. Learn 1 new technique every week. Try 1 new ML algorithm every month.</p><p>Trust the process.</p><p>Everything’s hard at the beginning, but I promise you, you’ll get better.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea2fc612bd83" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streamlit: Deploy Your App in 2 Hours!]]></title>
            <link>https://medium.com/@alfredtangsw/streamlit-deploy-your-app-in-2-hours-ef0c1c4909b7?source=rss-b1b5b8ee7b48------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef0c1c4909b7</guid>
            <category><![CDATA[streamlit-app-deployment]]></category>
            <category><![CDATA[streamlit]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[app-deployment]]></category>
            <dc:creator><![CDATA[Alfred Tang]]></dc:creator>
            <pubDate>Sat, 12 Aug 2023 17:04:32 GMT</pubDate>
            <atom:updated>2023-08-12T17:09:54.875Z</atom:updated>
            <content:encoded><![CDATA[<p>A friend of mine mentioned Streamlit for app deployment to me recently, and I got curious.</p><p>I’ve been working on some machine learning projects, but creations that are just sitting in your hard drive aren’t being useful to anyone, are they?</p><p>It’s important to make sure people can see, feel, and use what you’ve created, so I thought I’d give it a try.</p><p>What I wasn’t expecting was to be completely blown away by how easy it is to pick up and start deploying your apps using Streamlit!</p><p>Normally, I’d expect to spend days just getting a basic application to show up, but in this case, I went from 0 lines of front-end code to a fully-functioning (albeit basic) application in 2 hours.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DW1YEWQrr1voNumGQcQvog.png" /><figcaption>My app (still WIP) is now live at <a href="https://hdb-predictions.streamlit.app/">https://hdb-predictions.streamlit.app/</a></figcaption></figure><p>So how does this all work?</p><h3>Getting Started</h3><p>Firstly, visit <a href="https://streamlit.io/">https://streamlit.io/</a>!</p><p>They have a fantastic and simple introduction, but I’ll also share the important commands here. Open up your command line interface and type this in:</p><pre>pip install streamlit<br>streamlit hello</pre><p>Streamlit will open a local page in your browser:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4FHi4lUbWX3-IY6IOCCqFw.png" /></figure><p>You can play around with the demos, and I suggest looking up sample repos to get started.</p><p>I personally used gabbygab123’s Crop Recommendation repo for reference: <a href="https://github.com/gabbygab1233/Crop-Recommender/tree/main">https://github.com/gabbygab1233/Crop-Recommender/tree/main</a></p><h3>Coding</h3><p>Now, for the code!</p><p>The Streamlit team was not joking when they said this framework was a breeze to work with.</p><p>Have a look at my app alongside my code (Python):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7l5RsFAso6vOPubXxeW_rg.png" /></figure><blockquote>In general, 1 widget only required 1 line of code.</blockquote><p>I just had to supply min/max values for the sliders and all the possible selections for the dropdown selectboxes.</p><p>You can (and probably should) save the selected value of each widget to a variable. Every time you change the selections, the corresponding variable is updated. So if you change your mind and want to choose Ang Mo Kio instead of Punggol, the “town” variable will update to Ang Mo Kio.</p><p>The st.button(‘Predict’) function also makes things really convenient. It only computes the prediction when you click on the button.</p><p>This saved a lot of work on my end, because I didn’t have to write any code specially to account for states of completion and refresh the variables or predictions. It’s all built into Streamlit!</p><p>I only had to ensure that my pickled model and other parameters loaded correctly.</p><p>Now, on to the exciting part: deployment!</p><h3>Basic Requirements</h3><ol><li>Github Repository</li><li>Main Python file (.py)</li><li>Requirements.txt</li><li>Any supporting files you need, e.g. config.py, pickled models (.pkl), JSON files, etc</li></ol><p>After that, just go to the Streamlit site, sign up or log in, and click New App.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*P4FZYyWNbaJdoMkAam4M_A.png" /></figure><p>After that, just fill in some info about your repository and claim an app URL (if you like).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VjV02ZhISC96DOKQ_BoPNg.png" /></figure><p>And that’s all! Just wait for your app to be ready.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*D43IizYjMncJc-5FLs49Zw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DW1YEWQrr1voNumGQcQvog.png" /><figcaption>My app (again) for reference</figcaption></figure><p>Of course, everything is a WIP and I’ll be updating this app with time… and Streamlit just makes developing and updating the app so easy.</p><p>If you’ve stayed here thus far, and like this post, stay tuned.</p><p>I’ll be publishing more regularly from August 2023, as I begin my Master’s in Analytics at Georgia Tech!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef0c1c4909b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing Readable Code: More Data Art than Data Science]]></title>
            <link>https://medium.com/@alfredtangsw/writing-readable-code-more-data-art-than-data-science-c163a2ba28f4?source=rss-b1b5b8ee7b48------2</link>
            <guid isPermaLink="false">https://medium.com/p/c163a2ba28f4</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[documentation]]></category>
            <category><![CDATA[best-practices]]></category>
            <dc:creator><![CDATA[Alfred Tang]]></dc:creator>
            <pubDate>Tue, 14 Apr 2020 10:59:25 GMT</pubDate>
            <atom:updated>2020-04-15T01:10:11.011Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*PcVhqfg9NT7TJ6IVUWoG9g.png" /><figcaption>Credit to Shutterstock for the stock photo</figcaption></figure><p>Ever looked at someone’s code and felt like you were reading Greek?</p><p>Yeah, me too.</p><p>Sometimes, that code was my own, 3 months after I’d left it alone.</p><h3><strong>Why Do Documentation?</strong></h3><p>Not documenting my own code was already painful enough when I had to come back and explain it to a friend a few months later. I felt as if I was a codebreaker, trying to get into my own head and figure out what I was doing. I even had to run some of my own code line by line to recall and explain the logic behind it.</p><p>As if that wasn’t enough, I worked on a defence contract for a few months and had to develop new features on top of code that was 99% not documented. The 1% that was documented was full of short and vague comments as well; they would have only made sense to the writer. (To be fair, the original developer did not have a long lead time for his deliverables.)</p><p>Realising that I would be overhauling the code anyway, I decided to rewrite the code and fully document and comment the code because I did not want anyone to go through the same pain I did.</p><p>You can save yourself the pain, too!</p><p>I won’t claim to know everything about documentation, but here are a few suggestions that you can start using right away. Let’s start with the principles.</p><h3><strong>Core Principles of Documentation</strong></h3><ol><li>Done is better than perfect.</li><li>Make comments concise, clear, and informative.</li><li>Context matters. This can be provided in code, in comments, in a README file, or all of them.</li><li>Help other people and you’ll help yourself too.</li></ol><h3><strong>Recommended Practices</strong></h3><h4><strong>1. Communicate your intent. Keep it concise but clear and informative.</strong></h4><p>Most important: What is the purpose of this code? What is the aim?</p><p>Next: Why?</p><p>How it is done, Where it goes, When it happens can become apparent in the code.</p><p>“Who” may be optional. Depends on whether specific persons need to be mentioned.</p><p>Docstrings to summarise the entire transform are highly recommended. You can do this by putting a docstring underneath your imports or function definition.</p><h4>2. Code in the way you write an email.</h4><p>When writing emails, you have to be concise yet clear about what you want to achieve. Applying the same principle when coding, while retaining an English-like format, will help you write readable code and concise comments.</p><p>You can also save a lot of effort on comments by giving variable names that provide additional context.</p><p>Consider the following block of code.</p><pre>import string</pre><pre>r1 = &quot;The coffee here is amazing!&quot;</pre><pre>r1_lst = &#39;&#39;.join(c for c in r1 if c not in string.punctuation).split(&#39; &#39;)</pre><pre>print(r1_lst)</pre><p>The output is a list of words: [‘The’, ‘coffee’, ‘here’, ‘is’, ‘amazing’]</p><p>That much can be interpreted, but to what end?</p><p>Why does this data scientist want the sentence parsed into a list of words?</p><p>Why does the sentence mention coffee being amazing and why is that of interest to the data scientist?</p><p>Let’s look at an alternative block of code:</p><pre>import string</pre><pre>cafeReview1 = &quot;The coffee here is amazing!&quot;</pre><pre>review1AsLstOfWords = &#39;&#39;.join(c for c in r1 if c not in string.punctuation).split(&#39; &#39;)</pre><pre>print(review1AsLstOfWords)</pre><p>Now we’re getting somewhere. From the code alone — with no comments — we can see that this data scientist is probably studying the language patterns of cafe reviews.</p><p>We did this just by changing the names of variables to something more English-like. That helps provide some context. We were able to keep it concise as well.</p><p>Can this be further improved? Yes!</p><pre>cafeReview1 = &quot;The coffee in this cafe is amazing!&quot;</pre><pre>cleanCafeReview1 = &#39;&#39;.join(char for char in cafeReview1 if char not in string.punctuation)</pre><pre>review1AsLstOfWords = cleanCafeReview1.split(&#39; &#39;)</pre><pre>print(review1AsLstOfWords)</pre><p>More text was added and we needed 1 more line, but that’s not a bad thing. If writing more lines makes your code more readable, it’s perfectly okay to do that!</p><p>Here are some suggested formats:</p><pre>+----------------------------------+-------------------------------+<br>|       <strong>Recommended Formats  </strong>      |            <strong>Examples</strong>           |<br>+----------------------------------+-------------------------------+<br>|Descriptor + Origin + Type of Data|    recentDatabase1PriceData   |<br>+----------------------------------+-------------------------------+<br>|Origin + Type of Data + Descriptor|    database1PriceDataRecent   |<br>+----------------------------------+-------------------------------+</pre><p>The first example fits into an English sentence, whereas the second reflects how a programmer might think while being sufficiently English-like.</p><p>The result of using either is that you get context just from reading the filename, column name, or variable name.</p><p>It takes you a few seconds more to write the rest of the words out, but it saves you a day or two trying to figure it out when you come back to it later.</p><h4>3. Code and Document in a way everyone can read, even business users.</h4><p>When we write code, we write it in a way we understand in that moment.</p><p>We may not even remember what we wrote or why when we come back to our code in 3 months’ time. It can be as good as reading code written by someone else.</p><p>Save yourself the pain. Write code and documentation that anyone can pick up and understand!</p><p>I hope that was helpful to you, because it has been helpful to me in my data science journey.</p><p>Make everyone’s lives easier and you’ll help yourself too!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c163a2ba28f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Languages: Your Key to the World]]></title>
            <link>https://medium.com/@alfredtangsw/languages-your-key-to-the-world-c03668229a0?source=rss-b1b5b8ee7b48------2</link>
            <guid isPermaLink="false">https://medium.com/p/c03668229a0</guid>
            <category><![CDATA[culture]]></category>
            <category><![CDATA[language]]></category>
            <category><![CDATA[polyglot]]></category>
            <category><![CDATA[history]]></category>
            <category><![CDATA[communication]]></category>
            <dc:creator><![CDATA[Alfred Tang]]></dc:creator>
            <pubDate>Thu, 08 Aug 2019 08:44:37 GMT</pubDate>
            <atom:updated>2019-10-11T08:36:23.979Z</atom:updated>
            <content:encoded><![CDATA[<p>Anyone can do it.</p><blockquote>“Solely in the world of <strong>languages</strong> is the amateur of value. Well-intentioned sentences full of mistakes can still build bridges between people.” — <a href="https://www.goodreads.com/author/quotes/1045149.Kat_Lomb">Kató Lomb</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CEoh8_KBsEo05FgtLecsnQ.png" /><figcaption>The Tower of Babel. Peter Bruegel the Elder, 1563. <a href="https://en.wikipedia.org/wiki/Tower_of_Babel#/media/File:Pieter_Bruegel_the_Elder_-_The_Tower_of_Babel_(Vienna)_-_Google_Art_Project.jpg">Source</a></figcaption></figure><h3><strong>The Key to the World</strong></h3><p>If English happens to be your first language, you can consider yourself fortunate.</p><p>It’s the world’s lingua franca, and also the third-most spoken natively. You don’t have to struggle (as many do) to pick it up to better communicate with colleagues and business partners.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*bs57E9XW6rdVt5VkBYP8ng.png" /><figcaption>Pulp Fiction, 1994. <a href="https://www.mememaker.net/meme/english-motherfucker-do-you-speak-it93">Source</a></figcaption></figure><h3><strong>Building Bridges with Broken Languages</strong></h3><blockquote>“We should learn languages because language is the only thing worth knowing even poorly.” — <a href="http://spanishlinguist.us/2013/07/a-lovely-thought-about-language-learning/">Kató Lomb</a></blockquote><p>When I first met a Japanese colleague who was on a business trip, he seemed a little reserved. We were all hospitable towards him and he wasn’t new, so culture shock seemed an unlikely cause.</p><p>There seemed to be some other obstacle. I observed that he spoke some English, but always tried to keep sentences short. He would also profusely apologise if he got an expression wrong, and he appreciated corrections.</p><p>I thought that perhaps he was just not yet confident about speaking English. Before I joined this company, I had learned Japanese out of interest, so I decided to speak to him in whatever broken Japanese I knew at the time.</p><p>He was delighted. “Oh! You speak Japanese! <em>Sugoi ne!</em>” he exclaimed. We had a good laugh at my broken Japanese, and I could see the relief in his eyes as he told me how it was enough that I could speak even a little bit of his language. We made fast friends and offered to correct each other in English and Japanese as needed.</p><p>I did the same with my other Japanese colleagues, developing good relationships with them simply by knowing a little bit of their language and letting them laugh at my broken Japanese.</p><p>Even broken, language can build bridges. It’s all about how you use it.</p><h3><strong>Language, Culture, History: All Are One, One Is All</strong></h3><p>Communicating with others in a common language is powerful by itself, but take it one step further and this power multiplies.</p><p>Think about the history and culture behind the language. Languages are formed by geopolitics, economics, popular expressions, and more.</p><p>English, as we know it today, has a 1,400-year history. It has made several great evolutions alongside historical events.</p><p>Ever wondered why English has French loan-words? One reason is that the <a href="https://www.quora.com/Why-does-the-English-language-have-so-many-French-words-in-it">Norman-French king, William the Conqueror, subjugated England</a> in the 11th Century. French nobles dominated the court, and French became the official language throughout the land. (There are other French influences too, of course.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/1*jBLpafV9xafu1c-gPjde9Q.png" /><figcaption>A certain king of Wessex. <a href="https://en.wikipedia.org/wiki/Alfred_the_Great#/media/File:Statue_d&#39;Alfred_le_Grand_%C3%A0_Winchester.jpg">Source</a></figcaption></figure><p>Perhaps you’ve noticed that places in some parts of the United Kingdom have names that seem to belong in Scandinavian countries. That’s because of the <a href="https://en.wikipedia.org/wiki/Invasions_of_the_British_Isles">Viking invasions</a> in the late 8th century.</p><p>Faced with the prospect of Britain being ravaged by Viking raiders, <a href="https://en.wikipedia.org/wiki/Alfred_the_Great">a certain king of Wessex</a> rallied the many kingdoms of Britain to fight them. Under his leadership, the Britons <a href="https://en.wikipedia.org/wiki/Battle_of_Edington">won a decisive battle</a> and sued for peace, allowing the Vikings to settle in certain areas agreed upon in a peace treaty.</p><h3><strong>History is all in the past. How does all this help?</strong></h3><p>History is not just about what happened long ago.</p><p>Everything we have today — including our languages — is linked to the history of our cultures. History is alive.</p><p>I once met a British colleague who shared the same name as myself. At our introduction, I shook hands with him and said, “Hello, Al. I’m an Al too, as in ‘Alfred’.”</p><p>With a radiant smile, he grasped my hand and asked jokingly, “As in King Alfred the Great?” With a chuckle, I nodded and shook his hand.</p><p>“Yes, but I don’t fight Vikings,” I replied. He laughed, and at that point, we were no longer strangers.</p><p>He instantly knew that I understood the history of his culture to some extent, and he appreciated it. We started talking about the Viking and Norman invasions of Britain.</p><p>At that moment, we were no longer colleagues or people belonging to a culture or nation. We were just two English speakers discussing the origins of our common language.</p><p>It took just six words to break the ice.</p><h3><strong>I Chose The Polyglot Life</strong></h3><p>Going through high school, I had some interest in other languages such as Russian (I taught myself to read Cyrillic), German, and Japanese.</p><p>However, at the time, I didn’t have enough life experience to know how powerful languages could be. I didn’t have the drive to master any language other than English, which I was already good at.</p><p>I was so focused on English that my mother jokingly questioned if I was even Chinese because my command of Mandarin was poor at the time.</p><p>I found some motivation later on when I began my career. Slightly more than a month before I started working as a copywriter, I learned during an interview that my future job would involve managing localisations. I realised that it would be easier to do this job if I knew multiple languages.</p><p>I sought ways to efficiently pick up languages and came across “<a href="http://www.tesl-ej.org/books/lomb-2nd-Ed.pdf">Polyglot: How I Learn Languages</a>”, a wonderful book by <a href="https://en.wikipedia.org/wiki/Kat%C3%B3_Lomb">Kató Lomb</a> (a Hungarian interpreter who spoke <strong>16 languages</strong>).</p><p>Reading it changed my perspective on language proficiency; I revisited my past learning and decided I would learn to speak multiple languages.</p><h3><strong>You Can Be A Polyglot Too</strong></h3><p>I don’t think I have any natural talent for languages. I just have the benefit of being educated in Singapore. We study English as a first language and our mother tongues as a second language. It’s easier to build on an existing bilingual foundation.</p><p>As with anything else, though, you’ll have to do your part and be an active learner.</p><p>When I do something I’m passionate about, I dedicate 199% of my attention and energy to it. (As a result, I have eyebags that never go away. I often get engrossed and forget about the time when I’m learning something.)</p><h3>How to Polyglot: Start Now; Full Immersion</h3><p>If you’re thinking of picking up a new language, I suggest maximising your exposure in every way possible. I have the following suggestions :</p><ol><li>Attend an interactive class and put in your fullest effort.</li><li>Find a class where conversing in your language of choice is <strong>not</strong> optional. This makes you practise creating sentences in your target language.</li><li>Stop yourself from using your native language or as a crutch.</li><li>Adopt the target language’s method of pronunciation. Study how a native speaker says the words and try to imitate them.</li><li>Listen to radio shows and watch reality TV in your target language. Songs are okay, but least preferred. It’s harder to pick up correct pronunciation through songs when learning languages with intonation (e.g. Mandarin).</li><li>If learning more than one language at once, learn the basics of one before picking up the other. Otherwise, you could mix up words and rules.</li></ol><blockquote>Disclaimer: This is not the gospel truth for learning languages. I’m only sharing what I experienced. Maybe someone more experienced can share better methods.</blockquote><p>In my case, I picked up basic Japanese quickly because I forced myself to stop using English or Romaji after the first 5 sessions. I did all my homework in hiragana, katakana, or kanji. I also practised by imitating the way Japanese people speak. English was reserved for translation notes.</p><p>I risked making more mistakes this way, but that was the point of going to class. It was a safe environment where mistakes cost nothing and instead maximised my learning.</p><p>You can learn almost anything with enough motivation. I started learning data science on my own and decided to dedicate the rest of my life to the field because the more I did it, the more I wanted to do it.</p><h3>My Polyglot Journey</h3><p>I’m enjoying every moment of this journey.</p><p>My quality of life has improved because I can enjoy foreign content in the original language (although I still use subtitles for convenience). I also have new skills that I can apply at work.</p><p>After further developing my proficiency in Japanese, I was able to translate from Japanese to English. I was also trusted to proofread and edit English text that was translated from Japanese (and these tasks came very frequently).</p><p>I also found that I enjoyed Japanese anime, games, and movies more than I did before. The words were no longer foreign sounds and mystical runes. It’s better when you can grasp context and nuance immediately.</p><p>I’ve also gotten back in touch with my Chinese roots by exploring the Three Kingdoms (relevant to my <a href="https://medium.com/@tangshuweialfred/steamvox-topic-modelling-sentiment-analysis-d83a88d3003a">SteamVox data science project</a>) and Warring States Periods, and I now enjoy Total War: Three Kingdoms with Mandarin voice-overs only for total immersion.</p><h3>Conclusion</h3><p>I hope that sharing parts of my journey has helped you find your own reasons for picking up and using languages.</p><p>To my fellow (aspiring) polyglots, I bid you all the best.</p><p>May you always find deep connections through the use of language.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c03668229a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SteamVox: Topic Modelling & Sentiment Analysis]]></title>
            <link>https://medium.com/@alfredtangsw/steamvox-topic-modelling-sentiment-analysis-d83a88d3003a?source=rss-b1b5b8ee7b48------2</link>
            <guid isPermaLink="false">https://medium.com/p/d83a88d3003a</guid>
            <category><![CDATA[videogames]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Alfred Tang]]></dc:creator>
            <pubDate>Mon, 05 Aug 2019 10:44:27 GMT</pubDate>
            <atom:updated>2019-08-25T14:24:51.672Z</atom:updated>
            <content:encoded><![CDATA[<h3>SteamVox: Data Science for Learning What Players Say and Feel</h3><p>For when you absolutely have to draw conclusions from 10,000 reviews in a single day.</p><blockquote>NOTE: This is a non-technical writeup. For the detailed technical writeup, <a href="https://medium.com/@tangshuweialfred/steamvox-topic-modelling-sentiment-analysis-technical-adc5b88f71a0">click here</a>.</blockquote><h3>SteamVox in a Nutshell</h3><p>I built SteamVox to obtain the “Voice of the Player” from players’ reviews on Steam (one of the largest online distributors for PC games.)</p><p>SteamVox scrapes, cleans, and analyses reviews from Steam to identify topics and corresponding sentiment for each topic for a chosen game on Steam.</p><p>Using the power of machine learning, it delivers convenient snapshots and narrows down areas of negativity to investigate (and areas of positivity to celebrate!).</p><p>A future iteration will be made applicable across most games on Steam.</p><p>This project is hosted on GitHub at:</p><ul><li><a href="https://github.com/alfredtangsw/steamvox">https://github.com/alfredtangsw/steamvox</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7O69wA8wew18-c62.jpg" /><figcaption>One of the world’s biggest PC Game distribution platforms. <a href="https://greenhdwallpaper.com/game-developer-wallpaper-hd/">Source</a></figcaption></figure><h3>Voice of the Player</h3><p>If you could get a summary of your customers’ opinions on your product’s features with just a click or two, you could quickly address any changes in sentiment by solving the correct problem associated with that feature.</p><p>I stress <strong>“correct problem”</strong>. Passionate developers often build their idealised version of their game and have to course-correct to deliver what players want.</p><p>Intended or not, the effect is the same in the end. Players who dislike your features will quit very quickly.</p><h3>The Problem</h3><p>Time for doing anything comes at a premium in the video game industry:</p><ol><li>Game developers are always pressed for <strong>time</strong>.</li><li>Game publication is <strong>time</strong>-sensitive.</li><li>Reviews are important, but reading reviews is <strong>time</strong>-consuming.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*XEN3VMsdxO3bBTjXhjPJ1g.png" /><figcaption>Game developers are pressed for time dealing with these problems.</figcaption></figure><p>Source: <a href="https://www.researchgate.net/publication/220686446_What_went_wrong_A_survey_of_problems_in_game_development">This paper</a> by Petrillo et al., 2009.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*LbcWGaMwwMKQqA4yC6o6qw.png" /><figcaption>Players won’t keep spending money while features are less-than-satisfactory!</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*UVlddwGGVNl-8HsiR2VQ-A.png" /><figcaption>Would you spend a whole month just manually processing reviews?</figcaption></figure><p><strong>Problem Statement</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*MAk3ieyMuUM-0NK3u9xtQQ.png" /><figcaption>We want to get actionable conclusions (backed by data) ASAP.</figcaption></figure><p><strong>SteamVox Built to Answer a Real-World Business Problem</strong></p><p>In my previous job, I encountered precisely the problem described above.</p><p>Due to time constraints, we had to make do with what we could get by talking to a small group of players and quickly skimming some forums.</p><p>The conclusions derived did not inspire confidence because the sample did not represent our playerbase well.</p><p>Looking back, I believe we could have done much better.</p><h3>SteamVox is a Solution</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*y9sAVKvLvJonPp77jOeXqA.png" /><figcaption>SteamVox delivers insights that shorten the time taken to improve features.</figcaption></figure><p>Inspired by <a href="https://blog.insightdatascience.com/topic-modeling-and-sentiment-analysis-to-pinpoint-the-perfect-doctor-6a8fdd4a3904">DoctorSnapshot</a> by <a href="https://medium.com/u/9d961f59f6a3">Nuo Wang</a>, I developed my own methodology for generating sentiment snapshots for Steam games.</p><p>I decided to test my concept on one game first, before scaling up. I selected Total War: Three Kingdoms, a strategy game from the Total War series.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OWiaUSCJnLNxBnMa2wl9Rg.png" /></figure><p><strong>SteamVox Anatomy</strong></p><ol><li>Scrape Steam Reviews</li><li>Cleaning &amp; Tokenisation</li><li>Topic Modelling</li><li>Sentiment Analysis</li><li>Scoring &amp; Aggregation</li></ol><p><strong>Output: Tableau Dashboard</strong></p><p><a href="https://public.tableau.com/profile/alfred.tang#!/vizhome/SteamVox001/Dashboard1">Tableau Public</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*j-sWfVneCnsuL0nZpUrPhA.png" /><figcaption>SteamVox deployed as a Tableau Dashboard</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*eOtOHyvvkqM8IY69QXAnjw.png" /><figcaption>Sort by score and click on any bar to see the review, dominant topic, and sentiment score.</figcaption></figure><h3>Steam Reviews as a Dataset</h3><p>Steam reviews can be downloaded directly from Steam through an API.</p><p>When using reviews, take note:</p><ol><li>Reviewers only make up a portion of your player base. The rest thrive/suffer/quit in silence.</li><li>Paid reviews tend to be longer and more usable. Free-to-play (F2P) games will require a modified approach.</li></ol><p><strong>Paid games get fewer spam reviews</strong></p><p>To illustrate, I tested out my review qualification criteria on CounterStrike: Global Offensive, now an F2P game.</p><p>I scraped 92,074 reviews (1 year’s worth) and found that for the whole year, only 6,000 reviews had at least 5 words in them.</p><p>In contrast, Total War: Three Kingdoms has 3,661 usable reviews out of 8,235 available. As of the time of this writing, it has been available on Steam for 2 to 3 months.</p><p><strong>The Internet is for Spam</strong></p><p>Steam reviews are similar to social media posts, so it’s easy for the VADER SentimentIntensityAnalyzer to read them.</p><p>However, there are issues that plague all informal text found on the Internet:</p><ol><li>Spam and memes.</li><li>Most reviews are incredibly short.</li><li>Gamers fully demonstrate their proficiency in the ancient and mystic art of sarcasm when they are upset. This throws VADER off.</li><li>Players may spam the same review repeatedly.</li><li>Some reviewers do not use punctuation.</li></ol><p>There is no easy fix, but we can minimise such issues with effective data cleaning.</p><p><strong>Total War: Three Kingdoms Reviews</strong></p><ul><li>8,235 English Steam reviews</li><li>8,150 unique reviews</li><li>3,661 determined usable for training</li></ul><p>3,661 reviews may not sound like much, but the total word count exceeds 100,000 words!</p><p>For reference, the <a href="https://wordcounter.net/blog/2016/02/21/101241_how-many-pages-are-there-in-the-bible.html">New Testament of the Bible has around 184,000 words</a>.</p><h3>Step 1: Scrape Steam Reviews</h3><p>An awesome Internet citizen (woctezuma on GitHub) developed <a href="https://github.com/woctezuma/download-steam-reviews">steamreviews</a>, a Python package that allows you to download reviews from Steam directly.</p><p>Starting this project during the Steam Summer Sale of 2019, I encountered numerous scraping problems.</p><p>After adding my own error handling clauses to identify and troubleshoot this problem, I determined the issue to be 502 Bad Gateway errors.</p><p>It seems that Valve throttles traffic on Steam during big sales to prevent epic site crashes of yesteryears.</p><p>I asked woctezuma to make 2 improvements:</p><ol><li>Improve error handling to complete the review scraping even if there are 502 Bad Gateway errors.</li><li>Add an option to show error reports.</li></ol><p>woctezuma has added those features and made steamreviews better for everyone. Kudos!</p><h3>Step 2: Clean and Tokenise</h3><p>Arguably the most important step for Latent Dirichlet Allocation (LDA). It will be revisited multiple times as you seek out a coherent model.</p><p>LDA is not a simple plug-and-play algorithm that accepts a list of reviews as scraped from Steam. We have to process the text into a format that it can read.</p><blockquote>Garbage in, garbage out.</blockquote><p>We want to:</p><ol><li>Get coherent reviews</li><li>Clean coherent reviews for LDA Model to process</li></ol><p>Here’s what that looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*APlI-8cP75pnxf4CbxNa5w.png" /><figcaption>Essentially, we want to turn reviews into lists of keywords.</figcaption></figure><p><strong>General process of cleaning and tokenisation:</strong></p><ol><li>Filter reviews by criteria to maximise the number of usable reviews</li><li>Transform reviews into lists of important terms</li><li>Identify phrases (n-grams)</li><li>Lemmatise each token and retain only nouns</li></ol><p><strong>2–1. Filtering the Data</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gz_LB87o-eqe-F1agnPsJQ.png" /><figcaption>4 conditions for qualifying a review as usable</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*FcpQZzQGayH4AKEOAewhIA.png" /><figcaption>Before filtering, the shortest review is just 1 word long!</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*cxLGw3kk9eF8Hu8RkxVXUA.png" /><figcaption>After filtering, reviews are much meatier and more likely to be usable.</figcaption></figure><p><strong>2–2. Tokenisation</strong></p><p>Before the LDA Model can read any text, you have to clean the text in each review and transform it into a list of keywords, as shown earlier.</p><p><strong>Cleaning Steps</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MmWa5FAIF1Dtxead5giJMA.png" /><figcaption>Cleaning these 6 things up makes the text more machine-readable</figcaption></figure><p><strong>2–3. Identify phrases</strong></p><p>It’s important to identify phrases because they will make your topic model more coherent.</p><p>Many words consistently appear together, such as ‘total’ and ‘war’ in this dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*heHS0K-fR8N7cXZY9H3lkQ.png" /><figcaption>‘total’ and ‘war’ appear together a lot in this Word Cloud. ‘three’ and ‘kingdom’ as well.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*QEjJca9goYNpYU0cd_zbZA.png" /><figcaption>Makes more sense to put them together as ‘total_war’ and ‘three_kingdom’!</figcaption></figure><p>After making phrases, you can be more certain that single-token terms most likely occurred by themselves. This can make it easier to differentiate topics.</p><p>To tokenise phrases, we turn them into single tokens using gensim’s Phraser:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*7hFLul7RlEaI-0vl8bwkCA.png" /><figcaption>Visual representation of n-grams</figcaption></figure><p><strong>2–4. Lemmatise tokens and retain nouns only</strong></p><p>Words come in many forms and often come from the same <a href="https://en.wiktionary.org/wiki/lemma">lemma</a>.</p><p>For example:</p><blockquote>inflected: “playing”, “played”, “plays”</blockquote><blockquote>lemma: “play”</blockquote><p>By reducing them to their lemma, “play”, we get 3 of the same word. This reduces noise without losing information.</p><p>I prepared 3 variations to try out in Topic Modelling:</p><ol><li>All types of words</li><li>Nouns, verbs, and 3grams only</li><li>Nouns and 3grams only</li></ol><h3>3. Topic Modelling</h3><p>For Topic Modelling, I used Latent Dirichlet Allocation.</p><p><strong>What is Latent Dirichlet Allocation?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*YjCt4K6pZCVNUQUggJ2h5Q.png" /></figure><p>In NLP, LDA is a machine learning algorithm that explains observations in the dataset using latent (hidden) variables derived from the observations themselves.</p><p><strong>LDA in Plain English</strong></p><p>Let’s say you are given news articles without headlines or category labels, but with body text intact. Given no additional information, you are asked to label the categories.</p><p>One solution is to read the documents and find out what they’re about, then label them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7tolzBHRZnsSVA84sDqh2Q.png" /><figcaption>LDA identifies topics using the words in each document</figcaption></figure><p>As you read each document, you identify topics within the document. Essentially, LDA performs the above task.</p><p>Next, using LDAvis, we can generate a visualisation for our topic model.</p><p><strong>1st Run: All Types of Words</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*xAbKm4_ZTRR0XG1V1YUCbA.png" /><figcaption>This model allows all types of words</figcaption></figure><p>There is little overlap between topics at first glance, but inspect the relevant terms on the right and the topics will seem less coherent.</p><p>To further clean the data, I removed both rare and overly common terms, and other terms that seemed to only create noise.</p><p><strong>12th Run: Nouns and n-grams only</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*YK_WnttNH6ZxFXCy63CG0g.png" /></figure><p>After intensive cleaning and retaining only nouns, I got this largely coherent topic model.</p><p>I identified 5 topics that made sense to me as a human:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*JQMgVUwB0qhL46hbkWeR6g.png" /><figcaption><a href="https://www.glinkster.com/best-total-war-games/">Image source</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*r0XM6TBmxi6O9EYxMD1tPg.png" /><figcaption><a href="https://forums.totalwar.com/discussion/234237/meet-the-warlords-warlord-poster-master-list">Image source</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*lqZK8fkLx0nv7jpdqjLzsg.png" /><figcaption><a href="https://www.strategygamer.com/articles/total-war-three-kingdoms-gameplay/">Image source</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*2UkLaxDolhcOVlaYb2DCrA.png" /><figcaption><a href="https://store.steampowered.com/app/779340/Total_War_THREE_KINGDOMS/">Image source</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*w37wbTYRWmAbccaWc0-qNA.png" /><figcaption><a href="https://www.howtogeek.com/163452/everything-you-need-to-know-about-the-blue-screen-of-death/">Image source</a></figcaption></figure><p>I decided not to get too granular with the topics because the model is just meant to <strong>quickly identify general areas to investigate and improve.</strong></p><p><strong>Bonus Round: Nouns, Verbs, 3grams</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cvCDsl9xjIInLA5JRZjGmg.png" /><figcaption>Visually similar, less coherent</figcaption></figure><p>Despite running the model with both verbs and nouns at least 5 times, the results did not appear more coherent than the nouns-only model.</p><p>However, it would be <strong>hasty to exclude the Nouns-and-Verbs dataset</strong> from future analysis.</p><p>Verbs could still be useful when identifying more general features using a large Steam dataset that contains reviews for thousands of games.</p><blockquote>Replayability: <em>&#39;replay&#39;</em></blockquote><blockquote>Content: <em>&#39;read&#39;,&#39;feel&#39;,&#39;connect&#39;</em></blockquote><p><strong>Nouns &amp; n-grams Most Effective</strong></p><p>Topics are nouns themselves, and we look for the nouns most associated with them because they carry the most information.</p><p>n-grams also act like nouns in this case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*xNYvDTasBxhXj8QiJgbFPg.png" /><figcaption>Which type of word is more informative about the topic?</figcaption></figure><p><strong>Model Validation: Overview</strong></p><p>Models like LDA do not have built-in validation reports, because there are no labels in the original dataset to check against.</p><p>To validate my model, I randomly sampled 10% of the dataset and manually checked the labels using 2 different sets of conditions.</p><p><strong>Validation Findings</strong></p><p>The model was able to assign topics correctly 85% of the time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*iY1G4eck1F3Ne0BNJ85ZQQ.png" /><figcaption>The lower the token count, the worse the classification.</figcaption></figure><p>Rows with 0 tokens were classified inaccurately most of the time.</p><p>This is expected. If I asked you to guess what I was thinking and I didn’t give you a single word, you wouldn’t have enough information to do so.</p><p>I checked the performance of the all-token-counts sample dataset as well:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*-_IWWtrpRnJ437e0KUurLA.png" /><figcaption>Note the red lines for 25th, 50th, and 75th percentiles for token counts</figcaption></figure><p>Reviews with 0 to 2 tokens tended to be misclassified more than those with ≥ 3 tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*xEZ21cEVwkWKbLJoID6UMw.png" /><figcaption>It simply wasn’t worth trading a whole 25% of the usable data for a marginal improvement.</figcaption></figure><p>At this point, I dropped all reviews with 1 or 0 tokens.</p><p>I was unwilling to drop everything up to 2 tokens. For a small decrease in misclassification rates, we would have to drop 25% of the dataset. That seemed like a bad tradeoff to me.</p><p>In summary:</p><ul><li>The model learned 5 topics, and all were coherent topics corresponding to game features of Total War: Three Kingdoms.</li><li>The model was able to assign the dominant topics of reviews accurately 85% of the time; higher with 0- and 1-token reviews removed.</li><li>Makes no sense to classify reviews with 0 or 1 tokens, so they will be excluded entirely in the final aggregation.</li></ul><h3>Step 4: Sentiment Analysis</h3><p>Now that we know what players are talking about, we want to know how they feel about each topic.</p><p>Let’s pause here to address a critical question.</p><p><strong>Why not use the provided sentiment label?</strong></p><p>Steam reviews force the user to give a positive/negative opinion. There is also only positive and negative; no middle ground.</p><p>This simplifies data analysis, but in reality, <strong>most people have some level of mixed opinion.</strong></p><p>Even if they are “mostly” positive, for reasons discussed in the next section, I didn’t want to stop at getting an “overall positive” for the whole review.</p><p>Here’s a preview of VADER at work:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*gzmUi5v2hb3HJBAUSlZx2g.png" /><figcaption>Yes, my instance of the VADER SentimentIntensityAnalyzer is named “Anakin”.</figcaption></figure><p>VADER takes the text that you feed it (including punctuation and emotes) and analyses the sentiment behind the words. Out of the 4 scores it outputs, we just need the compound score to get the overall sentiment rating.</p><p><strong>Caveats:</strong></p><ul><li>We have to assume that (at least for paid games) most players have a vested interest in making the developers improve the game.</li><li>VADER performs better when it is fed more text.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*rGMVaby_NqARApqx1lkgog.png" /><figcaption>VADER compound score can get good sentiment scores on long documents! (This is the same review)</figcaption></figure><h3>5. Scoring &amp; Aggregation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HlK2m1rj8HDdvTXOEAW2Lg.png" /><figcaption>Sample output: tokenised and scored by sentences. Note that the classification is not highly accurate.</figcaption></figure><p>After we identify topics and score each document, we need to aggregate scores across the whole dataset in order to generate snapshots.</p><p><strong>Preprocessing for Aggregation</strong></p><p>The compound score returned by VADER is a decimal. For this model, however, the decimals provide dimensions that we don’t need.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*e3s5BS5hlm4imANBDywlPA.png" /><figcaption>Histogram of sentiment scores for sentences in a test review</figcaption></figure><p>For generating a snapshot of how many reviews/sentences in a dataset are positive, the exact value of the score is not needed.</p><p>We just need to know whether it’s positive, neutral, or negative (represented by 1, 0, and -1 respectively).</p><p>I decided to change the sentiment scores to integers:</p><ul><li>Score &gt; 0.1 → 1 (Pos)</li><li>-0.1 ≤ Score ≤ 0.1 → 0 (Neutral)</li><li>Score &lt; -0.1 → -1 (Neg)</li></ul><p><strong>Aggregation Logic</strong></p><p>Here, we score and aggregate by paragraphs, because it is close to how humans read reviews, identify topics, and feel the sentiment of the reviewer.</p><p>Readers identify topics and sentiments by the paragraph as they read the document.</p><p>In the end, readers may generally recall, “This person seems to really like the strategic gameplay. They also liked tactical gameplay and authenticity”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Uvqmw3tZ_FA4oq75ZKcioQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*gam5XKkOo-Q4YKHDjsAaEA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*IGziT68CYM5FVkQsbcLk1Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*uQhgeLULkvukfJQYt7IJkw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ajpdKwo2PEV8alkv9NYqzA.png" /><figcaption>Score each review, then aggregate for the whole dataset</figcaption></figure><p>This method used <a href="https://github.com/fnl/syntok">Syntok</a>, a specialised text tokenisation tool. Using Syntok, I parsed the data into paragraphs and pseudo-paragraphs, all of which were more coherent than the short sentences I had up to that point.</p><p>This was the final result, visualised in Python:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZtyTdicPS0gX5euzIdQE3g.png" /><figcaption>Final Output, a Python Dataframe.plot()</figcaption></figure><p>I was more confident about using these results than those from previous attempts because:</p><ul><li>Aggregation logic follows how a human reads and scores reviews</li><li>Longer sentences have good classification rates</li></ul><p><strong>How to Use the Data</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*j-sWfVneCnsuL0nZpUrPhA.png" /><figcaption>SteamVox on Tableau</figcaption></figure><p>How to use the data (Tableau example):</p><ol><li>Narrow down which features to pay most attention to (most negative)</li><li>Sort Original Text by Compound Score, then click mouse over any bar to read the review/paragraph.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*eOtOHyvvkqM8IY69QXAnjw.png" /></figure><p><strong>Insights and How to Use Them</strong></p><p>In the end, it’s up to a human to make sense of the data.</p><p>I inspected reviews for the most negative category (Strategic Gameplay) first and sorted the most negative ones to the top.</p><p>For Total War: Three Kingdoms, Strategic Gameplay has the highest proportion of negative reviews.</p><p>That doesn’t necessarily mean it’s badly built. Numbers aren’t everything; context matters as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*FCivo4yFp0Oo-rx1LXPaKw.png" /><figcaption>Sample negative review (Strategic Gameplay)</figcaption></figure><p>This reviewer is unhappy with how the Diplomacy system works in Total War: Three Kingdoms, but that doesn’t mean it is objectively bad.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*4MHPxvp9L95-Kxea1XJLXA.png" /><figcaption>Sample positive review (Strategic Gameplay).</figcaption></figure><p>Put in context, the Three Kingdoms era was full of impermanent diplomatic deals and alliances.</p><p>The developers built Total War: Three Kingdoms to maximise immersion, and they included the era’s political upheavals in their game design.</p><p>It may be that the player doesn’t agree with the design due to their personal preferences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*4ad5Gx7JCF7sXWXBHsUBVg.png" /><figcaption>Positive review by a Chinese player (Content &amp; Authenticity)</figcaption></figure><p>If Creative Assembly’s aim was to target the Chinese PC gaming market, they may have succeeded. Most reviews are about the authenticity of the game and how they succeeded in making an authentic and fun Three Kingdoms game.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*4nNhmra3vbeSQRenkX2FMA.png" /><figcaption>Another negative review for Strategic Gameplay</figcaption></figure><p>The above review presents legitimate concerns about Strategic Gameplay. The chief complaint is that there are bugs in the diplomacy system and on the campaign map.</p><p>With this information on hand, developers can quickly pinpoint what exactly to investigate and fix.</p><h3>Conclusion</h3><p>Doing this project challenged me to pick up and apply machine learning to a real-world problem using real-world data, the gathering and cleaning of which came with numerous real-world challenges.</p><p>It was also immensely satisfying to apply different skills from my diverse skill set in combination with each other.</p><p>Thank you for reading, and stay tuned for more!</p><p>My work has not ended; there is much more room for improvement.</p><p><strong>Future Work (in progress):</strong></p><ul><li>Add timestamps and enable aggregation by time period</li><li>Add a review age field (reviews become less relevant as new updates are released)</li><li>Make the model more generally applicable to most/all Steam games</li></ul><h3>References</h3><p>Liu, S. (2019) Dirichlet distribution. <a href="https://towardsdatascience.com/dirichlet-distribution-a82ab942a879">https://towardsdatascience.com/dirichlet-distribution-a82ab942a879</a></p><p>Amazon Web Services (2019) How LDA Works. <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/lda-how-it-works.html">https://docs.aws.amazon.com/sagemaker/latest/dg/lda-how-it-works.html</a></p><p>Clark, S. (2013) Topic Modelling and Latent Dirichlet Allocation. Machine Learning for Language Processing: Lecture 7. <a href="https://www.cl.cam.ac.uk/teaching/1213/L101/clark_lectures/lect7.pdf">https://www.cl.cam.ac.uk/teaching/1213/L101/clark_lectures/lect7.pdf</a></p><p>Pandey, P. (2018) Simplifying Sentiment Analysis using VADER in Python (on Social Media Text). <a href="https://medium.com/analytics-vidhya/simplifying-social-media-sentiment-analysis-using-vader-in-python-f9e6ec6fc52f">https://medium.com/analytics-vidhya/simplifying-social-media-sentiment-analysis-using-vader-in-python-f9e6ec6fc52f</a></p><p>cjhutto. vaderSentiment Documentation. <a href="https://github.com/cjhutto/vaderSentiment">https://github.com/cjhutto/vaderSentiment</a></p><p>SIL International. SIL Glossary of Linguistic Terms: Valency. <a href="https://glossary.sil.org/term/valency">https://glossary.sil.org/term/valency</a></p><h3>About the Author</h3><p>Alfred Tang is a writer-turned-data scientist with 3.5 years’ experience as a copywriter and sales optimisation analyst in the video game industry.</p><p>He comes from a diverse educational background, having studied data science, finance, hotel administration, and mechanical engineering.</p><p>In this project, he put on different hats, drawing on his experience as a writer, analyst, polyglot, and gamer to create this model and its aggregation logic.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d83a88d3003a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SteamVox: Topic Modelling & Sentiment Analysis (Technical)]]></title>
            <link>https://medium.com/@alfredtangsw/steamvox-topic-modelling-sentiment-analysis-technical-adc5b88f71a0?source=rss-b1b5b8ee7b48------2</link>
            <guid isPermaLink="false">https://medium.com/p/adc5b88f71a0</guid>
            <category><![CDATA[videogames]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Alfred Tang]]></dc:creator>
            <pubDate>Sat, 03 Aug 2019 13:42:42 GMT</pubDate>
            <atom:updated>2019-08-05T10:52:35.683Z</atom:updated>
            <content:encoded><![CDATA[<h3>SteamVox: Technical Writeup</h3><p>All the nitty-gritty you need to get started using LDA.</p><blockquote>NOTE: This is a detailed technical writeup meant to describe the logic behind every decision made. The shorter version is <a href="https://medium.com/@tangshuweialfred/steamvox-topic-modelling-sentiment-analysis-d83a88d3003a">here</a>.</blockquote><h3>About the Author</h3><p>Alfred Tang is a writer-turned-data scientist with 3.5 years’ experience as a copywriter and sales optimisation analyst in the video game industry.</p><p>He comes from a diverse educational background, having studied data science, finance, hotel administration, and mechanical engineering.</p><p>In this project, he puts on different hats, drawing on his experience as a writer, polyglot, analyst, and gamer to create this model and its aggregation logic.</p><h3>Introduction</h3><p>SteamVox is a model for identifying topics and analysing sentiment for player reviews on Steam.</p><p>Steam is an app store for PC game distribution, one of, or perhaps the biggest in the world.</p><p>“Vox” is Latin for “voice” and refers to “Vox populi, vox dei”: “The voice of the people is the voice of God.”</p><p>This project is hosted on GitHub at:</p><ul><li><a href="https://github.com/alfredtangsw/steamvox">https://github.com/alfredtangsw/steamvox</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Gz_W1c7wxlfZG0Kl.jpg" /><figcaption>One of the world’s biggest PC Game distribution platforms. <a href="https://greenhdwallpaper.com/game-developer-wallpaper-hd/">Source</a></figcaption></figure><p>The business problems behind this project are discussed in the non-technical article.</p><h3>SteamVox Overview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*y9sAVKvLvJonPp77jOeXqA.png" /><figcaption>SteamVox delivers insights that shorten the time taken to improve features.</figcaption></figure><p><strong>SteamVox Anatomy</strong></p><ol><li>Scrape Steam Reviews</li><li>Cleaning &amp; Tokenisation</li><li>Topic Modelling</li><li>Sentiment Analysis</li><li>Scoring &amp; Aggregation</li></ol><p><strong>Toolbox</strong></p><ol><li>Scraping — steamreviews, a package by <a href="https://github.com/woctezuma/download-steam-reviews">woctezuma</a></li><li>Cleaning &amp; Tokenisation — NLTK, SpaCy, gensim, <a href="https://pypi.org/project/syntok/">Syntok</a></li><li>Topic Modelling — Latent Dirichlet Allocation, ldaMulticore</li><li>Sentiment Analysis — VADER SentimentIntensityAnalyser</li><li>Scoring &amp; Aggregation — Python, Tableau</li></ol><p><strong>Output: Tableau Dashboard</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*j-sWfVneCnsuL0nZpUrPhA.png" /><figcaption>SteamVox deployed as a Tableau Dashboard</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*eOtOHyvvkqM8IY69QXAnjw.png" /><figcaption>Sort by score and click on any bar to see the review, dominant topic, and sentiment score.</figcaption></figure><p><strong>Current State</strong></p><p>SteamVox v0.1 supports only Total War: Three Kingdoms, as it is a proof of concept.</p><p>Future versions will be expanded to be more generally applicable across Steam.</p><h3>Steam Reviews as a Dataset</h3><p>Steam reviews for each game are stored as JSON files. This is a convenient format for Python, because it can be read in as a Python dictionary.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01497981c543683d855f5fc74043ef43/href">https://medium.com/media/01497981c543683d855f5fc74043ef43/href</a></iframe><p><strong>The Internet is for Spam</strong></p><p>Steam reviews are similar to social media posts. This is good for the VADER SentimentIntensityAnalyzer, which is designed to analyse such text.</p><p>However, there are issues that plague virtually all informal text found on the Internet:</p><ol><li>Spam and meme reviews are common and often hold no meaning.</li><li>Most reviews are incredibly short (fewer than 5 words).</li><li>Gamers fully demonstrate their proficiency in the ancient and mystic art of sarcasm when they are upset (this throws VADER off).</li><li>Players may spam the same review over and over, sometimes in coordination with other reviewers, to “review bomb” a game.</li><li>Some reviewers do not use punctuation. This can affect tokenisation.</li></ol><p>No easy fix exists for these problems, but we can minimise the issues faced by using effective cleaning and tokenisation techniques.</p><p><strong>Paid games get fewer spam reviews</strong></p><p>It seems that paying players have more incentive to give serious feedback.</p><p>I tested out my review qualification criteria on CounterStrike: Global Offensive, a free-to-play (F2P) game.</p><p>I scraped 92,074 reviews (1 year’s worth) and found that only 6,000 reviews had at least 5 words in them.</p><p>Total War: Three Kingdoms, on the other hand, had 3661 such reviews from just 2 months on Steam.</p><p><strong>Total War Reviews</strong></p><ul><li>8,235 English Steam reviews</li><li>8,150 unique reviews</li><li>3,661 determined usable for training</li></ul><p>3,661 reviews may not sound like much, but the total word count exceeds 100,000 words!</p><p>For reference, the <a href="https://wordcounter.net/blog/2016/02/21/101241_how-many-pages-are-there-in-the-bible.html">New Testament of the Bible has around 184,000 words</a>.</p><h3>Step 1: Scrape Steam Reviews</h3><p>An awesome Internet citizen by the username of woctezuma developed <a href="https://github.com/woctezuma/download-steam-reviews">steamreviews</a>, a package available on PyPI. It allows you to query reviews from the Steam API directly with just a few lines of code.</p><p>To use it, just type the following in your Anaconda Prompt:</p><pre>pip install steamreviews</pre><p>To use it, import it like you would any other Python package:</p><pre>import steamreviews</pre><p>Then follow the instructions here on the <a href="https://github.com/woctezuma/download-steam-reviews">main page</a>.</p><blockquote>NOTE 1: If you want to get verbose progress reports, you need to pass the parameter verbose=True (by default, verbose=False).</blockquote><blockquote>Sometimes the Steam API cannot be queried, and you may want to be informed of errors.</blockquote><pre>download_reviews_for_app_id(app_id, query_count=query_count,chosen_request_params=request_params,<br>verbose=True)</pre><blockquote>NOTE 2: During high-traffic periods e.g. Steam sales, you may have to run the query multiple times (or wait for the sale to end) to get your dataset.</blockquote><p>Valve throttles traffic on Steam during sales, so every time you access a page, there is a chance of getting a 502 Bad Gateway Error.</p><p>I started this project during the Steam Summer Sale of 2019 and had trouble running this package. I would get incomplete review datasets that did not go back the 365 days I specified. However, <em>i</em>t worked fine outside of the sale period.</p><p>After adding my own error handling clauses to identify and troubleshoot this problem, I asked woctezuma to make 2 improvements:</p><ol><li>Improve error handling so that the API querying process does not end upon encountering a single 502 Bad Gateway error.</li><li>Add option for verbose error reports so you can choose to be informed of such errors.</li></ol><p>woctezuma has added those features and made steamreviews better for everyone. Kudos!</p><h3>Step 2: Clean and Tokenise</h3><p>This is arguably the most important step in this project. It will be revisited multiple times as you tweak the model for coherence.</p><p>There is a heavy focus on cleaning and tokenisation in this article because LDA is not a simple plug-and-play algorithm that accepts a list of reviews as scraped from Steam.</p><blockquote>Garbage in, garbage out.</blockquote><p>We want to:</p><ol><li>Get coherent reviews</li><li>Clean coherent reviews for LDA Model to process</li></ol><p>Here’s what that looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*APlI-8cP75pnxf4CbxNa5w.png" /><figcaption>Essentially, we want to turn reviews into lists of keywords.</figcaption></figure><p><strong>General process of cleaning and tokenisation:</strong></p><ol><li>Filter reviews by criteria to maximise number of usable reviews</li><li>Tokenise reviews into lists of important terms</li><li>Identify phrases (n-grams)</li><li>Lemmatise each token and retain only nouns</li></ol><p><strong>2–1. Filtering</strong></p><p>Raw data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*FcpQZzQGayH4AKEOAewhIA.png" /><figcaption>The shortest review is just 1 word long!</figcaption></figure><p><strong>2–1 (i). Playtime filtering</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*HNwK9C-frHyghp_6aO6xfQ.png" /><figcaption>The shortest review is <strong>still</strong> 1 word long.</figcaption></figure><p>Playtime conditions:</p><ul><li>Player must have played at least 3 hours</li><li>Player must have played at least 10 minutes in the 2 weeks leading up to publication of review</li></ul><p>Steam allows refunds for up to 2 hours of game time, and opinions are more valid if the player has clocked playtime recently.</p><p>Even after dropping more than 3000 reviews, there was one problem: the shortest review was still 1 word long. That’s not usable.</p><p><strong>2–1 (ii). Review length (in words) filtering</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*TKdVXFeGtC1N-cLNAXZfEQ.png" /><figcaption>Now, we can be more certain that our dataset is full of usable reviews.</figcaption></figure><p>I decided to drop any reviews whose word counts were equal to or shorter than…</p><blockquote>“Best Total War game ever.”</blockquote><p>This sentence happens to be 5 words long, and 25% of the data was 1 to 5 words long. It can at least tell you that the player likes this game and that it has earned its place in the Total War series.</p><p>However, I wanted meatier, more informative reviews, so I decided to drop these reviews and anything shorter.</p><p>Dropping reviews containing 5 or fewer words, I essentially traded 25% of the data to ensure that the rest of the data was usable. It was worth it.</p><p><strong>2–1 (iii). Remove duplicates</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BE_0v6vhZcnosZ4J1AxHDA.png" /><figcaption>No duplicate data remains.</figcaption></figure><p>Sometimes, by chance, 4 different people will type exactly the same thing, and that’s fine. We just don’t want to include reviews if they are spammed by the same person. Duplicates are more noise than data.</p><p><strong>2–1 (iv). Language filtering</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*yWRLlKXGjxacbDTssaHLtQ.png" /><figcaption>SpaCy langdetect at work (detection by sentence) on the first of 3 randomly selected reviews</figcaption></figure><p>I designed SteamVox to analyse English reviews, so naturally, I needed a dataset of English reviews. During the scraping step, I set steamreviews to scrape only reviews marked as being in English, but I wanted to be absolutely sure.</p><p>I manually inspected 3 randomly selected reviews and found that 1 of them did in fact contain 3 languages: English, Turkish, and German. If 1 review can have 3 languages, surely there are more such reviews. (There were others with Chinese and other languages.)</p><p>Using SpaCy langdetect, we can detect languages by sentences in a document, or for the whole document in general. However, nothing is perfect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*VqP1sscdYAChp7eUqpfA1g.png" /><figcaption>False positives detected!</figcaption></figure><p>SpaCy langdetect tends to detect more false positives when detecting languages by sentence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*VXXi7i1V8SoXfaLJOwtxlg.png" /><figcaption>Same review, better result.</figcaption></figure><p>On the same document, SpaCy langdetect returned English only when detecting the language of the whole document.</p><p>Think of it as a tool that gets the mean probability score for each langauge detected in the document. It returns only the language with the highest mean probability score, greatly reducing the chances of getting false positives.</p><p>I decided to filter languages at the document level, so it would only filter out those that were not mainly in English. Any remaining documents would likely only have small amounts of non-English text, which could be filtered out based on their (in)frequency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*08QcqFN6dq2mF84kFKRd0A.png" /><figcaption>We only dropped 1.77% of reviews not labelled as “English”!</figcaption></figure><p><strong>2-2. Tokenisation</strong></p><p>Before the LDA Model can read any text, you have to clean the text in each review and transform it into a list of keywords.</p><p><strong>Cleaning Steps</strong></p><p>i. <a href="https://pypi.org/project/bbcode/">Remove BBCode</a> (a markup language used by Steam)</p><p>ii. <a href="https://gist.github.com/nealrs/96342d8231b75cf4bb82">Expand contractions</a></p><p>iii. Remove punctuation and split reviews into lists of words</p><p>iv. Convert single digits and Roman numerals to words</p><p>v. Clean out incoherent/unhelpful/spam words</p><p><strong>2–2 (i). Remove BBCode</strong></p><p>There’s a convenient BBCode parser package (linked above) for Python. I thought of using Regex to remove all the markup, but the BBCode package already does it. No need to reinvent the wheel.</p><p><strong>2–2 (ii). Expand contractions</strong></p><p>Shorthand use is very common in informal text. It’s better to expand them so that they can more easily be removed when cleaning out stopwords (words that do not have much meaning by themselves, e.g. “of” and “the”).</p><p><strong>2–2 (iii). Remove punctuation</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*Cq0y0WMVc_RGmgEoVV-_0A.png" /><figcaption>Testing out the regular expression on Regex101</figcaption></figure><p>You can split a string on non-word characters so it will return [&#39;I&#39;,&#39;like&#39;,&#39;Total&#39;,&#39;War&#39;,&#39;3&#39;,&#39;Kingdoms&#39;]. That makes the tokens easier to transform.</p><p>2–2 (iv). Convert single digits and Roman numerals to words</p><p>We want to capture phrases such as &#39;shogun_two&#39; and &#39;three_kingdoms&#39; , and we can only do so if we convert single digits and Roman numerals into their word forms.</p><blockquote>‘2’ → ‘two’</blockquote><p>However, the Roman numeral “I” is skipped because it conflicts with the English pronoun “I”. It’s not a problem anyway, because first games in a series are often mentioned without the number.</p><p>2–2 (v). Clean out incoherent/spam/unhelpful words</p><p>Because of the informal nature of Steam reviews, people do not write in a format that many Natural Language Processing (NLP) toolkits are trained to handle. We need to convert tokens into terms that such toolkits are equipped to process.</p><p>For example, there are Internet memes such as “REEEEEEEEEEEEEEEE” where are no hard rules on the capitalisation or number of letters.</p><p>To control the occurrence of such words, we retain only words that are longer than 1 and shorter than or equal to 45 characters long:</p><blockquote>1 → ‘a’</blockquote><blockquote>45 → ‘pneumonoultramicroscopicsilicovolcanoconiosis’</blockquote><p><strong>2–3. Identify phrases</strong></p><p>It’s important to identify phrases because they will make your topic modelling more coherent.</p><p>Many words consistently appear together, such as ‘total’ and ‘war’ in this dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*heHS0K-fR8N7cXZY9H3lkQ.png" /><figcaption>‘total’ and ‘war’ appear together a lot in this Word Cloud. ‘three’ and ‘kingdom’ as well.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*QEjJca9goYNpYU0cd_zbZA.png" /><figcaption>Makes more sense to put them together as ‘total_war’!</figcaption></figure><p>After making phrases, you can be more certain that single-token terms most likely occurred by themselves. Players can talk about ‘war’ as a part of the game rather than ‘war’ in reference to the ‘total_war’ series.</p><p>To tokenise phrases, we turn words into single tokens using gensim’s Phraser:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*7hFLul7RlEaI-0vl8bwkCA.png" /><figcaption>For those who prefer to see this visually</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97e4989430a0c1fcc785c9aeae67accf/href">https://medium.com/media/97e4989430a0c1fcc785c9aeae67accf/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*is7sfxN-9wxayESPbVl9sA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*qvdPaWII4xweEpAlNOq9oQ.png" /><figcaption>Visualising how make_trigrams works</figcaption></figure><p><strong>2–4. Lemmatise tokens and retain nouns only</strong></p><p>Words come in many forms and often come from the same lemma.</p><blockquote><a href="https://en.wiktionary.org/wiki/lemma">Lemma</a>: The <a href="https://en.wiktionary.org/wiki/canonical">canonical</a> form of an <a href="https://en.wiktionary.org/wiki/inflected">inflected</a> word; <em>i.e.</em>, the form usually found as the <a href="https://en.wiktionary.org/wiki/headword">headword</a> in a <a href="https://en.wiktionary.org/wiki/dictionary">dictionary</a>, such as the <a href="https://en.wiktionary.org/wiki/nominative">nominative</a> singular of a noun, the <a href="https://en.wiktionary.org/wiki/bare_infinitive">bare infinitive</a> of a verb, etc.</blockquote><p>A simple example would be:</p><blockquote>inflected: “playing”, “played”, “plays”</blockquote><blockquote>lemma: “play”</blockquote><p>Returning tokens to their dictionary form makes it easier to identify topics.</p><p>Take for example the following sentences:</p><ul><li>I love playing Total War!</li><li>I have played every Total War there is.</li><li>I play Total War every Friday night.</li></ul><p>They are all talking about the same topic in different ways, using different forms of the word “play”.</p><p>You only need to know that all three reviews mention ‘play’ and ‘total_war’, to get an idea of what the three sentences are about. They all refer to the ‘total_war’ series and the ‘play’ activity.</p><p>Left uncleaned, “playing”, “played”, and “plays” will all be treated as different tokens in the model. By reducing them to their lemma, “play”, we get 3 of the same token, reducing the noise in the LDA model without losing information.</p><p>SpaCy has a built-in lemmatiser that we can use for this purpose. Even more conveniently, we can use Part-Of-Speech (POS) tags to select what kinds of words we want to include.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6283bd3a18f8ea24738d080752dc57f/href">https://medium.com/media/f6283bd3a18f8ea24738d080752dc57f/href</a></iframe><p>I prepared 3 variations to try out in Topic Modelling:</p><ol><li>All types of words allowed</li><li>Nouns, verbs, and 3grams only</li><li>Nouns and 3grams only</li></ol><h3>3. Topic Modelling</h3><p>For Topic Modelling, I used Latent Dirichlet Allocation.</p><p><strong>What is Latent Dirichlet Allocation?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*YjCt4K6pZCVNUQUggJ2h5Q.png" /></figure><blockquote>Fun fact: Dirichlet comes from the name Peter Gustav Lejeune Dirichlet, the German mathematician for whom the Dirichlet Distribution is named.</blockquote><p>In NLP, LDA is a topic model used for unsupervised machine learning about a dataset.</p><p>In this case, we use the reviews to determine the topics that exist within them, rather than having topic labels that another model (such as a Logistic Regression) could use to predict the topic of the review.</p><p>To go deeper into the mechanics of LDA, check out <a href="https://towardsdatascience.com/dirichlet-distribution-a82ab942a879">this link</a>.</p><p><strong>LDA in Plain English</strong></p><p>There’s an easier way to understand LDA.</p><p>Let’s say you’re asked to provide category labels for a set of news articles which do not have headlines or category labels but have completed body text. You are given no additional information, such as the distribution of article categories.</p><p>One way of solving this problem is to read the documents and find out what they’re about, then label them.</p><p>As you read each document, you identify topics within the document.</p><p>Essentially, LDA performs the above task.</p><p><strong>How does LDA work?</strong></p><p>First, let’s talk about what LDA assumes.</p><p><a href="https://www.cl.cam.ac.uk/teaching/1213/L101/clark_lectures/lect7.pdf">LDA assumptions</a>:</p><ul><li>Each document is a bag of words. Frequency of occurrence is key; the order of word placement is not important.</li><li>Each document contains multiple topics.</li><li>Each topic is a distribution over a set of keywords.</li><li>Each document is assumed to be generated by LDA’s probabilistic model.</li><li>Only the number of topics is specified in advance.</li></ul><p>Based on these assumptions, we have cleaned and tokenised our data into a format that LDA can easily read and analyse.</p><p>Each review has been tokenised into a list of keywords that LDA can then be trained on.</p><p><strong>Training the LDA Model</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*NLGYnC9t2oRFgM745ZBXeg.png" /></figure><blockquote>NOTE: You may wish to use <strong>ldaMulticore</strong> if your computer has more than 1 or 2 cores. This significantly shortens the time required to run the model.</blockquote><p>First, we have to specify a number of topics that the LDA model must identify.</p><p>The LDA Model then learns topic distributions across the documents and fits what it finds into the number of topics you specify.</p><blockquote>Caveat: LDA rarely returns a full set of coherent topics the first time it is run, partly because it is random unless you set a random_state.</blockquote><p>In case you’re wondering, I set 10 topics the first time, got a beautiful distribution of topics, and didn’t save my model before running it again. That distribution of topics is now lost to us forever. <strong>Always save your model!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*xLVyKbVo7xMaHA65fj-iLQ.png" /></figure><p>Second, the LDA Model assigns temporary topics for all documents. Don’t worry about this, there’s no human input required for it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*WJHe9qlct7ARatCNQx0bdg.png" /></figure><p>Third, the LDA Model will evaluate topics in each document according to the keywords associated with each topic. The model iterates over the number of passes that you instruct it to use.</p><p>Next, using LDAvis, we can generate a visualisation for our topic model.</p><p><strong>1st Run: All Types of Words</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*xAbKm4_ZTRR0XG1V1YUCbA.png" /><figcaption>LDA visualisation for 1st run</figcaption></figure><p>Topic separation looks good at first glance, but human assessment of the smaller topics will tell you that they are not so coherent.</p><p>At this point, I revisited cleaning and tokenisation. I also applied filter_extremes() to remove overly common terms and added additional stopwords for removal. Such words seemed to only create more noise, most notably ‘total_war’, which appeared in numerous topics.</p><p><strong>12th Run: Nouns and n-grams only</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*YK_WnttNH6ZxFXCy63CG0g.png" /></figure><p>After intensive cleaning and retaining only nouns, I got this largely coherent model.</p><p>I identified 5 topics that made sense to me as a human:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*JQMgVUwB0qhL46hbkWeR6g.png" /><figcaption><a href="https://www.glinkster.com/best-total-war-games/">Image source</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*r0XM6TBmxi6O9EYxMD1tPg.png" /><figcaption><a href="https://forums.totalwar.com/discussion/234237/meet-the-warlords-warlord-poster-master-list">Image source</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*lqZK8fkLx0nv7jpdqjLzsg.png" /><figcaption><a href="https://www.strategygamer.com/articles/total-war-three-kingdoms-gameplay/">Image source</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*2UkLaxDolhcOVlaYb2DCrA.png" /><figcaption><a href="https://store.steampowered.com/app/779340/Total_War_THREE_KINGDOMS/">Image source</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*w37wbTYRWmAbccaWc0-qNA.png" /><figcaption><a href="https://www.howtogeek.com/163452/everything-you-need-to-know-about-the-blue-screen-of-death/">Image source</a></figcaption></figure><p>I decided not to go too granular with the topics because such granularity is not important for the purpose of this model, which is to<strong> quickly identify general areas to investigate and improve.</strong></p><p>Specific details can be gathered by reading relevant reviews (or playing that part of the game yourself).</p><p><strong>Bonus Round: Nouns, Verbs, 3grams</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cvCDsl9xjIInLA5JRZjGmg.png" /><figcaption>Visually similar, less coherent</figcaption></figure><p>I tried the dataset with nouns and verbs last because I thought to test it out only after I got the working model on my 12th run.</p><p>Despite running this model at least 5 times, the results did not appear more coherent than the nouns-only model.</p><p><strong>Nouns &amp; n-grams Most Effective</strong></p><p>When we identify topics, we are trying to identify nouns. For those nouns, there are also nouns are most associated with them. Nouns carry the most information in this case, as compared to adjectives and pronouns.</p><p>For example, “bicycle” (noun) relates to the sports topic known as “cycling” (noun). “Exciting” and “fun” can also be related to cycling, but they are less informative about the topic than “bicycle”, “helmet”, and “race”.</p><p>n-grams also act like nouns in this case. After forming n-grams, we are less concerned about the meaning of the phrase and more concerned about how frequently the phrase occurs.</p><p>However, it would be <strong>hasty to exclude the Nouns-and-Verbs dataset</strong> from future analysis off-hand. I can see certain verbs such as “replay”, “read”, and “feel” being important for general game features such as Replayability and Content.</p><p>This could still be useful when identifying more general features using a large Steam dataset that contains reviews for thousands of games.</p><p><strong>Model Validation: Overview</strong></p><p>It is always a good practice to check your model’s performance after you build it.</p><p>Whereas supervised learning models can be used on a test set of data and then scored using pre-built functions to get R-squared values or classification reports, unsupervised learning models do not have such validation reports. There is no ground truth in the original dataset to check against.</p><p>I still thought validation was necessary, so to validate my model, I checked the labels manually to see if the classification was reasonably accurate.</p><p>I randomly sampled 10% of my dataset twice, using different conditions for each sample dataset:</p><ul><li>Token count ≤ 5</li><li>All token counts</li></ul><p>I chose 10% as a sample size because <a href="http://www.raosoft.com/samplesize.html">I wanted to be 95% confident of my conclusions</a>. Trying to be 99% confident would have meant much more labelling work for a marginal increase in accuracy, which is a bad tradeoff.</p><p>I wanted to see whether low token counts would have horrible classification accuracy.</p><p><strong>Hazards and Pitfalls</strong></p><p>Beware that checking in this manner can be somewhat arbitrary.</p><p>That’s because it is up to you (the creator of this model) to decide whether each row is classified correctly. <strong>Check your bias!</strong></p><p>Another problem is that you are basically checking against your training data. Typically, training set accuracy will be higher than test set accuracy. Checking against an unseen dataset may be helpful for validating your model, but beware another problem.</p><p>Manual labelling is <strong>extremely time-consuming</strong>. Be sure that you are satisfied with your LDA Model’s topics before you start labelling any sampled dataset. I burned a good 10 hours or so on this particular activity and restarted many times.</p><p><strong>Validation Findings</strong></p><p>The model achieved 85% accuracy overall.</p><p>This was based on the sample that included all token counts. This result seemed quite good for an unsupervised learning model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*iY1G4eck1F3Ne0BNJ85ZQQ.png" /><figcaption>The lower the token count, the worse the classification.</figcaption></figure><p>I treated my classification results as harshly as I could, because when I was lenient with the results, the rows with 0 tokens had high classification accuracy.</p><p>This made no sense to me because by simple reasoning, you can’t possibly know what topic a sentence is about if there are 0 keywords. (Of course, this 0-keywords situation happened only after we cleaned our text intensively.)</p><p>Additionally, I found that most of the time, the model defaulted to Content &amp; Authenticity, the most dominant topic of the entire dataset.</p><p>Through manual inspection of the sampled data, I found that most short reviews with 0 tokens said something like “This is the best Total War game!” which naturally would have only ‘total_war’ as a token (which we removed during cleaning for a good reason).</p><blockquote>Worth noting: Since LDA is a probabilistic model, when given 0 tokens, it often gives you the most commonly occuring topic because it’s more likely to be the correct than any other topic. This behaviour may change when using an upsampled dataset with equal class balances.</blockquote><p>I checked the performance of the all-token-counts sample dataset as well:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*-_IWWtrpRnJ437e0KUurLA.png" /><figcaption>Note the red lines for 25th, 50th, and 75th percentiles for token counts</figcaption></figure><p>Cumulative misclassification rate dropped significantly when reviews had 0 to 3 tokens, and the misclassification rate stabilised at around 15% when token counts were higher. (Leading to the ~85% overall accuracy).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*xEZ21cEVwkWKbLJoID6UMw.png" /><figcaption>It simply wasn’t worth trading a whole 25% of the usable data for a marginal improvement.</figcaption></figure><p>At this point, I decided to drop all reviews with 1 or 0 tokens. I was unwilling to drop everything up to 2 tokens, because that meant dropping 25% of the dataset, a whopping 916 out of 3661 reviews.</p><p>In summary:</p><ul><li>The model learned 5 topics, and all were coherent topics corresponding to game features of Total War: Three Kingdoms.</li><li>The model can assign the dominant topics of reviews accurately 85% of the time.</li><li>Makes no sense to classify reviews with 0 or 1 tokens, so they will be excluded entirely in the final aggregation.</li></ul><h3><strong>Step 4: Sentiment Analysis</strong></h3><p>Now that we know what players are talking about, we want to know how they feel about each topic.</p><p>Let’s pause here to address a critical question.</p><p>Steam data comes with sentiment labels provided by the user, and the user will not be allowed to post a review unless they provide a score. There is also only positive and negative; it does not allow a middle ground.</p><p>That would normally be a good thing, and Steam’s review system is designed that way to simplify data analysis, but I did not think it was reflective of reality.</p><p><strong>Most people have some level of mixed opinion. </strong>It’s highly unlikely that anyone will love every single feature in a given game.</p><p>Even if they are “mostly” positive, for reasons discussed in the next section, I didn’t want to stop at getting an “overall positive” for the whole review.</p><p>Now, let’s discuss VADER and some issues it may present when you use it.</p><p><strong>Known issues using VADER:</strong></p><ul><li>Tends to give neutral scores.</li><li>Sarcastic reviews are likely to be given the wrong sentiment score.</li><li>VADER may read vulgarities used for emphasis as negative when they are in fact positive.</li><li>Short documents tend to be given the wrong sentiment score.</li></ul><p>Here’s a preview of VADER at work:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*gzmUi5v2hb3HJBAUSlZx2g.png" /><figcaption>Yes, my instance of the VADER SentimentIntensityAnalyzer is named “Anakin”.</figcaption></figure><p>VADER takes the text that you feed it (including punctuation and emotes) and analyses the sentiment behind the words. Trained to analyse social media posts, VADER performs well on Steam reviews because of how similar they are.</p><p>Its output is 4 separate scores: negative, neutral, positive, and compound. For specifics on each, and how they are calculated, <a href="https://medium.com/analytics-vidhya/simplifying-social-media-sentiment-analysis-using-vader-in-python-f9e6ec6fc52f">check out this article</a>.</p><p>We are only interested in the compound score because we just need the overall sentiment for each document on hand. <a href="https://github.com/cjhutto/vaderSentiment">Learn more about the compound score here.</a></p><p>The compound score is a weighted composite score for the valence scores of each word in the text, so you can think of it as the overall score for the entire document’s sentiments. <a href="https://glossary.sil.org/term/valency">More on valency here.</a></p><p><strong>Caveats:</strong></p><ul><li>We have to assume that (at least for paid games) most players want to give serious feedback that can help improve the game, because they have a vested interest (money spent).</li><li>We must feed as much text to VADER as possible, before we get sentiment scores.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*rGMVaby_NqARApqx1lkgog.png" /><figcaption>VADER compound score can get good sentiment scores on long documents! (This is the same review)</figcaption></figure><h3>5. Scoring &amp; Aggregation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HlK2m1rj8HDdvTXOEAW2Lg.png" /><figcaption>Sample output: tokenised and scored by sentences. Note that the classification rates look bad and</figcaption></figure><p>After we identify topics and score each document, we need to aggregate scores across the whole dataset in order to generate snapshots.</p><p><strong>Preprocessing for Aggregation</strong></p><p>The compound score returned by VADER is a float. For the purpose of aggregation, however, I found the float scores just made the problem more complex.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*e3s5BS5hlm4imANBDywlPA.png" /><figcaption>Histogram of sentiment scores for sentences in a test review</figcaption></figure><p>I decided to change the sentiment scores to integers and store them in a new column.</p><p>For generating a snapshot of how many reviews/sentences in a dataset are positive, the magnitude of the score is not needed. We just need to know whether it’s positive, neutral, or negative (represented by 1, 0, and -1 respectively).</p><p>Here’s how that looks:</p><ul><li>Score &gt; 0.1 → 1 (Pos)</li><li>-0.1 ≤ Score ≤ 0.1 → 0 (Neutral)</li><li>Score &lt; -0.1 → -1 (Neg)</li></ul><p><strong>Aggregation Logic</strong></p><p>Steps in general:</p><ol><li>For each review in the dataset…</li><li>Iterate through each topic in the topic dictionary…</li><li>Form smaller dataframe just for that topic.</li><li>Count the number of Pos/Neg/Neutral rows associated with that topic.</li><li>Divide Pos/Neg/Neutral<strong> row count</strong> by total number of rows for that topic to get proportion percentages.</li><li>Find the category with the highest proportion (the mode of this distribution); append the category to a topic score list inside a score_dict.</li><li>If there are 2 dominant sentiments, append Neutral sentiment. (More than 1 dominant sentiment → unclear sentiment → Neutral).</li><li>At the end, score_dict contains lists with 1 sentiment rating per review. Divide Pos/Neg/Neutral <strong>review count </strong>by <strong>total number of reviews </strong>to get proportion percentages.</li><li>Final result is your numerical snapshot. Use df.plot() in Python, Tableau, or any other visualisation/deployment tool you like.</li></ol><p>I liked this method because appending to a list inside a dictionary saved me the trouble of creating “NA” fields for reviews that had fewer than 5 topics and cleaning the “NAs” away later during final calculations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*pOIdFRS1BZX7UpRMQCaR3g.png" /><figcaption>Deriving Final Output from Aggregation Logic</figcaption></figure><p>Here’s the code for it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dab93691fa8f4c3ec179462241d305f8/href">https://medium.com/media/dab93691fa8f4c3ec179462241d305f8/href</a></iframe><p>The above aggregation logic works for any number of rows you derive from the dataset, as long as you correctly assign the review numbers before and during transformation.</p><p>Similar/identical logic is used in all 4 methods as the final step. The difference in results comes from how I parse and group the rows for final aggregation.</p><p><strong>Aggregation Methods</strong></p><ol><li>By dominant topic of each review</li><li>By sentences (regardless of review)</li><li>By sentences, aggregated by review</li><li>By “paragraphs”, aggregated by review <strong>(Chosen method)</strong></li></ol><p>I tried so many different ways of aggregation because I wanted to summarise the scores efficiently while minimising bias and maximising accuracy and coherence. Nobody should use biased and/or unreliable insights.</p><p><strong>5–1. By review</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*XutRFa0SoSOiIhA1xS47Ig.png" /><figcaption>A review may contain multiple topics, each with their own sentiment.</figcaption></figure><p>The most obvious place to start was to just get the dominant topic for each document and score the sentiment of that review to get the overall sentiment.</p><p>There were 2 problems:</p><ul><li>Data wastage: Using this method, the other 2 topics would be ignored. I thought it was wasteful to just leave them out.</li><li>Biased scoring: Scoring based on the whole review while only taking the dominant topic into account does not make sense to me at the review level. (I think it’s reasonable at the sentence/paragraph level.)</li></ul><p>The results look good at first glance, but they are biased:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*jZJvbtqT7NDyNp1tkZIriQ.png" /><figcaption>Method 1: Aggregate by dominant topic of each review</figcaption></figure><p><strong>5–2. By sentences (regardless of review)</strong></p><p>Next, I tried going by sentences instead, to solve the 1st method’s problems.</p><p>The reasoning was that if I went by sentences, I could simplify the aggregation since (in theory) it should not matter which review each sentence comes from.</p><p>I tokenised the reviews into sentences and validated my model one more time before I proceeded. All in all, there were 16,739 sentences as tokenised by SpaCy, parsed from 3661 reviews.</p><p>I found that going by sentences, the model produced a much lower classification accuracy of 67%.</p><p>After investigating, I found out that tokenisation by sentence caused all documents to have fewer tokens (obviously), and more documents with 0 and 1 token counts were created.</p><p>I found 2 problems:</p><ul><li>SpaCy’s tokenisation (with default settings) tends to break sentences incoherently at times.</li><li>Low classification accuracy.</li></ul><p>I simply couldn’t trust the model’s classification at the sentence level. The aggregation would be wrong as well because aggregation is based on the classification.</p><p>Allow me to illustrate:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*xayfF2061-Qyk3y8ekQ0xQ.png" /><figcaption>SpaCy’s sentence tokenisation generates a lot of sentences…</figcaption></figure><p>I don’t think that “1.” should be a sentence. To be fair, of course, SpaCy uses punctuation to help determine sentence boundaries. With some parameter changes, it’s possible to change how the sentences are tokenised. I decided to resolve this in a later attempt.</p><p>I then counted the number of pos/neg/neutral sentences and got them as a percentage of the total number of sentences, grouped by topic, throughout the whole dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vA5D07B3UOPqfYkYFzHsHg.png" /><figcaption>Method 2: Aggregate by sentences</figcaption></figure><p>Neutral counts increased dramatically, most likely because VADER had no idea how to score them and decided to assign a score close to or equal to 0.</p><p>I had serious doubts about this result because:</p><ul><li>Classification accuracy was low (~67% on the sample)</li><li>Shortened sentences tend to get wrong or neutral scores from VADER</li><li>The context of a sentence matters. Aggregating all sentences by the review they belonged to made more sense to me.</li></ul><p><strong>5–3. By sentences, grouped by review</strong></p><p>I repeated the above method with 1 difference: I grouped the sentences by the reviews they belonged to, to get the overall sentiment for each topic found in each review. Then, I aggregated for the dataset.</p><p>The main difference is the logic behind the parsing. I thought about how a human might read reviews and manually assign the sentiment score.</p><p>One way could be to:</p><ol><li>Label all sentences with topics</li><li>Aggregate using sentences instead of reviews as documents (still separate rows in the dataset)</li></ol><p>This summarises the scores for all sentences about a topic within each review.</p><p>The results are as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eeTc_LzCwuYpbjHjyRVf4w.png" /><figcaption>Method 3: By dominant topic of sentences, grouped by topic</figcaption></figure><p>However, at this point I had not yet resolved the SpaCy sentence tokenisation issue. I wanted to see if this would change the results significantly.</p><p>There were some minor changes, but the overall result still looks like the one derived from Method 2. Some of the same issues remained, too.</p><p>However, I believed in this result a little bit more because of the reasoning behind the parsing and grouping.</p><p>I felt like I was on the right track, building the aggregation logic to follow a typical human’s way of identifying topics and scoring sentiment while reading text.</p><p><strong>5–4. By “paragaphs”, grouped by review</strong></p><p>All this exploration seemed to lead me to a dead end. I was stuck as long as I couldn’t solve the SpaCy tokenisation issues.</p><p>At this point, I reviewed the logic one more time. How would a human read reviews? Did I really have to go by sentences?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*kL-UCUmVkUYvt_wD3S4mng.png" /></figure><p>After some consideration, I thought it would be more reasonable to assume that readers identify topics and sentiments by the paragraph as they read the document. Readers would then generally recall, “This person seems to really like the strategic gameplay”, and/or “This review was mostly about strategic gameplay.”</p><p>So, I decided to parse each review into paragraphs before getting dominant topics and scores. I looked around for a paragraphing tool and thought I found one in <a href="https://github.com/fnl/syntok">Syntok</a>.</p><p><strong>Comparing SpaCy and Syntok:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*bRzV5WAt2oA_r18LIDnigg.png" /><figcaption>SpaCy sentence tokenisation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*N3gjzmALSfvsUCdYrRmtMg.png" /><figcaption>Syntok sentence tokenisation</figcaption></figure><p>For the same review, SpaCy generated more sentences than Syntok (41 vs 27). I found the sentences tokenised by Syntok to be generally more coherent. (‘1. Diplomacy.’ is better than ‘1.’ by itself).</p><p>Some of them also contained more than one sentence, if we’re a little stricter about the definition of a “sentence”.</p><p><strong>Stumbling Block</strong></p><p>I was more satisfied with this tokenisation, but it still wasn’t generating what I would call “paragraphs”, which should contain maybe 3 lines or more. (Or at least 2 long lines.)</p><p>I found out that Syntok works best when paragraphs are demarcated by double newline characters (‘\n\n’). This was a bit of an issue. Steam reviews are typically short.</p><p>For this dataset, the median review length (before dropping any rows) was 18 words. The chances of a newline appearing are not high with 18 words; I would expect there to be at most 3 sentences in such a review.</p><p>I decided I would make do with the new sentence tokenisation anyway, since it was more coherent and some sentences were joined together into pseudo-paragraphs.</p><p><strong>Happy Accidents Do Happen</strong></p><p>I had to slightly modify my cleaning process to work with Syntok (into something I now call Syntokenize):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d4a7b38ceb439c43254ca806ba14087/href">https://medium.com/media/1d4a7b38ceb439c43254ca806ba14087/href</a></iframe><p>When I ran this function on a list of test reviews, I got paragraphs!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*tfW2o9E7dnlFwD5QYpAuPg.png" /><figcaption>The numbers in the 2nd list are index numbers for the review that the text belongs to.</figcaption></figure><p>Investigating this, I discovered an accidental interaction between expandContractions() and Syntok, such that when expandContractions is run on the review, Syntok tokenises it into very long sentences (made of sentences). It wasn’t quite the plug-and-play function I had hoped for, but it did what I needed it to.</p><p>Using Syntok, I parsed the data into paragraphs and pseudo-paragraphs, all of which were more coherent than the short sentences I had up to now. 642 rows (a 17.5% increase) were gained this way, so there were 4303 rows of data before dropping those with low token counts (after dropping low-token-count reviews, 3724 rows remained).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZtyTdicPS0gX5euzIdQE3g.png" /><figcaption>Method 4: By paragraphs in each review</figcaption></figure><p>I was a lot more confident of using these results than those from previous attempts.</p><p>The logic more closely followed how a human would read and score a review, and I was confident that Syntok would parse coherent paragraphs out of reviews.</p><p><strong>How to Use the Data</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*j-sWfVneCnsuL0nZpUrPhA.png" /><figcaption>SteamVox on Tableau</figcaption></figure><p>Deployed on Tableau, you can make a dashboard that allows you to see at a glance what the top/lowest-ranked features are in each category of Pos/Neg/Neutral. (I included the original compound sentiment score to enable more effective sorting.)</p><p>How to use the data:</p><ol><li>Narrow down which features to pay most attention to (most negative)</li><li>Sort Original Text by Compound Score, then click mouse over any bar to read the review/paragraph.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*eOtOHyvvkqM8IY69QXAnjw.png" /></figure><p><strong>Insights and How to Use Them</strong></p><p>In the end, it’s up to a human to make sense of the data.</p><p>I inspected reviews for the most negative category (Strategic Gameplay) first, and sorted the most negative ones to the top.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*FCivo4yFp0Oo-rx1LXPaKw.png" /><figcaption>Sample negative review (Strategic Gameplay)</figcaption></figure><p>In this case, Strategic Gameplay has the highest proportion of negative reviews, relative to all reviews on the topic. That doesn’t necessarily mean it’s badly built. Numbers aren’t everything; context matters as well.</p><p>This reviewer is unhappy with how the Diplomacy system works in Total War: Three Kingdoms, but that doesn’t mean it is objectively bad. It may be that they don’t agree with the design due to their personal preferences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*4MHPxvp9L95-Kxea1XJLXA.png" /><figcaption>Sample positive review (Strategic Gameplay).</figcaption></figure><p>Put in context, the Three Kingdoms era was full of impermanent diplomatic deals and alliances. Your ally from yesterday could be your enemy tomorrow. The developers built Total War: Three Kingdoms to maximise immersion, and they included the era’s political upheavals in their game design.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*4ad5Gx7JCF7sXWXBHsUBVg.png" /><figcaption>Positive review (Content &amp; Authenticity)</figcaption></figure><p>I would venture to say that if their aim was to target the Chinese PC gaming market, they have succeeded. Most reviews are about the authenticity of the game and how Creative Assembly succeeded in making an authentic Three Kingdoms game.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*4nNhmra3vbeSQRenkX2FMA.png" /><figcaption>Another negative review for Strategic Gameplay</figcaption></figure><p>The above review presents legitimate concerns about Strategic Gameplay. The chief complaint is that there are bugs in the diplomacy system and on the campaign map.</p><p>With this information on hand, developers can quickly pinpoint what they need to fix.</p><h3>Conclusion</h3><p>Doing this project challenged me to pick up and apply machine learning to a real-world problem using real-world data, the gathering and cleaning of which came with numerous real-world challenges.</p><p>SteamVox let me combine several abilities from my diverse skill set to solve a business problem I previously encountered.</p><p>I’m glad to see it come together, and I hope to take it many steps further and develop a tool that can be used by all game developers who use Steam.</p><p>If you’ve read up to this point, thank you for reading. Stay tuned for more! My work has not ended; there is much more room for improvement.</p><p><strong>Future Work (in progress):</strong></p><ul><li>Add timestamps and enable aggregation by time period</li><li>Add a review age field(reviews become less relevant as new updates are released)</li><li>Make the model more generally applicable to most/all Steam games</li></ul><h3><strong>References</strong></h3><p>Liu, S. (2019) Dirichlet distribution. <a href="https://towardsdatascience.com/dirichlet-distribution-a82ab942a879">https://towardsdatascience.com/dirichlet-distribution-a82ab942a879</a></p><p>Amazon Web Services (2019) How LDA Works. <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/lda-how-it-works.html">https://docs.aws.amazon.com/sagemaker/latest/dg/lda-how-it-works.html</a></p><p>Clark, S. (2013) Topic Modelling and Latent Dirichlet Allocation. Machine Learning for Language Processing: Lecture 7. <a href="https://www.cl.cam.ac.uk/teaching/1213/L101/clark_lectures/lect7.pdf">https://www.cl.cam.ac.uk/teaching/1213/L101/clark_lectures/lect7.pdf</a></p><p>Pandey, P. (2018) Simplifying Sentiment Analysis using VADER in Python (on Social Media Text). <a href="https://medium.com/analytics-vidhya/simplifying-social-media-sentiment-analysis-using-vader-in-python-f9e6ec6fc52f">https://medium.com/analytics-vidhya/simplifying-social-media-sentiment-analysis-using-vader-in-python-f9e6ec6fc52f</a></p><p>cjhutto. vaderSentiment Documentation. <a href="https://github.com/cjhutto/vaderSentiment">https://github.com/cjhutto/vaderSentiment</a></p><p>SIL International. SIL Glossary of Linguistic Terms: Valency. <a href="https://glossary.sil.org/term/valency">https://glossary.sil.org/term/valency</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adc5b88f71a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>