<?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 Susan Li on Medium]]></title>
        <description><![CDATA[Stories by Susan Li on Medium]]></description>
        <link>https://medium.com/@actsusanli?source=rss-731d8566944a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ffGGDMNA116sjMHXgQNodg.jpeg</url>
            <title>Stories by Susan Li on Medium</title>
            <link>https://medium.com/@actsusanli?source=rss-731d8566944a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 10:01:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@actsusanli/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 Comparison of G7 Countries House Price Movement]]></title>
            <link>https://actsusanli.medium.com/a-comparison-of-g7-countries-house-price-movement-e47fc0a44503?source=rss-731d8566944a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e47fc0a44503</guid>
            <category><![CDATA[economic-data]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[housing-prices]]></category>
            <category><![CDATA[g7]]></category>
            <category><![CDATA[fred]]></category>
            <dc:creator><![CDATA[Susan Li]]></dc:creator>
            <pubDate>Tue, 21 Jun 2022 03:56:54 GMT</pubDate>
            <atom:updated>2022-06-21T03:56:54.970Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CYR0QDLS0eAhste2GBErkg.jpeg" /><figcaption>Photo Credit: Pixabay</figcaption></figure><h4>Python, FRED, Economic Data, Housing Price</h4><p><a href="https://fred.stlouisfed.org/">Federal Reserve Economic Data</a> (FRED) is an online database maintained by the <a href="https://www.stlouisfed.org/">Federal Reserve Bank of St. Louis</a> that provides over 800,000 economic data series from more than 100 public and proprietary sources.</p><p>With <a href="https://fred.stlouisfed.org/docs/api/api_key.html">FRED API key</a>, you can use any programming language that can parse <a href="https://en.wikipedia.org/wiki/XML">XML</a> or <a href="https://en.wikipedia.org/wiki/JSON">JSON</a> to query FRED data free of charge.</p><p>In this post, we will write Python code to retrieve and compare G7 countries’ housing price movement data for the past over 50 years.</p><p>To get started.</p><ul><li><a href="https://fredaccount.stlouisfed.org/login/secure/">Create your FRED user account</a>.</li><li>Sign in to your account, and <a href="https://fredaccount.stlouisfed.org/apikeys">request FRED API keys</a>.</li></ul><h3>The Data</h3><p>We now have what we need. Let’s go fetch the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q7UFLXpzyZnONznCGW1NoQ.png" /></figure><p>The series id for “Real Residential Property Prices for Canada” is “<strong>QCAR628BIS</strong>”, the series start date is “1970–01–01” and end date is “2021–10–01”.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48b99ac51b2497c5ae8871f7a4019434/href">https://medium.com/media/48b99ac51b2497c5ae8871f7a4019434/href</a></iframe><pre>df_canada</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*zDqYC7kDWQv-XDc4ovbZEw.png" /><figcaption>Table 1</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59ac771c18865e0795bd8755458fec6c/href">https://medium.com/media/59ac771c18865e0795bd8755458fec6c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-XEMljNlsUbSIH0nxCyHzw.png" /><figcaption>Figure 1</figcaption></figure><p>Here we have Real Residential Property Prices data for Canada from 1970–01–01 to 2021–10–01.</p><p>With the information we have, now we are going to fetch all G7 countries housing data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef8677e04b1dc1fd51bc374af855a144/href">https://medium.com/media/ef8677e04b1dc1fd51bc374af855a144/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*LNp_X4WzUKUFmWwfXeoKZw.png" /><figcaption>Table 2</figcaption></figure><p>In this series, FRED has the housing data for 51 countries. We will need G7 countries.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3288018d7aa91ffeaa2f9e56ba74e0f5/href">https://medium.com/media/3288018d7aa91ffeaa2f9e56ba74e0f5/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*NHtkVYpiwdfObqT9XdFi5g.png" /><figcaption>Table 3</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d43150ecf3f00cfa682fff4a3cd7b41/href">https://medium.com/media/6d43150ecf3f00cfa682fff4a3cd7b41/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*srszYqqotsIPm6lc4N9BSA.png" /><figcaption>Table 4</figcaption></figure><p>The last step is to add a “country” column.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/08233292ae7642dbd137f2e3dc4c9431/href">https://medium.com/media/08233292ae7642dbd137f2e3dc4c9431/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*F9Y7tkJVENQ8BFnoyy5t6Q.png" /><figcaption>Table 5</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da8223fcac40766552fed3b3111231df/href">https://medium.com/media/da8223fcac40766552fed3b3111231df/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2tDuUAfAdtcfoIcQWXzCOQ.png" /><figcaption>Figure 2</figcaption></figure><p>G7 countries house prices’ long-term trend is mixed. Canada has significant appreciated over the long period of time, and the UK has been in a “weak” property market over the past 10 years. While Italy is trending down. The U.S housing market is still recovering from its “bubble”.</p><p><a href="https://github.com/susanli2016/Machine-Learning-with-Python/blob/master/G7%20Countries%20Real%20Residential%20Property%20Prices.ipynb">Jupyter notebook</a> can be found on <a href="https://github.com/susanli2016/Machine-Learning-with-Python/blob/master/G7%20Countries%20Real%20Residential%20Property%20Prices.ipynb">Github</a>. Enjoy the rest of the week!</p><p>Sources: National sources, BIS Residential Property Price database, <a href="https://www.bis.org/statistics/pp_detailed.htm">https://www.bis.org/statistics/pp_detailed.htm</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e47fc0a44503" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building A Recommender System With Implicit Feedback Datasets Using Alternating Least Squares]]></title>
            <link>https://actsusanli.medium.com/building-a-recommender-system-with-implicit-feedback-datasets-using-alternating-least-squares-64d4f5ba3c57?source=rss-731d8566944a------2</link>
            <guid isPermaLink="false">https://medium.com/p/64d4f5ba3c57</guid>
            <category><![CDATA[recommender-systems]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[implicit-feedback]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Susan Li]]></dc:creator>
            <pubDate>Sun, 16 Jan 2022 21:38:00 GMT</pubDate>
            <atom:updated>2022-01-16T21:54:24.784Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bJhFYwfPlukpc1wmsCKYyA.jpeg" /><figcaption>photo credit: pixabay</figcaption></figure><h4>RecSys, ALS, Collaborative Filtering</h4><p>In real-world scenarios most feedback is not explicit but implicit. Implicit feedback is tracked automatically, like monitoring clicks, view times, purchases, etc. Thus it is much easier to collect. Think of yourself, how often you give a rating after purchasing a product vs. how often you click or purchase a product. In fact implicit feedback is already available in almost every information system — e.g. web servers record any page access in log files.</p><p>In this post, we will focus on item recommendation. The task of item recommendation is to create a user-specific ranking for a set of items. Preferences of users about items are learned from the user’s past interaction with the system — e.g. his (or her) online purchasing history in this case. That is, building a recommender system that provides personalized recommendations to customers based on their purchasing history.</p><h3>The Data</h3><p>The data we are using today is <a href="https://archive.ics.uci.edu/ml/datasets/online+retail">online retail dataset from UCI machine learning repository</a>. And we will be using <a href="https://implicit.readthedocs.io/en/latest/quickstart.html">Implicit Library</a>, a Fast Python Collaborative Filtering for Implicit Datasets, for our matrix factorization.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ce25c8a9396a724cc54e1d98e42aa44/href">https://medium.com/media/5ce25c8a9396a724cc54e1d98e42aa44/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*iH0VdVkX7MbMgSxQ7fP6_g.png" /><figcaption>Figure 1</figcaption></figure><ul><li>There are a lot of “CustomerID” were missing from the data, so we will have to remove those rows.</li><li>Group “CustomerID” and “StockCode” then sum the “Quantity”. So that we get each customer and each item interactions.</li><li>If “Quantity” = 0, we change to one.</li><li>Eliminate negative “Quantity”.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e84803729ec1a6662ad6dbb662c8c501/href">https://medium.com/media/e84803729ec1a6662ad6dbb662c8c501/href</a></iframe><p>Here is our grouped data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*D-fgU-YAcKKIwnZJ76JAoA.png" /><figcaption>Table 1</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4196211c459830dac716fa2123f4d8f/href">https://medium.com/media/b4196211c459830dac716fa2123f4d8f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f8voYNbJFKW98meSsF5LdQ.png" /><figcaption>Figure 2</figcaption></figure><p>The vast majority of customers purchased less than 40 pieces of same item in one interaction, very few of them purchased more than 2,000 pieces of same item in one interaction.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e3f54e8c693fc9cbcac311965278cbd/href">https://medium.com/media/2e3f54e8c693fc9cbcac311965278cbd/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*okvpdYPdVdRgyhoP6B_eoQ.png" /><figcaption>Figure 3</figcaption></figure><h3>Implicit Feedback</h3><p>Instead of representing an explicit rating, the “Quantity” can represent a “confidence” in terms of how strong the interaction was. Items with a larger number of “Quantity” by a customer can carry more weight in our ratings matrix of “Quantity”.</p><ul><li>We will create numeric “customer_id and “item_id” columns.</li><li>Create two matrices, one for fitting the model (item-customer) and another one for recommendations (customer-item).</li><li>Initialize the Alternating Least Squares (ALS) recommendation model.</li><li>Fit the model using the sparse item-customer matrix.</li><li>We set the type of our matrix to double for the ALS function to run properly.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9abba684ecb440d6a5047424c6af76b4/href">https://medium.com/media/9abba684ecb440d6a5047424c6af76b4/href</a></iframe><h3>Example of Recommendation — Finding the Similar Items</h3><p>Let’s start with “WHITE METAL LANTERN”. We found that “item_id” for “WHITE METAL LANTERN” is 1319.</p><pre>grouped_df.loc[grouped_df[&#39;item_id&#39;] == 1319].head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*E4ol6OOFBOhDDeLcN7paZA.png" /><figcaption>Table 2</figcaption></figure><p>Finding the 10 most similar items to “WHITE METAL LANTERN”.</p><ul><li>Get the customer and item vectors from our trained model.</li><li>Calculate the vector norms.</li><li>Calculate the similarity score.</li><li>Get the top 10 items.</li><li>Create a list of item-score tuples of most similar items with this item.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e3965b120fe656360b6dbefd5dffc95/href">https://medium.com/media/0e3965b120fe656360b6dbefd5dffc95/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*OfpnkTBsed3uiw66btEh7w.png" /><figcaption>Figure 4</figcaption></figure><p>The first item is always itself. I will let you judge whether the rest 9 items are some what similar with the first one.</p><h3>Example of Recommendation — Recommend Items to Customers</h3><p>The following function will return the top 10 recommendations chosen based on the customer/item vectors for items never purchased for any given customer.</p><ul><li>Get the purchase score from the sparse customer item matrix.</li><li>Add 1 to everything, so that items with no purchase yet become equal to 1.</li><li>Make items already purchased zero.</li><li>Get dot product of customer vector and all item vectors.</li><li>Scale this recommendation vector between 0 and 1.</li><li>Items already purchased have their recommendation multiplied by zero.</li><li>Sort the indices of the item into order of best recommendations.</li><li>Start empty list to store descriptions and scores.</li><li>Append descriptions and scores to the list.</li><li>Get the trained customer and item vectors. We convert them to csr matrices.</li><li>Create recommendations for customer with id 2.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38052f7651dd7db74a4ad4b1bee8b452/href">https://medium.com/media/38052f7651dd7db74a4ad4b1bee8b452/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*hfp57z-0RRn8nXSyxH48Bw.png" /><figcaption>Figure 5</figcaption></figure><p>Now we have top 10 recommendations for customer_id 2. Do they make sense? Let’s get top 20 items this customer has purchased.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fbdd8fecf6c1e9d83ecf271de439c2c9/href">https://medium.com/media/fbdd8fecf6c1e9d83ecf271de439c2c9/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*PnKpFkJ9hjNlRk2esriJtg.png" /><figcaption>Figure 6</figcaption></figure><p>This customer’s top purchases were lip glosses, designed tissues and holiday cake cases, etc things like people purchase when hosting holiday parties. The items we recommended to him (her) includes fruit straws, gift boxes, cocktail parasols, etc. Those are also things people purchase when hosting a party. Remember “Customers who bought this item also bought…”?</p><p>The best evaluation metrics for a recommender system is how much the system adds value to the customers and/or business, whether the system increase sales and profits. We will want to do some kind online A/B testing to evaluate these metrics.</p><p>However, there are other common metrics for evaluating the performance of a recommender in isolation. By following this <a href="https://nbviewer.jupyter.org/github/jmsteinw/Notebooks/blob/master/RecEngine_NB.ipynb">tutorial</a>, we were able to calculate the <a href="https://en.wikipedia.org/wiki/Receiver_operating_characteristic">AUC</a> for each customer in our training set that had at least one item purchased. And <a href="https://en.wikipedia.org/wiki/Receiver_operating_characteristic">AUC</a> for the most popular items for the customers to compare.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/163/1*_C35LXRf6JValhw0hRvYIQ.png" /></figure><p><a href="https://github.com/susanli2016/Machine-Learning-with-Python/blob/master/bpr_OnlineRetail_Implicit.ipynb">Jupyter notebook</a> can be found on <a href="https://github.com/susanli2016/Machine-Learning-with-Python/blob/master/bpr_OnlineRetail_Implicit.ipynb">Github</a>. Enjoy the rest of the weekend!</p><p>Reference: <a href="https://towardsdatascience.com/building-a-collaborative-filtering-recommender-system-with-clickstream-data-dffc86c8c65">https://towardsdatascience.com/building-a-collaborative-filtering-recommender-system-with-clickstream-data-dffc86c8c65</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64d4f5ba3c57" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fake News Classification with LSTM or Logistic Regression]]></title>
            <link>https://actsusanli.medium.com/fake-news-classification-with-lstm-or-logistic-regression-82a3527aaf13?source=rss-731d8566944a------2</link>
            <guid isPermaLink="false">https://medium.com/p/82a3527aaf13</guid>
            <category><![CDATA[lstm]]></category>
            <category><![CDATA[dataspell]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[jetbrains]]></category>
            <dc:creator><![CDATA[Susan Li]]></dc:creator>
            <pubDate>Mon, 22 Nov 2021 09:32:18 GMT</pubDate>
            <atom:updated>2021-11-22T18:39:57.628Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gdz3dl-pjlP18OayU9tSqA.jpeg" /><figcaption>photo credit: Pixabay</figcaption></figure><h4>Tensorflow, Keras, DataSpell, Scikit-Learn, PyCharm</h4><p>Fake news has become a focal point of discussion in the media over the past several years. Therefore, there is a need for an automated way to classify fake and real news accurately.</p><p>This post attempts to eliminate the spread of rumors and fake news and helps people to identify the news as trustworthy or not by automatically classifying the news, using <a href="https://www.jetbrains.com/dataspell/">DataSpell</a>, — the latest Data Science IDE from <a href="https://www.jetbrains.com/">JetBrains</a>.</p><h3>The Data</h3><p>The dataset consists of 44,919 news articles, almost equally distributed to the true and fake categories.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*jBVKmQoQsvoXKpIxjRU2mw.png" /></figure><p>The true articles were collected from the <a href="https://www.reuters.com/">Reuters</a> website, and the fake ones from various sources flagged as fake sources by <a href="https://en.wikipedia.org/wiki/English_Wikipedia">Wikipedia</a> and from <a href="https://www.politifact.com/">Politifact</a>. The datasets comprises the full body of each article, the title, date and topic. As a courtesy of the <a href="https://www.uvic.ca/ecs/ece/isot/">University of Victoria ISOT Research Lab</a>, the data sets can be downloaded from <a href="https://www.uvic.ca/ecs/ece/isot/datasets/fake-news/index.php?utm_medium=redirect&amp;utm_source=/engineering/ece/isot/datasets/fake-news/index.php&amp;utm_campaign=redirect-usage">here</a>. We will compare the state-of-the-art approach such as <a href="https://en.wikipedia.org/wiki/Long_short-term_memory">long short-term memories</a> (LSTMs) vs. <a href="https://en.wikipedia.org/wiki/Logistic_regression">Logistic Regression</a>.</p><h3>DataSpell</h3><p>There are a number of ways to download DataSpell, if you plan to use DataSpell only not any other JetBrains’ tools in its toolbox, the simplest way is to download it from <a href="https://www.jetbrains.com/dataspell/">it’s website</a> directly.</p><p>After launching DataSpell, you will see a screen like this. If this is the first time you use DataSpell, you environment should be much more cleaner than mine. I have created a project called dsProject_LogReg_DL, under the project, I created a data folder, loaded Fake.csv and True.csv. I also created two Jupyter notebooks in the same directory FakeNew_DL.ipynb and FakeNew_LogReg.ipynb like so, by right clicking:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgfycat.com%2Fifr%2Fclumsytancuttlefish&amp;display_name=Gfycat&amp;url=https%3A%2F%2Fgfycat.com%2Fclumsytancuttlefish&amp;image=https%3A%2F%2Fthumbs.gfycat.com%2FClumsyTanCuttlefish-size_restricted.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=gfycat" width="1126" height="900" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1969c3699f0d5d52628c986691f2a08/href">https://medium.com/media/d1969c3699f0d5d52628c986691f2a08/href</a></iframe><p>As a data scientist, I am a heavy user of Jupyter notebook. DataSpell provides an interface similar to <a href="https://jupyterlab.readthedocs.io/en/stable/#">JupyterLab</a>, plus several more new functionalities such as interactivity with data frame, smart coding assistance and so on. You just need to try and test them out.</p><h3>Deep Learning</h3><p>This section presents an overview of preprocessing techniques, and description of the deep learning model used for classification.</p><p>To make meaningful comparison between Deep Learning model with Logistic Regression model, we add start time at the beginning of the notebook and end time at the end of the notebook, then calculated the time spent running the entire code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*IeTsSKWWz_XXIxGC5NVeDg.png" /></figure><h4>Pre-processing</h4><p>The following steps demonstrated part of the data pre-processing process.</p><ul><li>We load Fake.csv and True.csv.</li><li>Remove the useless columns, we only need title &amp; text.</li><li>Label fake news as 0, and real news as 1.</li><li>Concatenate two data frames into one.</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgfycat.com%2Fifr%2Fleftdifficultlark&amp;display_name=Gfycat&amp;url=https%3A%2F%2Fgfycat.com%2Fleftdifficultlark&amp;image=https%3A%2F%2Fthumbs.gfycat.com%2FLeftDifficultLark-size_restricted.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=gfycat" width="1280" height="882" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2a5c7e09d674bb88582dbb601f2b8b2/href">https://medium.com/media/c2a5c7e09d674bb88582dbb601f2b8b2/href</a></iframe><p>You may have noticed that you can view the entire data frame by clicking “Open in new tab”, and using the scroll bar when the data frame is large.</p><p>In the following steps, we</p><ul><li>Combine title &amp; text into one column.</li><li>Standard text cleaning process such as lower case, remove extra spaces and url links.</li><li>The way we split training and testing data must be the same for deep learning model and Logistic Regression.</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgfycat.com%2Fifr%2Fmindlessdeficientambushbug&amp;display_name=Gfycat&amp;url=https%3A%2F%2Fgfycat.com%2Fmindlessdeficientambushbug&amp;image=https%3A%2F%2Fthumbs.gfycat.com%2FMindlessDeficientAmbushbug-size_restricted.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=gfycat" width="1280" height="882" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4d2ab44a13d2fd3e53a20648c52a89e/href">https://medium.com/media/b4d2ab44a13d2fd3e53a20648c52a89e/href</a></iframe><ul><li>We put the parameters at the top like this to make it easier to change and edit.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*XSoJYLS40j1ppTyF9qurww.png" /></figure><h4>Tokenization</h4><ul><li>Tokenizer does all the heavy lifting for us. In our articles (aka title + text) that it was tokenizing, it will take 10,000 most common words. oov_tok is to put a special value in where an unseen word is encountered. This means I want “OOV” in bracket to be used to for words that are not in the word index. fit_on_text will go through all the text and create dictionary.</li><li>After tokenization, the next step is to turn those tokens into lists of sequence.</li><li>When we train neural networks for NLP, we need sequences to be in the same size, that’s why we use padding. Our max_length is 256, so we use pad_sequence to make all of our articles (aka title + text) the same length which is 256.</li><li>In addition, there are padding type and truncating type, we set both of them “post”., meaning for example, if one article at 200 in length, we padded to 256, and we padded at the end, add 56 zeros.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GlQP_IKoS0I5b4HwgwiBaQ.png" /></figure><h3>Building the Model</h3><p>Now we can implement LSTM. Here is my code that I build a tf.keras.Sequential model and start with an embedding layer.</p><ul><li>An embedding layer stores one vector per word. When called, it converts the sequences of word indices into sequences of vectors. After training, words with similar meanings often have the similar vectors.</li><li>Next is how to implement LSTM in code. The Bidirectional wrapper is used with a LSTM layer, this propagates the input forwards and backwards through the LSTM layer and then concatenates the outputs. This helps LSTM to learn long term dependencies. We then fit it to a dense neural network to do classification.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4bv53hu87kbdrdeROYNwdg.png" /></figure><ul><li>In our model summary, we have our embeddings, our Bidirectional contains LSTM, followed by two dense layers. The output from Bidirectional is 128, because it doubled what we put in LSTM. I also stacked LSTM layer to improve the results.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*xCtD6cUUvynLQaZFLQs8ow.png" /></figure><ul><li>We are using early stop, which stops when the validation loss no longer improves.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hrezZhnFFlGGV23F7hYiCw.png" /></figure><ul><li>Visualize training over time and the results were good.</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgfycat.com%2Fifr%2Fwindinglinedimpala&amp;display_name=Gfycat&amp;url=https%3A%2F%2Fgfycat.com%2Fwindinglinedimpala&amp;image=https%3A%2F%2Fthumbs.gfycat.com%2FWindingLinedImpala-size_restricted.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=gfycat" width="1280" height="882" frameborder="0" scrolling="no"><a href="https://medium.com/media/a17ffa3c8538022c98ee57f65f981290/href">https://medium.com/media/a17ffa3c8538022c98ee57f65f981290/href</a></iframe><h3>Logistic Regression</h3><p>This time, we are going to create a simple logistic regression model to classify news to either real or fake, using the same data sets, same methods of text cleaning and the same way of train_test_split.</p><p>The process is very simple and easy. We will clean and pre-process the text data, perform feature extraction using <a href="https://www.nltk.org/">NLTK</a> library, build and deploy a logistic regression classifier using <a href="https://scikit-learn.org/stable/">Scikit-Learn</a> library, and evaluate the model’s accuracy at the end.</p><h4>Pre-processing</h4><ul><li>In the following pre-processing, we strip off any html tags, punctuation, and make them lower case.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*kPUZ8ddxz2s9AmYMCJHIPQ.png" /></figure><ul><li>The following code combines tokenization and stemming techniques together, and then apply the techniques on “title_text”.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*H9-N0u3_Lz32VgEL9--Jnw.png" /></figure><h4>TF-IDF</h4><p>Here we transform “title_text” feature into TF-IDF vectors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*rwt_w4wVgzHM-nuwDDRG2g.png" /></figure><ul><li>Instead of tuning C parameter manually, we can use an estimator which is LogisticRegressionCV.</li><li>We specify the number of cross validation folds cv=5 to tune this hyperparameter.</li><li>The measurement of the model is the accuracy of the classification.</li><li>By setting n_jobs=-1, we dedicate all the CPU cores to solve the problem.</li><li>We maximize the number of iterations of the optimization algorithm.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JoHHgLjSblL8krCfsFrPWg.png" /></figure><ul><li>Evaluate the performance.</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgfycat.com%2Fifr%2Fshallowblushinglhasaapso&amp;display_name=Gfycat&amp;url=https%3A%2F%2Fgfycat.com%2Fshallowblushinglhasaapso&amp;image=https%3A%2F%2Fthumbs.gfycat.com%2FShallowBlushingLhasaapso-size_restricted.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=gfycat" width="1280" height="882" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d664e764e026df653875e8d8e9d7506/href">https://medium.com/media/5d664e764e026df653875e8d8e9d7506/href</a></iframe><h3>Summary</h3><p>We found that the deep learning model and Logistic Regression produced the similar results. Only the training time for Logistic Regression is half of the training time for deep learning.</p><p>The obvious difference, from the above process, is that the Deep Neural Network is estimating many more parameters and even more permutations of parameters than the logistic regression. Basically, we can think of logistic regression as a one layer neural network.</p><p>To sum it up, I would recommend to solve a classification problem with a simple model first (e.g., logistic regression). In our example, this would’ve already solved our problem sufficiently well. In other cases, when we are not satisfied the simple models’ performance and we have sufficient training data, we’d try to train a deep neural network, which has the advantage to learn more complex, non-linear functions.</p><p>The project repository can be found on <a href="https://github.com/susanli2016/dsProject_LogReg_DL">Github</a>. Have a great week!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82a3527aaf13" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Analysis on American National Election Studies (ANES)]]></title>
            <link>https://medium.com/data-science/the-analysis-on-american-national-election-studies-anes-8096799b72d4?source=rss-731d8566944a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8096799b72d4</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[survey-analysis]]></category>
            <category><![CDATA[anes-2020-pilot-study]]></category>
            <category><![CDATA[election-2020]]></category>
            <category><![CDATA[statistical-analysis]]></category>
            <dc:creator><![CDATA[Susan Li]]></dc:creator>
            <pubDate>Fri, 03 Sep 2021 05:22:15 GMT</pubDate>
            <atom:updated>2021-09-05T13:45:00.284Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*foMGPlHV1Oy0vV6qxrIlSg.jpeg" /><figcaption>Photo credit: Pixabay</figcaption></figure><h4>Statistics, survey, vote intention, public opinion, Joe Biden, Donald Trump</h4><p>Recently, I have been very interested in analyzing data for political science research. Fortunately, its easy to find political science data, encyclopedias, and information about quantitative and qualitative research methods.</p><h3>The Data</h3><p><a href="https://electionstudies.org/">The ANES collects high quality, non-partisan survey data on voting and public opinion</a>.</p><p>After creating an user account and password, you will be able to download the data from its <a href="https://electionstudies.org/data-center/">data center</a>.</p><p>I downloaded <a href="https://electionstudies.org/data-center/2020-exploratory-testing-survey/">the ANES 2020 Exploratory Testing Survey data</a>, its purpose is to assess new questions under consideration for inclusion in the ANES 2020 Time Series Study, especially related to novel issues arising in the election year, question wording effects, and the scaling properties of lengthy question batteries. The dataset includes 3,080 cases, its collection was conducted between April 10, 2020 and April 18, 2020. You can find questionnaire specifications <a href="https://electionstudies.org/wp-content/uploads/2020/07/anes_pilot_2020ets_qnnaire.pdf">here</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a319a41b08c81227db173e6d029b53b/href">https://medium.com/media/0a319a41b08c81227db173e6d029b53b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*9FNdQMydDVS8VZCz-LxghQ.png" /><figcaption>Figure 1</figcaption></figure><p>The data set contains 470 variables (i.e. survey questions), I will only select what I am interested in. In the meantime, I am going to re-name some columns to make them more user friendly, and re-code all the categorical variables according to <a href="https://electionstudies.org/wp-content/uploads/2020/07/anes_pilot_2020ets_qnnaire.pdf">questionnaire specifications</a>. The missing values will be replaced by “NaN”.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/005b22ab360c239ec3ed40eeb2cf33a3/href">https://medium.com/media/005b22ab360c239ec3ed40eeb2cf33a3/href</a></iframe><h3>Vote Choice</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7a94a58695a8c58ba8b6b233c2f48cc/href">https://medium.com/media/e7a94a58695a8c58ba8b6b233c2f48cc/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qbGsvrILHEN_jLIbPswBuw.png" /><figcaption>Figure 2</figcaption></figure><p>According to the data, Donald Trump and Joe Biden were neck to neck as of April 2020 on vote intention.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6431a62b4a32c6516e73b70bf2a24222/href">https://medium.com/media/6431a62b4a32c6516e73b70bf2a24222/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IDY1pjLD10WuObvAUBuq4w.png" /><figcaption>Figure 3</figcaption></figure><p>Little surprise here, when you look at the numbers by party.</p><pre>df_clean.query(&quot;vote == &#39;Donald Trump&#39; &amp; fttrump1 &lt; 5&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rnT4PdD_WWPzUclU6vFXAQ.png" /><figcaption>Table 1</figcaption></figure><p>The above 10 voters gave Trump thermometer rating &lt; 5 but stated that they would vote for him. It looks like they disliked Biden as much.</p><pre>df_clean.query(&quot;vote == &#39;Joe Biden&#39; &amp; ftbiden1 &lt; 5&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X18yBjFQyJvH00h-Ps71mA.png" /><figcaption>Table 2</figcaption></figure><p>The above 15 voters gave Biden thermometer rating &lt; 5 but stated that they would still vote for him. They are mostly democrats, and liked Obama.</p><pre>df_clean.query(&quot;ftbiden1 == 100 &amp; fttrump1 == 100&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rLNTdQ8UtUJfjU5CnKyIBQ.png" /><figcaption>Table 3</figcaption></figure><p>The above 10 voters rated Joe Biden 100 and Trump 100 at the same time, while almost all of them stated that they would vote for Trump.</p><h3>Likability</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8cbf88273f09b649ae45d1e9c054acb8/href">https://medium.com/media/8cbf88273f09b649ae45d1e9c054acb8/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*mAe3WOE2fOq7Jshmwa_YPA.png" /><figcaption>Figure 4</figcaption></figure><p>Among voters who would vote for Biden, 54% liked him, roughly 13% disliked him.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b24476976b8b3b96e7e14a3ad9053616/href">https://medium.com/media/b24476976b8b3b96e7e14a3ad9053616/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*QcYeJudiYRzMWPY7w0R9BA.png" /><figcaption>Figure 5</figcaption></figure><p>Among voters who would vote for Trump, 71% liked him, roughly 5% disliked him. Indeed, Trump was able to stir a lot of apathy within the republicans.</p><h3>Voters’ Age</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef4d82a127af307be4da5a0f65036fb0/href">https://medium.com/media/ef4d82a127af307be4da5a0f65036fb0/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jqt4X6R4Niu176ldIna8TQ.png" /><figcaption>Figure 6</figcaption></figure><p>According to the data, more voters between 30 and 45 year old, and again 55 and 70 year old would vote for Trump, as of April 2020.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9425df1637b329fc251b3b9a1bda7c68/href">https://medium.com/media/9425df1637b329fc251b3b9a1bda7c68/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hHkGTBDOOmwarwye0xGBfg.png" /><figcaption>Figure 7</figcaption></figure><p>Interesting, Trump was more favored by senior women and younger (around 40 years old) men.</p><h3>Economy</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac4beb8d5784cf8aee54332e69e69744/href">https://medium.com/media/ac4beb8d5784cf8aee54332e69e69744/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*KSGoqIOJoJv1sPxgvlGPMw.png" /><figcaption>Figure 8</figcaption></figure><p>Among Biden’s voters, over 86% worried about current state of the economy. 14% did not worry about current state of the economy.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e6a8edd0587a9f2ff9f341089cfd4bf/href">https://medium.com/media/4e6a8edd0587a9f2ff9f341089cfd4bf/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*APxO-5W_VRLJRaRVWTsIiw.png" /><figcaption>Figure 9</figcaption></figure><p>Among Trump’s voters, over 64% worried about current state of the economy. 36% did not worry about current state of the economy.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e11f995e73476ddf6b0b51ffc5a560a2/href">https://medium.com/media/e11f995e73476ddf6b0b51ffc5a560a2/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8tr1chYY4sz9iaGvaQ-k1w.png" /><figcaption>Figure 10</figcaption></figure><p>Vast majority of voters worried about the current state of the economy, with 53% very or extremely worried about the current state of the economy.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe4bf5ed7282d7313a7bb1200d4de2e2/href">https://medium.com/media/fe4bf5ed7282d7313a7bb1200d4de2e2/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yALptqDSyDCz1fLGC22sLg.png" /><figcaption>Figure 11</figcaption></figure><p>85% of democrats worried about current state of the economy, with 63% very or extremely worried about current state of the economy. While 65% of republicans worried about current state of the economy, with 41% very or extremely worried about current state of the economy.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a5196fa7d3c5ea3a66b62f0220b077b/href">https://medium.com/media/6a5196fa7d3c5ea3a66b62f0220b077b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z1klMdLLXYJ7-88UgkN12w.png" /><figcaption>Figure 12</figcaption></figure><p>Female democrats are most worried about current state of the economy, 18% more than female republicans among extremely and very worried about current state of the economy. While male democrats only 6% more than male republicans among extremely and very worried about current state of the economy.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c33860f52fe96306266a8d80b5d4c74e/href">https://medium.com/media/c33860f52fe96306266a8d80b5d4c74e/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ET8UKjCcw-gkvVqTAa4HmQ.png" /><figcaption>Figure 13</figcaption></figure><p>35–45 year old &amp; 55–75 year old age groups were the most worried about current state of the economy.</p><h3>Universal Basic Income</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a451dae848daff6c78d8a8503ee4029/href">https://medium.com/media/2a451dae848daff6c78d8a8503ee4029/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*Evu4dJgOBS8KPC1CV9r8yg.png" /><figcaption>Table 4</figcaption></figure><p>32% of Trump’s voters oppose universal basic income a great deal, while 18% favor a great deal.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6d9e634ad423ff7fd3274eea0897d32/href">https://medium.com/media/e6d9e634ad423ff7fd3274eea0897d32/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*14HEPb9oBiEoo9TwMh0xOw.png" /><figcaption>Table 5</figcaption></figure><p>6% of Biden’s voters oppose universal basic income a great deal, while 26% favor a great deal.</p><h3>Universal Basic Income vs. Political Ideology</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82186db1f4e5ceb15fc962fa8cb333d9/href">https://medium.com/media/82186db1f4e5ceb15fc962fa8cb333d9/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*3cg7W9k8cNwjThxVWAqOPw.png" /><figcaption>Table 6</figcaption></figure><p>Over 50% of the conservatives oppose universal basic income, and 36% oppose a great deal. Almost 70% liberals favor universal basic income and 34% favor a great deal.</p><h3>Universal Basic Income &amp; Free College</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e3ecafca3b7a5e71b0f1acd75efc50a/href">https://medium.com/media/8e3ecafca3b7a5e71b0f1acd75efc50a/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*n52XSoSq0CjPTYOJW-l5Hw.png" /><figcaption>Figure 14</figcaption></figure><p>Among Biden’s voters, 45% favor both universal basic income and free college, 55% oppose both.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a83588d88909925646c32db107ac35f5/href">https://medium.com/media/a83588d88909925646c32db107ac35f5/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*KLQtPBP23URNDG05vSjnEw.png" /><figcaption>Figure 15</figcaption></figure><p>Among Trump’s voters, 29% favor both universal basic income and free college, 71% oppose both.</p><h3>MeToo vs. Feminists</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5886bce8b0b97d525687dc083de0a445/href">https://medium.com/media/5886bce8b0b97d525687dc083de0a445/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*gMTKfHVeGPNdK9uat3Rr2w.png" /><figcaption>Table 7</figcaption></figure><p>Voters who favored Trump had the lowest favorability on #MeToo &amp; feminists, voters who favored Biden had the highest favorability on these two movements.</p><h3>Thermometer Rating</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26452cfe47f872895a162a55aa69c90f/href">https://medium.com/media/26452cfe47f872895a162a55aa69c90f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*aytWF8dTdWqyiW2jFHy-vw.png" /><figcaption>Table 8</figcaption></figure><p>The correlation between Biden and Trump’s thermometer ratings is negative, as it should be.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e10cb36c801269b7e0176cc58f571e61/href">https://medium.com/media/e10cb36c801269b7e0176cc58f571e61/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qJOml-kAu6wjdY8wsV95lQ.png" /><figcaption>Figure 16</figcaption></figure><p>Democrats were mostly united in rating Trump very low, but they had a wide range of mixed feelings towards Biden. Republicans were united in rating Biden very low, and they were a little bit more clustered around higher ratings for Trump. Independents were spread out all over the place.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/445884db59d03cb8f41582a72ba9b69c/href">https://medium.com/media/445884db59d03cb8f41582a72ba9b69c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ga-9wWq9Nj0YS5sG8B3mVQ.png" /><figcaption>Figure 17</figcaption></figure><p>There isn’t obvious difference between how male vs. female rated on both candidates.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1ad10e14eaad5e67478f41f9b7d178c/href">https://medium.com/media/a1ad10e14eaad5e67478f41f9b7d178c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*BZ2ZWrRDi7PAPbLkYN15eA.png" /><figcaption>Figure 18</figcaption></figure><p>Apparently, Biden’s average thermometer rating was higher among younger voters, and Biden and Trump average thermometer ratings among older voters were similar.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9372baf99747163833f5c4c4d51a903c/href">https://medium.com/media/9372baf99747163833f5c4c4d51a903c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x9SqdySZheP0XF35X4wvTg.png" /><figcaption>Figure 18</figcaption></figure><p>More people had extreme opinions of Trump, and more people had mediocre opinions of Biden.</p><h3>Statistical Analysis</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca389b9c9f42a1952c964e3fd776cd63/href">https://medium.com/media/ca389b9c9f42a1952c964e3fd776cd63/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*YZbZl-u7yTUKihF4IYw9-Q.png" /><figcaption>Table 9</figcaption></figure><p>There is a clear relationship between party affiliation and candidates’ thermometer ratings.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/12cf9c18dc7ea19422d8d7ed7953cd8d/href">https://medium.com/media/12cf9c18dc7ea19422d8d7ed7953cd8d/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*LLa6YdqxVmnx3Fy_fpB1FQ.png" /><figcaption>Table 10</figcaption></figure><p>Liberals who extremely worried about economic impact of the coronavirus rated Biden 40.57 points higher than Trump on average, and conservatives who did not at all worry about economic impact of the coronavirus rated Trump 60.71 points higher than Biden on average.</p><h4>Hypothesis Tests</h4><p>Whether there is a significant difference between men and women on how they rate Trump vs. Biden.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2794d85a6a812d934d64342802dcc73f/href">https://medium.com/media/2794d85a6a812d934d64342802dcc73f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*TyTJ_KbnxCciTEpu0pOigw.png" /></figure><p>We can reject the null hypothesis and conclude that there is a statistically significant difference between men and women in terms of how highly they rate Trump, on average.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b238b96dc91a217e8938b29a53c5c292/href">https://medium.com/media/b238b96dc91a217e8938b29a53c5c292/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*v5AbWfYQO6BpBQmNbg943w.png" /></figure><p>We failed to reject the null hypothesis and that women and men have the same average thermometer rating to Biden.</p><h4>Compare the Average Rating of Trump to the Average Rating of Biden</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68200dbe7d75aec42f38ac2a71b0418b/href">https://medium.com/media/68200dbe7d75aec42f38ac2a71b0418b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*BmbpJKM3GzVAP-5EAKTxeg.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/808e9e2a4cbf0448c5ed4433dcb26345/href">https://medium.com/media/808e9e2a4cbf0448c5ed4433dcb26345/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*Qzw0rpeGG-i84wSOakXdKA.png" /></figure><p>We reject the null hypothesis and conclude that there is a statistically significant difference between voters rate Trump vs. Biden, on average.</p><h4>Test of Multiple Comparisons</h4><p>Whether there is a significant difference between the average age of democrat, independent, and republican voters.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f12c177521f606dc62dff8e3f4b0cfb0/href">https://medium.com/media/f12c177521f606dc62dff8e3f4b0cfb0/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/1*l2ZdnIoxE4bopvTl_qFCIQ.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/642b2ecaa0c760dec096316d32979c3e/href">https://medium.com/media/642b2ecaa0c760dec096316d32979c3e/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*g2jk0OnTleLrLBHdh2YYew.png" /></figure><p>The p-value is much smaller than .05, so we reject the null hypothesis and conclude that there is a statistically significant difference between these three parties in terms of voters’ average age.</p><h4>Tests of Association</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cce9136d117e72dd14b70e5c1363932e/href">https://medium.com/media/cce9136d117e72dd14b70e5c1363932e/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*HXukO9TGee8FIE0qq-Y_5w.png" /></figure><p>Conservatives overwhelmingly oppose both universal basic income &amp; free college, with 79% of conservatives stating that they oppose them. Only 44% of liberals, in contrast, oppose both universal basic income &amp; free college.</p><p>Whether these differences are strong enough for us to conclude that there are ideological differences in support for both universal basic income &amp; free college.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1cdb91e0fcecd076918838aee94a466/href">https://medium.com/media/e1cdb91e0fcecd076918838aee94a466/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*XJWSRz1nUJGIdx-s4cbEcg.png" /></figure><p>The p-value at 3.56e-73 is much less than .05. Therefore, we reject the null hypothesis and conclude that there is a statistically significant relationship between ideology and support for both universal basic income &amp; free college.</p><h4>Principal Component Analysis (PCA)</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01aabfd5445c2077075d1b89016248bf/href">https://medium.com/media/01aabfd5445c2077075d1b89016248bf/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*CWOOCVC6ILDZb-_Kwu4cnQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*p0O-6g2Bc9AUlc_Q-f33-w.png" /><figcaption>Table 11</figcaption></figure><p>The first feature (dim1) seems to represent the traditional left-right ideological spectrum. The republican party, Trump, Pence, Haley, Rubio, along with big business, capitalists and white load most strongly on one side of this index, and Warren, Pelosi, Harris, democratic party load most strongly on the other side.</p><pre>loadings.sort_values(&#39;dim2&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*JVzwvHQvTQ4EfAwWwLnLMQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*ff0pQBulvg-9CWGq_gMpWg.png" /><figcaption>Table 12</figcaption></figure><p>The second feature(dim2) seems associated with left-right political ideology as well.</p><h4>Multiple Correspondence Analysis (MCA)</h4><p>Similar to PCA, but MCA works with categorical features instead of continuous-valued ones.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eca0b67674664cd580d9763ce86f9e58/href">https://medium.com/media/eca0b67674664cd580d9763ce86f9e58/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*voMbjz_se31DcWxENzALfQ.png" /><figcaption>Table 13</figcaption></figure><p>The first latent feature (0) starts from the top, it represents categories for liberal ideology, for example: voting for Hillary Clinton in 2016, identifying as a Democrat, voting for Joe Biden in 2020, favoring free college a great deal, and believing science is extremely important. On the other end we have categories for conservative ideology, for example: opposing a great deal on both universal basic income and free college, identifying as a republican, no at all worried about the economy. This first latent feature appears to be the left-right ideological dimension.</p><pre>mca.column_coordinates(df_cat).sort_values(1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*y-NzKOrska5XXVTzc8YGJA.png" /><figcaption>Table 14</figcaption></figure><p>For the second latent feature, we have positions that do not take a position: Did not vote in 2016, probably will not vote in 2020, and neither favor nor oppose universal basic income, and free college. This appears to measure voter apathy.</p><p><a href="https://github.com/susanli2016/Machine-Learning-with-Python/blob/master/Anes_2020.ipynb">Jupyter notebook</a> can be found on <a href="https://github.com/susanli2016/Machine-Learning-with-Python/blob/master/Anes_2020.ipynb">Github</a>, enjoy the long weekend!</p><p>Reference:</p><p><a href="https://jkropko.github.io/surfing-the-data-pipeline/ch12.html">https://jkropko.github.io/surfing-the-data-pipeline/ch12.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8096799b72d4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/the-analysis-on-american-national-election-studies-anes-8096799b72d4">The Analysis on American National Election Studies (ANES)</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Forecasting the 2020 US Election Using Multilevel Regression with Post-stratification]]></title>
            <link>https://medium.com/data-science/forecasting-the-2020-us-election-using-multilevel-regression-with-post-stratification-bbf2f93585fb?source=rss-731d8566944a------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbf2f93585fb</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pymc3]]></category>
            <category><![CDATA[public-opinion]]></category>
            <category><![CDATA[survey-data]]></category>
            <category><![CDATA[bayesian-statistics]]></category>
            <dc:creator><![CDATA[Susan Li]]></dc:creator>
            <pubDate>Sun, 18 Jul 2021 06:16:08 GMT</pubDate>
            <atom:updated>2021-09-16T06:27:10.706Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xk-U2hD34_2NnYM0NeiYSQ.jpeg" /><figcaption>Photo credit: Pixabay</figcaption></figure><h4>Presidential election, Trump, Political Polls, PYMC3, Python</h4><h3>How to Estimate Public Opinion in the States</h3><p>The most commonly used method for estimating state- level opinion is called <strong><em>disaggregation</em></strong>. The process is simple and easy to implement: After combining a set of national polls, you calculate the opinion percentages disaggregated by state.</p><p>The problem with <strong><em>disaggregation</em></strong> is that it requires a large number of national surveys that collected over 10 years or more to create a sufficient sample size within each state. In addition, <strong><em>disaggregation</em></strong> does not correct for sampling issues and may obscure temporal dynamics in state opinion.</p><p>To overcome these drawbacks, <a href="https://en.wikipedia.org/wiki/Multilevel_regression_with_poststratification"><strong><em>Multilevel Regression with Post-stratification</em></strong></a> (<strong><em>MRP</em></strong>) was developed to estimate American state-level opinions from national polls.</p><h3>What is <strong><em>Multilevel Regression with Post-stratification</em></strong> (MRP)?</h3><p>MRP begins by using multilevel regression to model individual survey responses as a function of demographic and geographic predictors, partially pooling respondents across states to an extent determined by the data. The final step is post-stratification, in which the estimates for each demographic-geographic respondent type are weighted (post-stratified) by the percentages of each type in the actual state populations.</p><p>Let’s say we run a survey asking people if they support gay marriage. We have a survey with 1,000 respondents, 700 of which are male and 300 of which are female. We could use the survey results to calculate the proportion of people who support gay marriage. However, we know that the population distribution between male and female is roughly 50%/50%, rather than 70%/30% implied by our survey. So just taking the raw result from our survey over-represents the opinions of male.</p><p>Given we know the gender distribution of the broader population, we can reweight (post-stratify) our results: so in this example, an estimate of the proportion of people who support gay marriage would be:</p><p><strong><em>0.5 X Proportion of Male + 0.5 X Proportion of Female</em></strong></p><p>This technique is called post-stratification. We need survey data and a reliable census data that gives us the population weights. Data can be re-weighted based on many different categories, such as age, education, gender, race, etc.</p><h3>Forecasting the 2020 US election</h3><p>In this post, we will follow examples <a href="https://www.tellingstorieswithdata.com/mrp.html#ref-wang2015forecasting">here</a> and <a href="https://austinrochford.com/posts/2017-07-09-mrpymc3.html">here</a> to forecast the 2020 US election using the technique of disaggregation &amp; MRP and two data sets (one polling data set and one census data set). Let’s go!</p><h3>The Elections Polls Data</h3><p>I won’t be able to share the data set, however, below is the instruction on how to get the data:</p><ol><li>Go to website: <a href="https://www.voterstudygroup.org/">https://www.voterstudygroup.org</a>.</li><li>Click “Nationscape”.</li><li>Click “GET THE LATEST NATIONSCAPE DATA”.</li><li>Fill your name and email address then click “SUBMIT REQUEST”.</li><li>You will receive an email with a download link, click this link.</li><li>We will download .dta files.</li><li>Unzip the downloaded “Nationscape-DataRelease_WeeklyMaterials_DTA_200910_161918”, then open the folder “phase_2_v20200814”.</li><li>There are many dta.files, I am using “ns20200625.dta”, which refers to 25 June 2020.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2ff0ef66e515e2c42e34be5f2966696/href">https://medium.com/media/a2ff0ef66e515e2c42e34be5f2966696/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5uoCHRlhFVZl1jAiwr3seQ.png" /><figcaption>Table 1</figcaption></figure><p>There are many features in the data, this analysis will need seven: “vote_2020”, “race_ethnicity”, “education”, “state”, “gender”, “age”, “census_region”.</p><h3>EDA</h3><pre>df.vote_2020.value_counts(normalize=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*iqm_PPL5BqwTDLat2sHAMQ.png" /><figcaption>Figure 1</figcaption></figure><p>In the data, roughly 42% said they would vote for Biden and 38% said they would vote for Trump, 10% were not sure, and so on.</p><h4>Number of Poll Respondents by States</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ddd7e8ed3e062f85bb90c3d10f08e5cb/href">https://medium.com/media/ddd7e8ed3e062f85bb90c3d10f08e5cb/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eOh253a72FzgRbCG0lOB3w.png" /><figcaption>Figure 2</figcaption></figure><p>Obviously, the bigger the state, the more poll respondents. Notably, every state had respondents.</p><h4>Respondents by State and Race</h4><ol><li>We will simplify race to four categories: “White”, “Black”, “Asian” and “Others”.</li><li>Because we are interested in Trump’s voters, we will re-code “vote_2020” variable.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a91f0abe5d12ea007ccffd77a646177/href">https://medium.com/media/4a91f0abe5d12ea007ccffd77a646177/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iOY3K7e7l9nbCnn5uDzIaA.png" /><figcaption>Figure 3</figcaption></figure><p>All the states had white respondents, several states had no black and / or Asian respondents, even more states had very few black and / or Asian respondents.</p><h4>Respondents by State and Gender</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/649a5ee19d272504185feb422eeec2a7/href">https://medium.com/media/649a5ee19d272504185feb422eeec2a7/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sk8I_9Fesdy8mSFIAujxGA.png" /><figcaption>Figure 4</figcaption></figure><p>One state (WY) had no female respondent, all the other states had both male and female respondents.</p><h4>Disaggregation Estimate Support for Trump</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2485b2f74744c2dedad9e9de9a424b34/href">https://medium.com/media/2485b2f74744c2dedad9e9de9a424b34/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EZj4lzyp_4eUqgR8eGIZ3Q.png" /><figcaption>Figure 5</figcaption></figure><p>Arkansas had the highest support, and Vermont had the lowest support for Trump.</p><h4>Vote for Trump by Age and Gender</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5f430ef2eb3bbabf61764de5f06efa9/href">https://medium.com/media/c5f430ef2eb3bbabf61764de5f06efa9/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ie2SUWfH-BOwXs5zY2nhfw.png" /><figcaption>Figure 6</figcaption></figure><p>In this poll, around 35–45 years old male were the largest voting block for Trump.</p><h4>Simplify education and age variables</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dafb3dffb73202769befb8f29c41d8fe/href">https://medium.com/media/dafb3dffb73202769befb8f29c41d8fe/href</a></iframe><p>We’re going to explore Trump’s voters by combining all possible combinations of gender(2 categories), race (4 categories), age (4 categories) and education (4 categories).</p><h4>Vote for Trump by Gender</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7da4c122c9b2e78b4cba9ffbadfe7c2c/href">https://medium.com/media/7da4c122c9b2e78b4cba9ffbadfe7c2c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*gwaivNG3QhweXjDQC-siUg.png" /><figcaption>Table 2</figcaption></figure><p>Among voters who said they would vote for Trump, roughly 43% are female, and 57% are male.</p><h4>Vote for Trump by Age Category</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb431a1bbc6b8c575f293b88b981e7eb/href">https://medium.com/media/eb431a1bbc6b8c575f293b88b981e7eb/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*KsgUelsBt9liI5BYA2-veQ.png" /><figcaption>Table 3</figcaption></figure><p>30-44 years old are the largest voting block, followed by 60 years old and over.</p><h4>Vote for Trump by Age and Gender</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c70522f370bda858088d5b75653c9a9/href">https://medium.com/media/2c70522f370bda858088d5b75653c9a9/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*Ye09SmcJrRocXyfJycFl-A.png" /><figcaption>Table 4</figcaption></figure><h4>Vote for Trump by Race</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c63b4f0de4e7c8d8d35322e44854a1f/href">https://medium.com/media/5c63b4f0de4e7c8d8d35322e44854a1f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*jB13FLZ3pbNtffj3wLa-zw.png" /><figcaption>Table 5</figcaption></figure><h4>Vote for Trump by Race &amp; Gender</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4b93a5206866d9f2cf029e8213ed2d8/href">https://medium.com/media/f4b93a5206866d9f2cf029e8213ed2d8/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*FPajA4FUbrZdogzWspj94w.png" /><figcaption>Table 6</figcaption></figure><h4>Vote for Trump by Race &amp; Age</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd73e4bd6edc65fdc22639ee0548b79b/href">https://medium.com/media/fd73e4bd6edc65fdc22639ee0548b79b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*xyUcEjFxX-B67KB-JU5BDQ.png" /><figcaption>Table 7</figcaption></figure><h4>Vote for Trump by Education</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0be4b6f4dda5cd9bdc3cc5e61d6d6da4/href">https://medium.com/media/0be4b6f4dda5cd9bdc3cc5e61d6d6da4/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*XPG1AJu3sYEN-kTGaRFieQ.png" /><figcaption>Table 8</figcaption></figure><h4>Vote for Trump by Education &amp; Gender</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/57c4118c391afd54d7b5aa228feeaa70/href">https://medium.com/media/57c4118c391afd54d7b5aa228feeaa70/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*iLrzE6KGg_5Vv40S011wuQ.png" /><figcaption>Table 9</figcaption></figure><h4>Vote for Trump by Education &amp; Race</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16612ee52ed563f249fd88fa2bca1ae7/href">https://medium.com/media/16612ee52ed563f249fd88fa2bca1ae7/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*Fd4yvN_LUoi3CyGgltj8og.png" /><figcaption>Table 10</figcaption></figure><h4>Vote for Trump by Education &amp; Age</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ea5fc2775eae7a7ab60ee56819c46b8/href">https://medium.com/media/1ea5fc2775eae7a7ab60ee56819c46b8/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*Ud5B8PCw_JHLPBQftU42Nw.png" /><figcaption>Table 11</figcaption></figure><h3>Multilevel Model</h3><p>Our multilevel polling model will include factors for state, race, gender, education, age, and vote. In order to accelerate inference, we count the number of unique combinations of these factors, along with how many respondents with each combination will vote for Trump.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb18697ca81dede33146b14a89ce0205/href">https://medium.com/media/fb18697ca81dede33146b14a89ce0205/href</a></iframe><p>This reduction reduces the number of rows in the data set by almost 70%.</p><pre>uniq_dt_df.shape[0] / dt_df.shape[0]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/255/1*pBTU9Y-16CtZ-w3xLJM3oA.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6951c65a2d79de191872ed5f8fffe36/href">https://medium.com/media/d6951c65a2d79de191872ed5f8fffe36/href</a></iframe><p>Now we’ re ready to specify the model with PyMC3, start with wrapping the predictors in theano.shared.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c26e010469c84d07cd03d40a8d625ae8/href">https://medium.com/media/c26e010469c84d07cd03d40a8d625ae8/href</a></iframe><p>We specify the multilevel (hierarchical) model for α_state.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7dd33c8d690be839f9c65be03298885a/href">https://medium.com/media/7dd33c8d690be839f9c65be03298885a/href</a></iframe><p>We specify the parameters as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2528fd70ff278bb010c93ea74e0fd57b/href">https://medium.com/media/2528fd70ff278bb010c93ea74e0fd57b/href</a></iframe><p>Finally, we specify the likelihood and sample from the model using NUTS.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91965f780b26f4006b716aef4ff5448b/href">https://medium.com/media/91965f780b26f4006b716aef4ff5448b/href</a></iframe><p>We can verify the convergence of the chains formally using the Gelman Rubin test. Values close to 1.0 mean convergence.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70d62e79f4701c914eb3e1541b447fde/href">https://medium.com/media/70d62e79f4701c914eb3e1541b447fde/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*r0Hhs-CImUKHEr5e_OBYUw.png" /><figcaption>Figure 6</figcaption></figure><h3>Post-stratification Data</h3><p>We will use IPUMS US Census &amp; American Community Survey data. Again, I won’t be able to share the data set, here are the steps on how to get it:</p><ol><li>Go to IPUMS website: <a href="https://ipums.org/">https://ipums.org</a>, then click “VISIT SITE” on “IPUMS USA”.</li><li>Click “Get Data”.</li><li>If you’ve not done before, you will need to create an account, then wait for a confirmation.</li><li>Once you have an account, go to ‘Select Samples’ and de-select everything apart from the 2019 ACS.</li><li>We need to get the variables that we’re interested in. From the household we want ‘STATEICP,’ then in person we want “SEX”, “AGE”, “EDUC” and “RACE”.</li><li>Once everything is selected, “view cart”, and we want to change the data format to “.dta”. It should be less than 300MB, then submit the request.</li><li>You should get an email saying that your data can be downloaded in a few minutes.</li><li>I downloaded and saved “usa_00002.dta” in my data folder.</li></ol><p>We now can start cleaning up the data, that including re-organize age category, education category, race category and change state names to two-letter state abbreviations, that in align with the survey polls data we analyzed earlier.</p><pre>census_df = pd.read_stata(&#39;data/usa_00002.dta&#39;)<br>census_df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S_cjC0vpEP2V-IEmYwq1xw.png" /><figcaption>Table 12</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/90ab3a89e978323eeea2e02465fcec83/href">https://medium.com/media/90ab3a89e978323eeea2e02465fcec83/href</a></iframe><p>After creating counts of each sub-cell, and proportions by state, merge with the previous state data. Now we finally have our Post-stratification data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*RkgTpbyVqmLsN4lEszuJBg.png" /><figcaption>Table 13</figcaption></figure><p>Again we encode category variables to numeric and encode this combined data in the same way as before.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9ea4aa69d28d8292147e994c548794c/href">https://medium.com/media/f9ea4aa69d28d8292147e994c548794c/href</a></iframe><p>We now set the values of the theano.shared variables in our PyMC3 model to the post-stratification data and sample from the posterior predictive distribution.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc8873f4f4aaabe41c53d96541395c84/href">https://medium.com/media/dc8873f4f4aaabe41c53d96541395c84/href</a></iframe><p>We complete the post-stratification step by taking a weighted sum across the demographic cells within each state, to produce posterior predictive samples from the state-level polling distribution. The simplest summary of state-level poll is the posterior expected mean.</p><p>The following map shows the MRP estimates of support for Trump by state.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec7d89797ce63520c8ed072436072082/href">https://medium.com/media/ec7d89797ce63520c8ed072436072082/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YB-Ckirvtsu_fiXny1SpbA.png" /><figcaption>Figure 7</figcaption></figure><p>And we can have a look at our estimates to compare how the estimate for each state differs between disaggregation and MRP.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6707525f403567aef74924432a3f5c81/href">https://medium.com/media/6707525f403567aef74924432a3f5c81/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*o4Z5gpkanl5isKt2n9C7lg.png" /><figcaption>Figure 8</figcaption></figure><h3>How Trump was Supported by Black Men?</h3><p>Let’s try to answer this question by two estimates.</p><p>First we plot the disaggregation estimates of support for Trump among black men. We realized that the pollsters polled few or none black men in many states. Therefore, support for Trump in these states among black men cannot be measured using disaggregation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ed56037106823fd6a4ff1b9d158fcfe/href">https://medium.com/media/0ed56037106823fd6a4ff1b9d158fcfe/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FuiV17AKGiOI6s5-yhgoNQ.png" /><figcaption>Figure 9</figcaption></figure><p>While using MRP, we are able to estimate support for Trump among black men for all the states.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b71d7e52eece54fa53815d765140792e/href">https://medium.com/media/b71d7e52eece54fa53815d765140792e/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N5WFIRMhZWgILr3u8ArFWg.png" /><figcaption>Figure 10</figcaption></figure><p><a href="https://github.com/susanli2016/Machine-Learning-with-Python/blob/master/Multilevel%20regression%20with%20post-stratification_election2020.ipynb">Jupyter notebook</a> can be found on <a href="https://github.com/susanli2016/Machine-Learning-with-Python/blob/master/Multilevel%20regression%20with%20post-stratification_election2020.ipynb">Github</a>. Have a great weekend.</p><p>References:</p><p><a href="https://scholar.princeton.edu/sites/default/files/jkastellec/files/mrp_primer.pdf">https://scholar.princeton.edu/sites/default/files/jkastellec/files/mrp_primer.pdf</a></p><p><a href="https://austinrochford.com/posts/2017-07-09-mrpymc3.html">MRPyMC3 - Multilevel Regression and Poststratification with PyMC3</a></p><p><a href="https://www.tellingstorieswithdata.com/mrp.html#ref-wang2015forecasting">https://www.tellingstorieswithdata.com/mrp.html#ref-wang2015forecasting</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbf2f93585fb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/forecasting-the-2020-us-election-using-multilevel-regression-with-post-stratification-bbf2f93585fb">Forecasting the 2020 US Election Using Multilevel Regression with Post-stratification</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Quick Introduction On Granger Causality Testing For Time Series Analysis]]></title>
            <link>https://medium.com/data-science/a-quick-introduction-on-granger-causality-testing-for-time-series-analysis-7113dc9420d2?source=rss-731d8566944a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7113dc9420d2</guid>
            <category><![CDATA[stationarity]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[statistical-modeling]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <dc:creator><![CDATA[Susan Li]]></dc:creator>
            <pubDate>Wed, 23 Dec 2020 09:32:54 GMT</pubDate>
            <atom:updated>2020-12-23T15:05:22.236Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qtwFWkSYilENB1Ae9qZX3g.jpeg" /><figcaption>Photo Credit: Pixabay</figcaption></figure><h4>Augmented Dickey-Fuller (ADF) test, <strong>Kwiatkowski–Phillips–Schmidt–Shin (KPSS) tests, </strong>Vector Autoregressions (VA), Durbin–Watson statistic, Cointegration test</h4><p>The <a href="https://en.wikipedia.org/wiki/Granger_causality"><strong>Granger causality test</strong></a> is a statistical hypothesis test for determining whether one time series is a factor and offer useful information in forecasting another time series.</p><p>For example, given a question: Could we use today’s Apple’s stock price to predict tomorrow’s Tesla’s stock price? If this is true, our statement will be Apple’s stock price Granger causes Tesla’s stock price. If this is not true, we say Apple’s stock price does not Granger cause Tesla’s stock price.</p><h3>The Data</h3><p>So, let’s go to <a href="https://ca.finance.yahoo.com/">Yahoo Finance</a> to fetch the adjusted close stock price data for Apple, Walmart and Tesla, start from 2010–06–30 to 2020–12–18.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18ae8f882434ffd32ce8fc6c968aeb2c/href">https://medium.com/media/18ae8f882434ffd32ce8fc6c968aeb2c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*1JjjIDVstF95Svn4UHqjvw.png" /><figcaption>Table 1</figcaption></figure><h3>Visualize the Time Series</h3><p>Time series can be represented using either line chart or area chart.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa44523ff8562f27dba8aec105f71342/href">https://medium.com/media/fa44523ff8562f27dba8aec105f71342/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cc9keceSy19yF7-h6wUFYQ.png" /><figcaption>Figure 1</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e68fd5bdbfd9a5cbd00814bcbdc2b00/href">https://medium.com/media/2e68fd5bdbfd9a5cbd00814bcbdc2b00/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Xf7jFfVkXOx1h6oSIr6Jw.png" /><figcaption>Figure 2</figcaption></figure><p>Apple and Walmart time series have a fairly similar trend patterns over the years, where Tesla Stock IPOed just over 10 years ago and it has surprised everyone with over 700% rise year-to-date in 2020.</p><h3>ADF Test for Stationarity</h3><p><a href="https://en.wikipedia.org/wiki/Augmented_Dickey%E2%80%93Fuller_test">The ADF test</a> is one of the most popular statistical tests. It can be used to help us understand whether the time series is stationary or not.</p><p><strong><em>Null hypothesis</em></strong>: If failed to be rejected, it suggests the time series is not stationarity.</p><p><strong><em>Alternative hypothesis</em></strong>: The null hypothesis is rejected, it suggests the time series is stationary.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b65bfbc3aff43ab173b65ca2e155febd/href">https://medium.com/media/b65bfbc3aff43ab173b65ca2e155febd/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*dHVyKORgr0Yr1qoEtQNWJw.png" /><figcaption>Figure 3</figcaption></figure><p>The p-values are all well above the 0.05 alpha level, we cannot reject the null hypothesis. So the three time series are not stationary.</p><h3>KPSS Test for Stationary</h3><p><a href="https://en.wikipedia.org/wiki/KPSS_test">The KPSS test</a> figures out if a time series is stationary around a mean or linear trend, or is non-stationary due to a unit root.</p><p><strong><em>Null hypothesis</em></strong>: The time series is stationary</p><p><strong><em>Alternative hypothesis</em></strong>: The time series is not stationary</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4782fa6fb679fce03e11f39f5ae44319/href">https://medium.com/media/4782fa6fb679fce03e11f39f5ae44319/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*VYOqOcgCmAW8dohqaZ7ogg.png" /><figcaption>Figure 4</figcaption></figure><p>The p-value are all less than 0.05 alpha level, therefore, we can reject the null hypothesis and derive that the three time series are not stationary.</p><p>After cross-check ADF test and KPSS test. We can conclude that the three time series data we have here are not stationary. We will transform the time series to be stationary by difference method.</p><h3>Difference Method</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c038f2fddc817167de9fec9842b72f28/href">https://medium.com/media/c038f2fddc817167de9fec9842b72f28/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fpcHLb2L4E9oly77LV6Zxw.png" /><figcaption>Figure 5</figcaption></figure><h3>ADF Test Again</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63b204524ab327d40b69600fdb601c10/href">https://medium.com/media/63b204524ab327d40b69600fdb601c10/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*_FWI_yY-4jqw2wF11LSUIA.png" /><figcaption>Figure 6</figcaption></figure><p>After transforming the data, the p-values are all well below the 0.05 alpha level, therefore, we reject the null hypothesis. So the current data is stationary.</p><h3>KPSS Test Again</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/58448a94219937d9b3a5c855bfbf048f/href">https://medium.com/media/58448a94219937d9b3a5c855bfbf048f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*O5h6gLRSpnM8Q8q1JnVM1Q.png" /><figcaption>Figure 7</figcaption></figure><p>Some of the KPSS Null Hypothesis could not be rejected.</p><h3>VAR Model</h3><p>The VAR class assumes that the passed time series are stationary. Non-stationary or trending data can often be transformed to be stationary by first-differencing or some other method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53b185e1390ebae0872bfde37dc49977/href">https://medium.com/media/53b185e1390ebae0872bfde37dc49977/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*xa-VsDlQBDh4dPOwE3ccig.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*WkRy6nbUXPM9McNEGAmtdw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*KNdCEuHPrXM61ZdhPaXHAQ.png" /></figure><p>There is no hard-and-fast-rule on the choice of lag order. It is basically an empirical issue. However, it is often advised to use the AIC in selecting the lag order with the smallest value. Therefore, we will select lag order = 15.</p><pre>results = model.fit(maxlags=15, ic=&#39;aic&#39;)<br>results.summary()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*fogvb66DVLd1sIo3bbDCqg.png" /><figcaption>Table 2</figcaption></figure><p>The biggest correlation is 0.43 (Apple &amp; Tesla).</p><h3>Durbin-Watson Statistic</h3><p>The <a href="https://en.wikipedia.org/wiki/Durbin%E2%80%93Watson_statistic">Durbin Watson Test</a> is a measure of autocorrelation in residuals from regression analysis.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a7462a766f941d06096958bf8b908ec/href">https://medium.com/media/4a7462a766f941d06096958bf8b908ec/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*iYzeUvIw_b5Ncb5jBZVvSg.png" /></figure><p>A value of 2.0 means that there is no autocorrelation detected in the residuals.</p><h3>Granger Causality Test</h3><p>The following code was borrowed from <a href="https://stackoverflow.com/questions/58005681/is-it-possible-to-run-a-vector-autoregression-analysis-on-a-large-gdp-data-with">stackoverflow</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41241882aa44357ed999746a422391f4/href">https://medium.com/media/41241882aa44357ed999746a422391f4/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*CVQRlvcVwX7TCtuZY0DvBg.png" /><figcaption>Table 3</figcaption></figure><p>The row are the response (y) and the columns are the predictors (x). If a given p-value is &lt; significance level (0.05), for example, take the value 0.0 in (row 1, column 2), we can reject the null hypothesis and conclude that walmart_x Granger causes apple_y. Likewise, the 0.0 in (row 2, column 1) refers to walmart_y Granger causes apple_x.</p><p>All the time series in the above data are interchangeably Granger causing each other.</p><h3>Forecasting</h3><p>Remember we transformed the data by difference method, now we will invert the transformation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/19f0c65cf35392c82acebbcdd2f0837d/href">https://medium.com/media/19f0c65cf35392c82acebbcdd2f0837d/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/10c5bffefd599e35f05d790311cc5c0e/href">https://medium.com/media/10c5bffefd599e35f05d790311cc5c0e/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*2ahesrlMkql_gYOdqy-onQ.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/833d9101a09b7ddfa46561e93f8eb974/href">https://medium.com/media/833d9101a09b7ddfa46561e93f8eb974/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*NnmgkO3nM105ZHZllaR06Q.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/165ec8833d7c56e9c6785a9a49836e8c/href">https://medium.com/media/165ec8833d7c56e9c6785a9a49836e8c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*4vb4kc9BvAWS_yAbfjFG4Q.png" /></figure><p><a href="https://github.com/susanli2016/Machine-Learning-with-Python/blob/master/Granger%20Causality%20Test.ipynb">Jupyter notebook</a> can be found on <a href="https://github.com/susanli2016/Machine-Learning-with-Python/blob/master/Granger%20Causality%20Test.ipynb">Github</a>. Happy Holidays!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7113dc9420d2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/a-quick-introduction-on-granger-causality-testing-for-time-series-analysis-7113dc9420d2">A Quick Introduction On Granger Causality Testing For Time Series Analysis</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Bayesian Model for Estimating the Effects of Covid-19 Vaccines]]></title>
            <link>https://medium.com/data-science/a-bayesian-model-for-estimating-the-effects-of-covid-19-vaccines-7e9cec99266b?source=rss-731d8566944a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e9cec99266b</guid>
            <category><![CDATA[bernoulli-distribution]]></category>
            <category><![CDATA[bayesian-inference]]></category>
            <category><![CDATA[covid-vaccine]]></category>
            <category><![CDATA[pymc3]]></category>
            <category><![CDATA[bayesian-statistics]]></category>
            <dc:creator><![CDATA[Susan Li]]></dc:creator>
            <pubDate>Mon, 30 Nov 2020 08:06:33 GMT</pubDate>
            <atom:updated>2020-11-30T14:23:46.575Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z_8WfLQQ1gaLMuKxiaH9Eg.jpeg" /><figcaption>Phone Credit: Pixabay</figcaption></figure><h4>PYMC3, Bernoulli Distribution, Pfizer, Moderna, AstraZeneca</h4><p>Because of the trials are still ongoing, researchers caution against making head-to-head comparisons of vaccines based on incomplete data. But for the sake of learning, we will do it anyway, just not making any meaningful conclusions.</p><p>Recently, the announcements went out that the potential effectiveness of SARS-CoV-2 vaccine candidates developed by <a href="https://www.pfizer.com/news/press-release/press-release-detail/pfizer-and-biontech-conclude-phase-3-study-covid-19-vaccine">Pfizer-Biontech</a>, <a href="https://investors.modernatx.com/news-releases/news-release-details/modernas-covid-19-vaccine-candidate-meets-its-primary-efficacy">Moderna</a>, <a href="https://www.astrazeneca.com/media-centre/press-releases/2020/azd1222hlr.html">AstraZeneca</a> regimen 1 and AstraZeneca regimen 2 to be 95%, 94.5%, 90% and 62% respectively. We know that some of the data are incomplete. The following analysis will be based on whatever information we currently have.</p><h3>The Data</h3><p>Based on the information from the announcements and the other <a href="http://blog.fellstat.com/">scientist’s blog posts</a>, we know that:</p><p><strong>Pfizer: </strong>Over 43,000 participants got the two doses of the vaccine or placebo. The same number of subjects was assigned to the treatment and control group. An efficacy of 95% implies that among 170 confirmed cases of COVID-19, 8 of them observed in the vaccine group.</p><p><strong>Moderna</strong>: The vaccine is being tested in 30,000 people. Half received two doses of the vaccine, and half received a placebo. Of the 95 cases of covid-19, 90 were in the group that received the placebo.</p><p><strong>AstraZeneca regimen 1</strong>: Regimen 1(first a half dose and at least a month later a full dose) with 2741 participants showed 90% efficacy implies that among 37 confirmed cases of COVID-19, 3 of them observed in the vaccine group.</p><p><strong>AstraZeneca regimen 2</strong>: Regimen 2 (two full doses at least one month apart) with 8896 participants showed 62% efficacy implies that among 94 confirmed cases of COVID-19, 26 of them observed in the vaccine group.</p><p>Therefore, we could set up the data like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/caef011993875cf5589b0d1fa6029eae/href">https://medium.com/media/caef011993875cf5589b0d1fa6029eae/href</a></iframe><h3>The Model</h3><p>Because our variables should be between 0 and 1,we’ll use a <a href="https://en.wikipedia.org/wiki/Beta_distribution">beta distribution</a> for the priors and a <a href="https://en.wikipedia.org/wiki/Bernoulli_distribution">Bernoulli distribution</a> for the likelihood. To start, we assume that we do not know anything about how many participants caught the COVID in each group. So we choose the parameters of the beta distribution a uniform distribution. After we see the observed data, the distribution will change accordingly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9082d5ced2ad92da3ae02b8446ee831/href">https://medium.com/media/e9082d5ced2ad92da3ae02b8446ee831/href</a></iframe><p>At this point, you will be able to evaluate each vaccine trial result individually:</p><pre>az.plot_trace(trace);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4GqyQsmeax5SuVEJ1Kg2sQ.png" /><figcaption>Figure 1</figcaption></figure><p>Or together:</p><pre>sns.distplot(trace[&#39;p_Pfizer&#39;], hist=False, rug=True, label=&#39;Pfizer&#39;)<br>sns.distplot(trace[&#39;p_Moderna&#39;], hist=False, rug=True, label=&#39;Moderna&#39;)<br>sns.distplot(trace[&#39;p_regimen1&#39;], hist=False, rug=True, label=&#39;AstraZeneca regimen 1&#39;)<br>sns.distplot(trace[&#39;p_regimen2&#39;], hist=False, rug=True, label=&#39;AstraZeneca regimen 2&#39;)<br>plt.title(&quot;Posterior distributions of efficacy of different vaccines&quot;)<br>plt.legend()<br>plt.show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*wPk6J2AC-0gi88f0Ilt4Hw.png" /><figcaption>Figure 2</figcaption></figure><p>We can also use Forest plot (95% HPD, IQR and median) of the posterior distribution on the same axes, allowing us to directly compare the vaccines.</p><pre>pm.forestplot(trace, var_names=[&#39;p_Pfizer&#39;, &#39;p_Moderna&#39;, &#39;p_regimen1&#39;, &#39;p_regimen2&#39;]);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*SIrVIEMLRcZBx845y3RPnQ.png" /><figcaption>Figure 3</figcaption></figure><p>According to the available data, it looks like Pfizer’s vaccine has the highest mean effectiveness, and AstraZeneca regimen 2 has the lowest mean effectiveness.</p><h3>Comparison Between Vaccines</h3><p>Is Pfizer’s vaccine always better than Moderna’s? We will create two variables that will contain the “difference” and the “relation” between the variations.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f9841d019543f236ca56dbd2ec58d22/href">https://medium.com/media/9f9841d019543f236ca56dbd2ec58d22/href</a></iframe><pre>_ = pm.plot_posterior(trace_1, varnames=[&#39;difference&#39;, &#39;relation&#39;], ref_val=0);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uq44K0aPA35qWJMHvXRYcA.png" /><figcaption>Figure 4</figcaption></figure><pre>diffs_1 = trace_1.get_values(&#39;difference&#39;, burn=1000)<br>100*len(diffs_1[diffs_1&gt;0])*1.0/len(diffs_1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/1*25OzJxknk3KgIeRvJB9iTA.png" /></figure><p>We can say that the difference in effectiveness of these two vaccines, with 61.4% of the posterior probability are greater than zero. We can not rule out a difference of zero, which suggests these two vaccines are not credibly different.</p><p>Is AstraZeneca regimen 1 always better than AstraZeneca regimen 2?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d560491945b455502c8c1d7a9a2db57/href">https://medium.com/media/0d560491945b455502c8c1d7a9a2db57/href</a></iframe><pre>_ = pm.plot_posterior(trace_2, varnames=[&#39;difference&#39;, &#39;relation&#39;], ref_val=0);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RVzsYIA9p9LQ2Gzh1JXCyw.png" /><figcaption>Figure 5</figcaption></figure><pre>diffs_2 = trace_2.get_values(&#39;difference&#39;, burn=1000)<br>100*len(diffs_2[diffs_2&gt;0])*1.0/len(diffs_2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/1*lFi1ihNAeWNKehc0oSUQng.png" /></figure><p>According to the available data, we have 99% confidence that regimen 1 is more effective than regimen 2.</p><pre>100*len(diffs_2[diffs_2&gt;0.06])*1.0/len(diffs_2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/1*j_RDYOKwrbv9FB03UG-fHQ.png" /></figure><p>There is 95.5% probability that regimen 1 is more effective than regimen 2 by 6%.</p><pre>plt.figure(figsize=(12,4))<br>plt.hist(diffs_2, bins=100, density=True)<br>plt.vlines(0.06, 0, 6, linestyle=&#39;--&#39;, color=&#39;red&#39;)<br>plt.title(&#39;Posterior distribution of the difference of the two regimens&#39;)<br>plt.show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kngtt7t01nk5us0X3l-K5Q.png" /><figcaption>Figure 6</figcaption></figure><p>Please note, <a href="https://www.nytimes.com/2020/11/25/business/coronavirus-vaccine-astrazeneca-oxford.html?action=click&amp;module=Top%20Stories&amp;pgtype=Homepage">scientist communities have described several problematic issues with AstraZeneca vaccine study results</a>. So <a href="https://www.cbc.ca/news/health/covid-19-vaccine-trial-astra-zeneca-1.5817410">AstraZeneca is likely to run an additional global trial</a>. My above analysis will be updated once new data becomes available.</p><p><a href="https://github.com/susanli2016/Machine-Learning-with-Python/blob/master/Compare%20Vaccines%20Effectiveness.ipynb">Jupyter notebook</a> can be found on <a href="https://github.com/susanli2016/Machine-Learning-with-Python/blob/master/Compare%20Vaccines%20Effectiveness.ipynb">Github</a>. Have a nice week!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e9cec99266b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/a-bayesian-model-for-estimating-the-effects-of-covid-19-vaccines-7e9cec99266b">A Bayesian Model for Estimating the Effects of Covid-19 Vaccines</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Time Series of Price Anomaly Detection with LSTM]]></title>
            <link>https://medium.com/data-science/time-series-of-price-anomaly-detection-with-lstm-11a12ba4f6d9?source=rss-731d8566944a------2</link>
            <guid isPermaLink="false">https://medium.com/p/11a12ba4f6d9</guid>
            <category><![CDATA[deep-neural-networks]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[stock-analysis]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Susan Li]]></dc:creator>
            <pubDate>Tue, 08 Sep 2020 02:45:08 GMT</pubDate>
            <atom:updated>2020-09-08T04:15:59.474Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r2STe0WAobpVdOM2iIVVyA.png" /></figure><h4>Johnson and Johnson, JNJ, Keras, Autoencoder, Tensorflow</h4><p><a href="https://en.wikipedia.org/wiki/Autoencoder">Autoencoders</a> are an unsupervised learning technique, although they are trained using supervised learning methods. The goal is to minimize reconstruction error based on a loss function, such as the mean squared error.</p><p>In this post, we will try to detect anomalies in the <a href="https://finance.yahoo.com/quote/JNJ/history?p=JNJ">Johnson &amp; Johnson’s historical stock price time series data</a> with an <a href="https://machinelearningmastery.com/lstm-autoencoders/">LSTM autoencoder</a>.</p><p>The data can be downloaded from <a href="https://finance.yahoo.com/quote/JNJ/history/">Yahoo Finance</a>. The time period I selected was from 1985–09–04 to 2020–09–03.</p><p>The steps we will follow to detect anomalies in Johnson &amp; Johnson stock price data using an LSTM autoencoder:</p><ol><li>Train an LSTM autoencoder on the Johnson &amp; Johnson’s stock price data from 1985–09–04 to 2013–09–03. We assume that there were no anomalies and they were normal.</li><li>Using the LSTM autoencoder to reconstruct the error on the test data from 2013–09–04 to 2020–09–03.</li><li>If the reconstruction error for the test data is above the threshold, we label the data point as an anomaly.</li></ol><p>We will break down an LSTM autoencoder network to understand them layer-by-layer.</p><h3>The Data</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0828be230eb7ad66bdea4ab186374d6a/href">https://medium.com/media/0828be230eb7ad66bdea4ab186374d6a/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*r7BPmL_za2TS-wJG8Cjy-w.png" /></figure><h3>Visualize the timeseries</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e3dd06d2e5d3e88b34809e356dd508b4/href">https://medium.com/media/e3dd06d2e5d3e88b34809e356dd508b4/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tTkBafghZOBEpr4AOFi5jQ.png" /><figcaption>Figure 1</figcaption></figure><h3>Preprocessing</h3><ul><li>Train test split</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52cae18f6bc757562d2740cf8e772199/href">https://medium.com/media/52cae18f6bc757562d2740cf8e772199/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*Sn0mvNhMrvYuijI0ScbFsw.png" /></figure><ul><li>Standardize the data</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7376814b0e84e7ba3d54c4fd7b666f2c/href">https://medium.com/media/7376814b0e84e7ba3d54c4fd7b666f2c/href</a></iframe><ul><li>Create sequences</li></ul><p>Convert input data into 3-D array combining TIME_STEPS. The shape of the array should be [samples, TIME_STEPS, features], as required for LSTM network.</p><p>We want our network to have memory of 30 days, so we set TIME_STEPS=30.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/279a4d5ab7002691384fb769bf4c8c90/href">https://medium.com/media/279a4d5ab7002691384fb769bf4c8c90/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*brqyV0LurLV5rLIx47JvWw.png" /></figure><h3>Build the Model</h3><ul><li>We define the reconstruction LSTM Autoencoder architecture that expects input sequences with 30 time steps and one feature and outputs a sequence with 30 time steps and one feature.</li><li>RepeatVector() repeats the inputs 30 times.</li><li>Set return_sequences=True, so the output will still be a sequence.</li><li>TimeDistributed(Dense(X_train.shape[2])) is added at the end to get the output, where X_train.shape[2] is the number of features in the input data.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fddce272272897ce5c701a0e22f158ae/href">https://medium.com/media/fddce272272897ce5c701a0e22f158ae/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*o_EOPLQBMfzK7wFlXX2dag.png" /><figcaption>Figure 2</figcaption></figure><h3>Train the Model</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27c2e9c21f2a7eded6689efc8101c4ce/href">https://medium.com/media/27c2e9c21f2a7eded6689efc8101c4ce/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zjMe9QBC_HffFdmeoDSLJA.png" /><figcaption>Figure 3</figcaption></figure><pre>plt.plot(history.history[&#39;loss&#39;], label=&#39;Training loss&#39;)<br>plt.plot(history.history[&#39;val_loss&#39;], label=&#39;Validation loss&#39;)<br>plt.legend();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*S_s0EIu4YHl5gsoUpCagnQ.png" /><figcaption>Figure 4</figcaption></figure><pre>model.evaluate(X_test, y_test)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*qdbVA0jFozR7EhMfNYt_kg.png" /></figure><h3>Determine Anomalies</h3><ul><li>Find MAE loss on the training data.</li><li>Make the max MAE loss value in the training data as the reconstruction error threshold.</li><li>If the reconstruction loss for a data point in the test set is greater than this reconstruction error threshold value then we will label this data point as an anomaly.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f2ae108266dd365a89dd7e6d3ebf8fb/href">https://medium.com/media/6f2ae108266dd365a89dd7e6d3ebf8fb/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*c_uE4WS-TQTN42aaP95jEw.png" /><figcaption>Figure 5</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1fc259ffdfcd07bcdb837a2e13363f14/href">https://medium.com/media/1fc259ffdfcd07bcdb837a2e13363f14/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*-MqJeqmME5X_QSjW1yI-Lg.png" /><figcaption>Figure 6</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a02b9382ed57b189ee56a1bef2fb17ea/href">https://medium.com/media/a02b9382ed57b189ee56a1bef2fb17ea/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JCb1l7mjYh4gZpK9g_WGBw.png" /><figcaption>Figure 7</figcaption></figure><pre>anomalies = test_score_df.loc[test_score_df[&#39;anomaly&#39;] == True]<br>anomalies.shape</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/129/1*jQzUTGtB4D7rSpN_lpE0Cw.png" /></figure><p>As you can see, there are 22 data points in the test set that exceeded the reconstruction error threshold.</p><h3>Visualize Anomalies</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42e65a043eafe992bcb930bcff06ab0d/href">https://medium.com/media/42e65a043eafe992bcb930bcff06ab0d/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tHvS1PUj1EpfhbyaH5ZzdQ.png" /><figcaption>Figure 8</figcaption></figure><p>The model found that some low price anomalies in March and high price anomalies in April. As it was well documented that <a href="https://www.investors.com/news/technology/jnj-stock-buy-now/">JNJ stock hit a 2020 low in March, but quickly reaccelerated to a high point less than a month later on bullish expectations for its coronavirus vaccine</a>.</p><p><a href="https://github.com/susanli2016/Machine-Learning-with-Python/blob/master/Timeseries%20anomaly%20detection%20using%20LSTM%20Autoencoder%20JNJ.ipynb">Jupyter notebook</a> can be found on <a href="https://github.com/susanli2016/Machine-Learning-with-Python/blob/master/Timeseries%20anomaly%20detection%20using%20LSTM%20Autoencoder%20JNJ.ipynb">Github</a>. Have a great week!</p><p>References:</p><ul><li><a href="https://machinelearningmastery.com/lstm-autoencoders/">A Gentle Introduction to LSTM Autoencoders - Machine Learning Mastery</a></li><li><a href="https://www.coursera.org/projects/anomaly-detection-time-series-keras">Anomaly Detection in Time Series Data with Keras</a></li><li><a href="https://keras.io/examples/timeseries/timeseries_anomaly_detection/">Keras documentation: Timeseries anomaly detection using an Autoencoder</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11a12ba4f6d9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/time-series-of-price-anomaly-detection-with-lstm-11a12ba4f6d9">Time Series of Price Anomaly Detection with LSTM</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multi Class Text Classification With Deep Learning Using BERT]]></title>
            <link>https://medium.com/data-science/multi-class-text-classification-with-deep-learning-using-bert-b59ca2f5c613?source=rss-731d8566944a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b59ca2f5c613</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[document-classification]]></category>
            <category><![CDATA[nlp-tutorial]]></category>
            <category><![CDATA[text-classification]]></category>
            <dc:creator><![CDATA[Susan Li]]></dc:creator>
            <pubDate>Sun, 02 Aug 2020 20:00:14 GMT</pubDate>
            <atom:updated>2020-08-02T21:33:21.006Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vO75HqnqS4bz_hJqBmLEtA.jpeg" /><figcaption>Photo credit: Pexels</figcaption></figure><h4>Natural Language Processing, NLP, Hugging Face</h4><p>Most of the researchers submit their research papers to academic conference because its a faster way of making the results available. Finding and selecting a suitable conference has always been challenging especially for young researchers.</p><p>However, based on the previous conferences proceeding data, the researchers can increase their chances of paper acceptance and publication. We will try to solve this text classification problem with deep learning using <a href="https://huggingface.co/transformers/model_doc/bert.html">BERT</a>.</p><p>Almost all the code were taken from this <a href="https://www.coursera.org/projects/sentiment-analysis-bert">tutorial</a>, the only difference is the data.</p><h3>The Data</h3><p>The <a href="https://raw.githubusercontent.com/susanli2016/NLP-with-Python/master/data/title_conference.csv">dataset</a> contains 2,507 research paper titles, and have been manually classified into 5 categories (i.e. conferences) that can be downloaded from <a href="https://raw.githubusercontent.com/susanli2016/NLP-with-Python/master/data/title_conference.csv">here</a>.</p><h4>Explore and Preprocess</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e29f7b0806b468ee27ff3b17b72e658/href">https://medium.com/media/8e29f7b0806b468ee27ff3b17b72e658/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*hTqhwvVGJtl-z8FZ7PFCPA.png" /><figcaption>Table 1</figcaption></figure><pre>df[&#39;Conference&#39;].value_counts()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*BKjZItVJH0E3KZgS-ZQqRg.png" /><figcaption>Figure 1</figcaption></figure><p>You may have noticed that our classes are imbalanced, and we will address this later on.</p><h4>Encoding the Labels</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72dc47d6d6045a64b995d62d2378c539/href">https://medium.com/media/72dc47d6d6045a64b995d62d2378c539/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*focrY1e8cFIvGCh_w9kqGw.png" /></figure><pre>df[&#39;label&#39;] = df.Conference.replace(label_dict)</pre><h3>Train and Validation Split</h3><p>Because the labels are imbalanced, we split the data set in a stratified fashion, using this as the class labels.</p><p>Our labels distribution will look like this after the split.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e2ba738ec0fe288be1832a724b8e380/href">https://medium.com/media/8e2ba738ec0fe288be1832a724b8e380/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*G9GE1COQ4aKTlTB2zera6A.png" /><figcaption>Figure 2</figcaption></figure><h3>BertTokenizer and Encoding the Data</h3><p><a href="https://huggingface.co/transformers/main_classes/tokenizer.html">Tokenization</a> is a process to take raw texts and split into tokens, which are numeric data to represent words.</p><ul><li>Constructs a <a href="https://huggingface.co/transformers/model_doc/bert.html#berttokenizer">BERT tokenizer</a>. Based on WordPiece.</li><li>Instantiate a pre-trained BERT model configuration to encode our data.</li><li>To convert all the titles from text into encoded form, we use a function called batch_encode_plus , and we will proceed train and validation data separately.</li><li>The 1st parameter inside the above function is the title text.</li><li>add_special_tokens=True means the sequences will be encoded with the special tokens relative to their model.</li><li>When batching sequences together, we set return_attention_mask=True, so it will return the attention mask according to the specific tokenizer defined by the max_length attribute.</li><li>We also want to pad all the titles to certain maximum length.</li><li>We actually do not need to set max_length=256, but just to play it safe.</li><li>return_tensors=&#39;pt&#39; to return PyTorch.</li><li>And then we need to split the data into input_ids, attention_masks and labels.</li><li>Finally, after we get encoded data set, we can create training data and validation data.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/033f47127bc3af3752ac101fe17bdb8c/href">https://medium.com/media/033f47127bc3af3752ac101fe17bdb8c/href</a></iframe><h3>BERT Pre-trained Model</h3><p>We are treating each title as its unique sequence, so one sequence will be classified to one of the five labels (i.e. conferences).</p><ul><li>bert-base-uncased is a smaller pre-trained model.</li><li>Using num_labels to indicate the number of output labels.</li><li>We don’t really care about output_attentions.</li><li>We also don’t need output_hidden_states.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d195caf803b4ebbf1032b6ab0ccd675/href">https://medium.com/media/6d195caf803b4ebbf1032b6ab0ccd675/href</a></iframe><h3>Data Loaders</h3><ul><li>DataLoader combines a dataset and a sampler, and provides an iterable over the given dataset.</li><li>We use RandomSampler for training and SequentialSampler for validation.</li><li>Given the limited memory in my environment, I set batch_size=3.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e11251dbe1cbdfd9fbfd00e4d1ca7e1/href">https://medium.com/media/7e11251dbe1cbdfd9fbfd00e4d1ca7e1/href</a></iframe><h3>Optimizer &amp; Scheduler</h3><ul><li>To construct an optimizer, we have to give it an iterable containing the parameters to optimize. Then, we can specify optimizer-specific options such as the learning rate, epsilon, etc.</li><li>I found epochs=5 works well for this data set.</li><li>Create a schedule with a learning rate that decreases linearly from the initial learning rate set in the optimizer to 0, after a warmup period during which it increases linearly from 0 to the initial learning rate set in the optimizer.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f350587c336156b4614c35897aa2cad6/href">https://medium.com/media/f350587c336156b4614c35897aa2cad6/href</a></iframe><h3>Performance Metrics</h3><p>We will use f1 score and accuracy per class as performance metrics.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e7e3224cc763e87c789525514171014/href">https://medium.com/media/3e7e3224cc763e87c789525514171014/href</a></iframe><h3>Training Loop</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e67305726aec6f74fcfc2bc35063e16b/href">https://medium.com/media/e67305726aec6f74fcfc2bc35063e16b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*8unFwxDZTMgpPUUDH4XbPA.png" /><figcaption>Figure 3</figcaption></figure><h3>Loading and Evaluating the Model</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/10d00c20b2c972088e761f75162a827f/href">https://medium.com/media/10d00c20b2c972088e761f75162a827f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*r_aRhmjPGW_cz_yiPdE-dw.png" /><figcaption>Figure 4</figcaption></figure><p><a href="https://github.com/susanli2016/NLP-with-Python/blob/master/Text_Classification_With_BERT.ipynb">Jupyter notebook</a> can be found on <a href="https://github.com/susanli2016/NLP-with-Python/blob/master/Text_Classification_With_BERT.ipynb">Github</a>. Enjoy the rest of the weekend!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b59ca2f5c613" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/multi-class-text-classification-with-deep-learning-using-bert-b59ca2f5c613">Multi Class Text Classification With Deep Learning Using BERT</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[COVID Fake News Detection with a Very Simple Logistic Regression]]></title>
            <link>https://medium.com/data-science/covid-fake-news-detection-with-a-very-simple-logistic-regression-34c63502e33b?source=rss-731d8566944a------2</link>
            <guid isPermaLink="false">https://medium.com/p/34c63502e33b</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[covid19]]></category>
            <category><![CDATA[nlp-tutorial]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[fake-news]]></category>
            <dc:creator><![CDATA[Susan Li]]></dc:creator>
            <pubDate>Wed, 22 Jul 2020 01:44:11 GMT</pubDate>
            <atom:updated>2020-07-22T02:52:52.328Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i_QAGFBqlu2SN6rRsr6msw.png" /><figcaption>Photo credit: Unsplash</figcaption></figure><h4>Natural Language Processing, NLP, Scikit Learn</h4><p>This time, we are going to create a simple logistic regression model to classify COVID news to either true or fake, using the <a href="https://raw.githubusercontent.com/susanli2016/NLP-with-Python/master/data/corona_fake.csv">data</a> I collected a while ago.</p><p>The process is surprisingly simple and easy. We will clean and pre-process the text data, perform feature extraction using <a href="https://www.nltk.org/">NLTK</a> library, build and deploy a logistic regression classifier using <a href="https://scikit-learn.org/stable/">Scikit-Learn</a> library, and evaluate the model’s accuracy at the end.</p><h3>The Data</h3><p>The <a href="https://raw.githubusercontent.com/susanli2016/NLP-with-Python/master/data/corona_fake.csv">data set</a> contains 586 true news and 578 fake news, almost 50/50 split. Because the data collection bias, I decided not to use “source” as one of the features, instead, I will combine “title” and “text” into one feature “title_text”.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c85ee758d652c8ffbe89eff6c48cf35/href">https://medium.com/media/6c85ee758d652c8ffbe89eff6c48cf35/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*AMTQiBJod-KU2OPZT-e_iQ.png" /></figure><h3>Pre-processing</h3><p>Let’s have a look an example of the title text combination:</p><pre>df[&#39;title_text&#39;][50]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QQvnr-cYtL0N7L8wdZuy8A.png" /></figure><p>Looking at the above example of title and text, they are pretty clean, a simple text pre-processing would do the job. So, we will strip off any html tags, punctuation, and make them lower case.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2efe0058f29f5c4c0495dd3decce3ba1/href">https://medium.com/media/2efe0058f29f5c4c0495dd3decce3ba1/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WV5Lg23dFDOlnLR_O56toA.png" /></figure><p>The following code combines tokenization and stemming techniques together, and then apply the techniques on “title_text” later.</p><pre>porter = PorterStemmer()</pre><pre>def tokenizer_porter(text):<br>    return [porter.stem(word) for word in text.split()]</pre><h3>TF-IDF</h3><p>Here we transform “title_text” feature into TF-IDF vectors.</p><ul><li>Because we have already convert “title_text” to lowercase earlier, here we set lowercase=False.</li><li>Because we have taken care of and applied preprocessing on “title_text”, here we set preprocessor=None.</li><li>We override the string tokenization step with our combination of tokenization and stemming we defined earlier.</li><li>Set use_idf=True to enable inverse-document-frequency reweighting.</li><li>Set smooth_idf=True to avoid zero divisions.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee2a69d2808aa027c70c36438b85ee14/href">https://medium.com/media/ee2a69d2808aa027c70c36438b85ee14/href</a></iframe><h3>Logistic Regression for Document Classification</h3><ul><li>Instead of tuning C parameter manually, we can use an estimator which is LogisticRegressionCV.</li><li>We specify the number of cross validation folds cv=5 to tune this hyperparameter.</li><li>The measurement of the model is the accuracy of the classification.</li><li>By setting n_jobs=-1, we dedicate all the CPU cores to solve the problem.</li><li>We maximize the number of iterations of the optimization algorithm.</li><li>We use pickle to save the model.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9aa75e386e65beef580bdd3c345af124/href">https://medium.com/media/9aa75e386e65beef580bdd3c345af124/href</a></iframe><h3>Model Evaluation</h3><ul><li>Use pickle to load our saved model.</li><li>Use the model to look at the accuracy score on the data it has never seen before.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4390a92c56e2252907a68a22a035f608/href">https://medium.com/media/4390a92c56e2252907a68a22a035f608/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/1*bIlrvWFWPPlSb9rEmXlVSQ.png" /></figure><p><a href="https://github.com/susanli2016/NLP-with-Python/blob/master/Fake_News_LogReg.ipynb">Jupyter notebook</a> can be found on <a href="https://github.com/susanli2016/NLP-with-Python/blob/master/Fake_News_LogReg.ipynb">Github</a>. Enjoy the rest of the week.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34c63502e33b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/covid-fake-news-detection-with-a-very-simple-logistic-regression-34c63502e33b">COVID Fake News Detection with a Very Simple Logistic Regression</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>