<?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 Irene Chang on Medium]]></title>
        <description><![CDATA[Stories by Irene Chang on Medium]]></description>
        <link>https://medium.com/@irenechang1510?source=rss-6d381bb66361------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Irene Chang on Medium</title>
            <link>https://medium.com/@irenechang1510?source=rss-6d381bb66361------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 04:38:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@irenechang1510/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[Now, why should we care about Recommendation Systems…? ft. A soft introduction to Thompson Sampling]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/data-science/now-why-should-we-care-about-recommendation-systems-ft-a-soft-introduction-to-thompson-sampling-b9483b43f262?source=rss-6d381bb66361------2"><img src="https://cdn-images-1.medium.com/max/2600/0*vTMF9sSQpwa5HZF2" width="5541"></a></p><p class="medium-feed-snippet">An ongoing Recommendation System series</p><p class="medium-feed-link"><a href="https://medium.com/data-science/now-why-should-we-care-about-recommendation-systems-ft-a-soft-introduction-to-thompson-sampling-b9483b43f262?source=rss-6d381bb66361------2">Continue reading on TDS Archive »</a></p></div>]]></description>
            <link>https://medium.com/data-science/now-why-should-we-care-about-recommendation-systems-ft-a-soft-introduction-to-thompson-sampling-b9483b43f262?source=rss-6d381bb66361------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9483b43f262</guid>
            <category><![CDATA[bayesian-statistics]]></category>
            <category><![CDATA[thompson-sampling]]></category>
            <category><![CDATA[recommendations]]></category>
            <category><![CDATA[editors-pick]]></category>
            <category><![CDATA[bayesian-machine-learning]]></category>
            <dc:creator><![CDATA[Irene Chang]]></dc:creator>
            <pubDate>Tue, 07 Nov 2023 16:31:30 GMT</pubDate>
            <atom:updated>2023-11-09T15:13:09.826Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[SQL to SARIMAX: How I navigate the first time-series analysis personal project for my portfolio]]></title>
            <link>https://medium.com/data-science/sql-to-sarimax-how-i-navigate-the-first-time-series-analysis-personal-project-for-my-portfolio-1ed24cba2c52?source=rss-6d381bb66361------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ed24cba2c52</guid>
            <category><![CDATA[personal-project]]></category>
            <category><![CDATA[deep-dives]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[eda]]></category>
            <dc:creator><![CDATA[Irene Chang]]></dc:creator>
            <pubDate>Wed, 06 Apr 2022 22:37:33 GMT</pubDate>
            <atom:updated>2022-04-06T22:37:33.431Z</atom:updated>
            <content:encoded><![CDATA[<h4>Including the resources I used to learn time-series as I was doing this project (MySQL, ARIMA orders selection, parallelization in Jupyter Notebook, etc)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6CuN2zDFni6PWO48" /><figcaption>Photo by <a href="https://unsplash.com/@wonderlane?utm_source=medium&amp;utm_medium=referral">Wonderlane</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Brainstorming</h3><p>My process of creating a personal project often starts with knowing what type of skills or knowledge I want to learn or improve upon. For this project, I had two goals in mind: (1) to learn time-series analysis and (2) to practice applying SQL skills to real life projects.</p><p>I found a dataset from <a href="https://www.kaggle.com/c/store-sales-time-series-forecasting/overview/description">Kaggle</a> Knowledge that is suitable for this project, which includes information about sales of an Ecuadorian-based grocery retailer. I took a quick look at the problem and some of the notebooks that have been published, most of which solved the problem of predicting sales from all the variables in this dataset. Taking an even closer look at the variables in the dataset, a question was raised in my head that have not been addressed much in the contributors of this challenge: Are the promotions effective in increasing sales? This knowledge would be beneficial to this store chain in that it helps understand how promotions are reacted to differently in across the products and locations, so that marketing strategies can be adjusted accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i_i05bxqrQHx0YNm" /><figcaption>Photo by <a href="https://unsplash.com/@belart84?utm_source=medium&amp;utm_medium=referral">Artem Beliaikin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Starting out with EDA and SQL</h3><p>As suggested above, I utilized SQL for the major part of this process since in this way I wouldn’t have to reload multiple big tables and store them throughout my analysis. Instead, I created and stored my tables in MySQL server and only queried the relevant subset of data that I wanted to visualize or investigate further. As to how to set this up, you can refer to my script <a href="https://github.com/irenechang1510/sales-analysis/blob/main/mysql_connection.ipynb">here</a>:</p><p>From here, I proceeded to carry out my EDA using the Python-SQL connection. Here is an example of using this to examine the relationship between sales and the locations of the stores:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a60af1989217c7eee6715ce8c4e50519/href">https://medium.com/media/a60af1989217c7eee6715ce8c4e50519/href</a></iframe><p>The result is a nicely organized dataset from which we can filter and visualize the data in various way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*as4Krm9A0x7s528HbWQf2Q.png" /><figcaption>Image by Author</figcaption></figure><p>Overall, I put more emphasis on the story-telling aspect as I was doing EDA on this dataset than I ever did before. Most of my analysis in the past did not have a clear direction, nor did I have a good reason behind my selections of variables. In short, it&#39;s more of looking for that “interesting insight&quot; needle in a haystack than having clear goals for my analysis. This time, I took a different approach, taking advices from <a href="https://medium.com/u/e49ad09c9fd1">Chaya Bakshi</a>, to come up with a coherent outline for the “narration” I wanted to craft (and my potential audience wanted to hear) through my data. This includes establishing the related hypotheses and questions ahead of diving straight into the Jupyter notebook, choosing the relevant subsets of features and visualization that will support the claims you are making, and condensing key takeaways and implications of your findings in the context of the problems. This story-centered way of thinking has benefited my understanding of how a new dataset should be approached and a better EDA can be conducted, and I encourage you to keep in mind your own narrative as you are doing your EDA as well. My full writeup can be accessed <a href="https://docs.google.com/document/d/17K_Orm-841ehCpNxM86i9xVOcd3ARoUdNV-BwFXaDFY/edit">here</a>, and the <a href="https://github.com/irenechang1510/sales-analysis/blob/main/promotion_analysis.md">here</a> is the link to the notebook (section 1 — 4).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Wc7x3Cw1sX6ERkKy" /><figcaption>Photo by <a href="https://unsplash.com/@chrisliverani?utm_source=medium&amp;utm_medium=referral">Chris Liverani</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Time-series analysis for promotion</h3><p>The last piece of EDA, promotion, requires some additional model building steps. I have converted the discrete target variable — onpromotion — into a binary variable, since my goal is to compare across two groups: promotion vs no promotion. From this, as a beginner in time-series, I wasn&#39;t sure what models or packages to use starting out. Later on in the project, I realized pmdarima is an incredibly helpful tool for this specific task, but at the time, I didn&#39;t know how it was applicable to my work, or if I even needed ARIMA (This <a href="https://otexts.com/fpp2/arima.html">e-book</a> contains great descriptions of ARIMA and other key time-series knowledge). Therefore, I narrowed my scope of analysis down to a more granular level and tried to find a right model for it first. The subset of data I selected includes daily sales information for Grocery I products from store number 1 in the city of Quito. The initial visualizations showed a potential significant difference between the two groups, the relationship we are mining.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*aMPxeiZ5SUwUh2Jue7t_7w.png" /><figcaption>Image by Author</figcaption></figure><h4>2.1 Finding the right model</h4><p>In a non time-series problem, a solution could be to use two-sample t-test to see if there is any significant difference in sales. However, an assumption in this type of statistical test is the independence among the data points, which time series data normally fails to achieve, unless the series is stationary (read more <a href="https://stats.stackexchange.com/questions/19715/why-does-a-time-series-have-to-be-stationary">here</a>). I was stuck on finding an alternative for this until I stumbled upon <a href="https://stats.stackexchange.com/questions/118425/using-2-sample-t-test-in-time-series-data">this</a> discussion: what I need is a type of ARIMA model that incorporates an <strong><em>exogenous</em></strong> variable, which in my case, is the binary onpromotion feature.</p><p>In determining the appropriate ARIMA model, I found this <a href="https://towardsdatascience.com/the-complete-guide-to-time-series-analysis-and-forecasting-70d476bfe775">article</a> extremely helpful. For the purpose of learning, I began with choosing the orders of the model in a manual way. Here are some of the main lessons I learned from this:</p><ul><li>To obtain a general sense of the <strong>trend</strong> and <strong>seasonality </strong>of the time series, I used a popular function from statsmodel called seasonal_decompose, along with plot_acf and plot_pacf to visualize the data. Here, for example, the seasonal component and the ACF, PACF plots suggest a very obvious pattern that appears to be a weekly cycle. We definitely need a <strong>Seasonal ARIMA</strong>–with the exogenous variable (<strong>SARIMAX</strong>)–in this case.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*v5cikwmPJzpl6HOX6xl8SA.png" /><figcaption>Image by Author</figcaption></figure><ul><li>Then comes a more technical in-depth look at the data. For <strong><em>Stationarity</em></strong>, this <a href="https://towardsdatascience.com/when-a-time-series-only-quacks-like-a-duck-10de9e165e">article</a> from Heiko provides a very thorough process of checking stationarity that involves using both KPSS and adfuller tests (2 most common tests for stationarity). The rule is to difference if either test says the series is not stationary. To achieve stationarity, we can use function <strong>ndiffs()</strong> from the library pmdarima to help determine the order of difference and use the <strong>max </strong>suggested order from the two tests to take the corresponding difference. <em>Note</em>: If the resulting ACF/PACF plot after differencing plunges to large negative values (like mine below), it&#39;s likely that we over-differenced, and we should revert to a lower differencing order, or not do it altogether.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*sa9gs-08H7gcPEz72cWmOg.png" /><figcaption>Image by Author</figcaption></figure><ul><li>For <strong><em>Seasonality</em></strong>, order of differencing is largely based on ACF/PACF plots. Looking at the example above, ACF and PACF plots have pikes every 7 or 8 lags, suggesting a seasonal order of 7 (weekly pattern). Pandas&#39;s autocorrelation_plot() function can be used to check if the differenced series has successfully removed the seasonality. If the pattern in the plot shows small and decreasing fluctuation around the 0 line, you are good to go (it means the seasonal pattern is fading away quickly over time).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*yBfdQAIkpm-S8lHPxtj0Tw.png" /><figcaption>Image by Author</figcaption></figure><ul><li>On to the most important part of selecting the orders of the terms for this time-series model! This nicely listed <a href="https://people.duke.edu/~rnau/arimrule.htm">set of rules </a>from Duke University is a great reference to determine the order of SARIMA and learn more about the meanings behind each of the terms involved in the model.</li></ul><p>After choosing the orders, I started building the SARIMAX model using the statsmodel package and examining the summary:</p><pre>from statsmodels.tsa.statespace.sarimax import SARIMAX</pre><pre># fitting the model<br>model = SARIMAX(continuous_date.sales, exog=continuous_date.bool_promotion, order=(1,0,2), seasonal_order=(1,1,1,7), enforce_invertibility=False, enforce_stationarity=False).fit(max_iter=50, method=&#39;powell&#39;)</pre><pre># model summary<br>print(model.summary())</pre><p>The diagnostics plot for this particular model shows a decently good fit . When being used for prediction, it followed the real trend closely. And since our focus is on the estimates/coefficients of the bool_promotion variable, I considered this model good enough to be used in our analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*bCmU_ZHxI63lX9ljoQ0AbQ.png" /><figcaption>The model&#39;s summary—Image by Author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*5Hxu0fXf8jtzbe755MUVCg.png" /><figcaption>Diagnostics plots—Image by Author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*26GZPWR3nxmozaUaYBgseQ.png" /><figcaption>Predictions—Image for Author</figcaption></figure><p>As we can see from the model summary, our bool_promotion variable is significant, meaning it&#39;s showed to affect sales of grocery I at store 1, and in this case, positively. Having promotions added more than 500 units to the sales for this given combination.</p><h4>Automate the process for other combinations</h4><p>Having figured out the pipeline throughout these steps, I automated this process for other store-city-product combinations with auto_arima(), which helps us identify the best fit set of orders, record these orders, as well as coefficients. First, I created a helper function to identify the necessary parameters and train the auto_arima().</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8de2f63ccda44a96996184ceec66bc1d/href">https://medium.com/media/8de2f63ccda44a96996184ceec66bc1d/href</a></iframe><p>One parameter that appeared tricky to me was parameter m, which is the period for <a href="https://robjhyndman.com/hyndsight/seasonal-periods/">seasonal differencing</a>. I (fortunately!) found a function that helped me estimate this parameter, Fast Fourier Transform Seasonality detector (read the doc <a href="https://facebookresearch.github.io/Kats/api/kats.detectors.seasonality.html">here</a>). It gives back one or several values that are the likely seasonal period values. I limited the value of m to be no more than 30 (monthly pattern) since it significantly reduced training time and since I only used the data of the last year and a half (more recent data), any seasonal periods that were in the hundreds (equivalent to only 2–3 cycles in the dataset) could be considered non-seasonal (the pattern was not strong enough).</p><p>In order to go through 1597 combinations available in the dataset, I made a parallelization script that significantly accelerated the whole training process. The script does several things: (1) It wrote the state of the training to progress.txt every iteration, which includes the orders of the best SARIMAX models fitted on the data of each combination; (2) Keep track of the models in which promotions have a statistically significant impact on sales; (3) Write all “significant” combinations to a result file for future reproduction purpose.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8880c77100199e9bee5a54e7fd94ebb/href">https://medium.com/media/b8880c77100199e9bee5a54e7fd94ebb/href</a></iframe><p><em>Note: Pool method from multiprocessing package will help you do the same tasks on multiple processors at the same time. By using apply_async, each of the SARIMAX models is trained and written to a file on finishing. The tasks are queued continuously, so they wouldn&#39;t wait for each other to start, which speed up the whole process significantly.</em></p><h4>Analyze the results</h4><p>With the model at hand, I could analyze the result in multiple ways. First, I chose to analyze the significant models and how they were distributed across the locations. I examined the count and the proportion of significant combinations out of all combinations in different regions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*pfWedgA71kRl0OiF0v-oGQ.png" /><figcaption>Count of significant combinations — Image by Author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*HALGWUJKAmRdJ9sMd-GK_g.png" /><figcaption>Proportion of significant combinations — Image by Author</figcaption></figure><p>Quito and Guayaquil are the cities that have the most significant combinations, due to the fact that they are the biggest cities in Ecuador. However, Playas, Manta, El Carmen are the cities that have the most effective promotions, with almost 80% of all of their promotions resulted in significant change in sales. Similarly, I also investigated the count and the proportion across the products (only 8 top and 8 bottom products).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*OPw3tMZGipCwt3I7-iykng.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*3m6qcpShW2JPRwa2hx1JDg.png" /></figure><p>With the presence of promotions, products like Beauty and Grocery I have a change in sales 100% of the times, while products like hardware and home appliances, baby care, etc witnessed this change for only 20% of the time. The products that reacted to promotions all the times include the products that are of great necessity, or products that people may be waiting for promotions to buy (favorites). And it is also found that these are all positive reactions (resulting in increased sales).</p><p>An analysis of the distribution of these coefficients showed that the majority of the coefficients are very positive, but there are 24 instances where having promotions decreases sales.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*GvRhRoUgykBY29iVmEuPVw.png" /><figcaption>Distribution of coefficients — Image by Author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*FC7q0hkYa80SYk_HyHQ8lw.png" /><figcaption>Cases where promotions decreased sales — Image by Author</figcaption></figure><p>A closer look at the cases with adverse reaction to promotions showed that they are mostly diary, meat and preprocessed products. This makes sense since promotions for these products can be for the purpose of clearing the inventory before expiration dates. As pointed out before, the fact that these products are close to their expiration dates explains why the sales go down overall. Conversely,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*ei05FqImyzxJ_mqdrV3jiA.png" /><figcaption>Cases where promotions increased sales — Image by Author</figcaption></figure><p>Grocery I, beverages and several produce products experience more than 5000 units increase in sales while being on promotions.</p><h4>Conclusion</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EnxOIckuENJAsDs3" /><figcaption>Photo by <a href="https://unsplash.com/@dirtjoy?utm_source=medium&amp;utm_medium=referral">Zoe Schaeffer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>More than 70% of the promotions have a positive effect on sales and the majority of them result in a good amount of boost in the units sold of certain products. How promotions affect sales differ by locations and by products. Some products score 100% on sales with the presence of promotions, while some experience a slight decrease. Some cities have more, but smaller-effect promotions and some cities have fewer but larger-effect promotions on sales. We can use this analysis to adjust the strategies for the upcoming promotions. Suggestions include: have more promotions in cities like Manta, Santa Domingo, Daule where both the quantity and quality of the effect of promotions are great; beverages and beauty products’ promotions can be used to boost sales in certain stores and cities like Riobamba where sales are usually lower.</p><p>And that wraps up my analysis, thank you so much for reading! The full markdown for this part can be found <a href="https://github.com/irenechang1510/sales-analysis/blob/main/promotion_analysis.md#4-analysis-of-the-results">here</a>. A next step could be to use these information in building a model that uses promotions and other variables to predict sales. Beyond that, I hope this is helpful for people who are starting out on their time series project. Feel free to leave any questions/feedback you have on my post through my <a href="https://www.linkedin.com/in/irene-chang-4356a013a/">LinkedIn</a>, happy to connect and respond to them!</p><h3>REFERENCES:</h3><p>MySQL documentation: <a href="https://dev.mysql.com/doc/">https://dev.mysql.com/doc/</a></p><p>Open source dataset on Kaggle Knowledge: <a href="https://www.kaggle.com/c/store-sales-time-series-forecasting/overview/description">https://www.kaggle.com/c/store-sales-time-series-forecasting/overview/description</a></p><ul><li><a href="https://people.duke.edu/~rnau/arimrule.htm">Rules for identifying ARIMA models</a></li><li><a href="https://towardsdatascience.com/the-complete-guide-to-time-series-analysis-and-forecasting-70d476bfe775">The Complete Guide to Time Series Analysis and Forecasting</a></li><li><a href="https://machinelearningmastery.com/arima-for-time-series-forecasting-with-python/">How to Create an ARIMA Model for Time Series Forecasting in Python - Machine Learning Mastery</a></li><li><a href="https://www.machinelearningplus.com/time-series/arima-model-time-series-forecasting-python/">ARIMA Model - Complete Guide to Time Series Forecasting in Python</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ed24cba2c52" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/sql-to-sarimax-how-i-navigate-the-first-time-series-analysis-personal-project-for-my-portfolio-1ed24cba2c52">SQL to SARIMAX: How I navigate the first time-series analysis personal project for my portfolio</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[Build a Flask-Heroku Mood Tracker Web App Using the Spotify API]]></title>
            <link>https://medium.com/data-science/build-a-flask-heroku-mood-tracker-web-app-using-the-spotify-api-14b3b5c92ac9?source=rss-6d381bb66361------2</link>
            <guid isPermaLink="false">https://medium.com/p/14b3b5c92ac9</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-dives]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[hands-on-tutorials]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Irene Chang]]></dc:creator>
            <pubDate>Tue, 09 Nov 2021 22:17:00 GMT</pubDate>
            <atom:updated>2023-11-10T14:20:01.961Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsdatascience.com/tagged/hands-on-tutorials">Hands-on Tutorials</a></h4><h4>A-Z project to generate mood scores based on the songs I listen to everyday and color my online mood tracker accordingly</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9e-O5bruClQjVVQh" /><figcaption>Photo by <a href="https://unsplash.com/@esteejanssens?utm_source=medium&amp;utm_medium=referral">Estée Janssens</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>Update April 2023: Heroku no longer provides free dyno, so my website currently cannot be loaded. However, the tutorial below still applies and should you decide to purchase a dyno plan yourself, you’ll see the result!</em></p><p><em>Here&#39;s a sneak peak of the </em><a href="https://mood-journaling.herokuapp.com/"><em>final result</em></a>!</p><p>Bullet journaling (or… bujo) is one of my main hobbies. Browsing through hundreds of Instagram bujo accounts, one thing that I most look forward to every month is the bujo artists&#39; mood tracker template. These colorful collages of moods laid the foundation of this project of mine. As I was designing next month’s mood tracker, the idea crossed my mind that it would be great to have a system that automatically detects our mood and helps us fill in the cells everyday.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MN9v3bVXmfAhTv6F" /><figcaption>Photo by <a href="https://unsplash.com/@thatsherbusiness?utm_source=medium&amp;utm_medium=referral">That&#39;s Her Business</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Ok, and… the data?</h4><p>Music has always been an important component of my everyday life. My music’s relationship with my mood is generally linear: I listen to upbeat songs when I’m happy, to ballad songs when I’m sad, to healing rhythms when I’m stressed out. Thus, I decided to use songs I listened to on Spotify, especially their provided attributes through API such as acousticness, danceability, etc as indicators of a song’s happiness level, and subsequently, my overall mood.</p><p>Having brainstormed a general project idea, I started to draft a checklist of the components of the pipelines, figuring out the order of which the tasks should be done and how I should tackle each of them. The below image is a documentation of my thought process and my development plan/progress for each stage:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ciEbv1VvKWB_6TMlJls8wA.jpeg" /><figcaption>The workflow that helped me keep track of my project progress — Image by Author</figcaption></figure><h3>Heroku</h3><p>Heroku is a cloud platform that offers free option for basic hosting of Webapp, so it’s suitable for a small-scale personal project. All we need is an account!</p><p>After signing up, navigate to your personal dashboard and hit ‘New’ to create a new app (my app is called mood-journaling). Go to your app and under ‘Deploy’, choose Heroku Git as your ‘Deployment method’ and follow the steps listed out underneath to clone your project (currently empty) to your local work environment. We&#39;re going to add files into this folder and push the changes afterwards. With that, let&#39;s get started on the project!</p><h3>Deciding on the model</h3><p>First thing first, I need a model to produce the said mood score based on my music list. Determining the appropriate model requires taking a step back to focus on what the final outcomes look like. I believe that good models come from focusing on your end goal; a more complex model doesn’t necessarily make the best solution to one’s question.</p><p><em>As mentioned above, my happiness level is defined by how happy a song sounds. Thus, I need an algorithm that assigns a higher score to songs that has a happier vibe, and a lower score otherwise. K-Means, a unsupervised method often used for song analysis, groups songs by their similarities, but it&#39;s not helpful for my task since I already have two categories in mind. A deep learning model for lyrics analysis was an option too, but sentences in songs are generally short, repetitive and have hidden meanings. Plus, lyrics is not the main factor determining when I listen to a song, the rhythm is.</em></p><p>Cycling through different options, I concluded that I could obtain the desired outcomes with a binary Logistic Regression model. If I fitted the model using two very distinctive lists, one with upbeat, happy songs, and one with ballad-y, melancholy melodies, then I could produce a probabilistic prediction of how close any given song was to being a happy song. This probability could be used as my <em>mood score.</em> Taking the median of all the mood scores for all the songs in a day, I would have the final score ready!</p><h3>Train the Logistic Regression model</h3><h4>From the training data…</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YpvOD4A-purEQtQz" /><figcaption>Photo by <a href="https://unsplash.com/@esteejanssens?utm_source=medium&amp;utm_medium=referral">Estée Janssens</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Special thanks to <a href="https://medium.com/u/e353ddb0c125">Sejal Dua</a>’s detailed <a href="https://towardsdatascience.com/k-means-clustering-and-pca-to-categorize-music-by-similar-audio-features-df09c93e8b64">guide</a> to scrape songs with Spotify API for making this task easier than ever! Sejal&#39;s program takes in a list of Spotify’s playlist IDs and return a dataframe of all the songs&#39; attributes, ready to be used to train the model. I fed into this function Spotify-made happy compilations (Mood Booster, Happy Beats, etc) and sad compilations (sad hour, Life sucks, etc)—those that contained very representative songs of the class. The full set amounted to around 1000 songs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e92af1ff488e89fcae3a8b513eb748e/href">https://medium.com/media/3e92af1ff488e89fcae3a8b513eb748e/href</a></iframe><p>I trained the model with cross validation, with which it achieved an accuracy score of 0.89! I also used <em>predict_proba</em> on a personal playlist containing both sad and happy songs, and the probabilistic estimations the model assigned to the songs reflected the happiness level of each of them pretty well. The model was then pickled for use in our application.</p><pre>import pickle</pre><pre>pickle.dump(lr, open(&quot;deploy_model.sav&quot;, &#39;wb&#39;))</pre><h4>…to the prediction</h4><p>In order to make predictions, I needed to get all the songs I listen to in a day. Out of all the functionalities offered with the Spotify API, <em>current_user_recently_played </em>is the closest function to producing the our target outcomes. However, it&#39;s limited to returning most recent 50 songs in one call. So I had to write a small program to scrape all the songs within the past 24 hours (illustration of how this works can also be found on my handwritten note).</p><p>Whenever I called this function, beside all the tracks, it also returned a <strong><em>cursor</em></strong>, which told me the timestamp of the 50th song I listened to (in milliseconds). For example, if I listened to 120 songs in the past 24 hours, then the 50th most recent song was, say, 5 hours ago. The idea was to get a batch of 50 songs at a time, extract this cursor, set the starting point to this cursor and start over to get the next 50 songs. The process stopped once the cursor of the batch I got exceeded the 24 hour mark. At that point, I would have to call a <em>get_right_limit()</em> function, which determined the number of songs I listened to since the last cursor that didn&#39;t go over the 24-hour mark. The code snippet is below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8bd492d705e0f526e1b0f78dbda887e/href">https://medium.com/media/d8bd492d705e0f526e1b0f78dbda887e/href</a></iframe><p>The get limit function is as followed:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05776c9efa60bf3de7471b31aeb185f4/href">https://medium.com/media/05776c9efa60bf3de7471b31aeb185f4/href</a></iframe><p>Once I got all the songs, the rest was to extract the features of these songs, just like how I did it in the previous section. After that, I loaded the pickled model with <em>pickle.load()</em>, and used <em>predict_proba</em> to produce the scores, which I would append to our dataframe as a column called “prediction”:</p><pre>mixed = get_features_for_playlist2(mixed, curr_time, curr_time - 86400000) # 86400000 is 1 day in millis</pre><pre>lr = pickle.load(open(&#39;models/deploy_model.sav&#39;, &#39;rb&#39;))</pre><pre>vnpred = lr.predict_proba(mixed.drop([&#39;name&#39;, &#39;artist&#39;,&#39;track_URI&#39;], axis=1))[:,1]</pre><pre>mixed.insert(3, &#39;prediction&#39;, vnpred)</pre><pre># take the median score<br>day_median = float(median(mixed[&#39;prediction&#39;]))</pre><h3>Storing the results</h3><p>I also needed a means of storage that would get updated when the above program was run, and from which the Flask app could easily retrieve and use the results. Here I used a SQL table. The code for storing and updating the results everyday is:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/226d4056fb41bb99dcc7f495474db85a/href">https://medium.com/media/226d4056fb41bb99dcc7f495474db85a/href</a></iframe><p>Worth noting that I had to create a table with 31 rows since the Flask app would retrieve all 31 values to look up the colors for the graph. All values in the table were initialized to 0. Whenever we turned to a new month, the table would be reset: all the old values would be clear and replaced with 0.</p><h3>On to Flask and Heroku!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ChcnGe3dnWHa6bd_" /><figcaption>Photo by <a href="https://unsplash.com/@esteejanssens?utm_source=medium&amp;utm_medium=referral">Estée Janssens</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Flask environment</h4><p>If you haven’t used Flask before, <a href="https://towardsdatascience.com/end-to-end-deployment-of-a-machine-learning-model-using-flask-dc456abcc6da#:~:text=Making%20a%20WebApp%20to%20deploy%20the%20model">here</a>’s a quick and helpful guide to install and get started! The list of all necessary files for our flask app can be found in my planner above.</p><p>Also in order to push your app to Heroku, I suggest using pipenv—a tool to create a virtual environment—since it does a good job locking all the necessary dependent libraries for your app (and cause me less trouble than using requirements.txt file!). In order to use it, use <em>pip install pipenv</em>, then type <em>pipenv shell</em> to activate the environment. In this environment, do <em>pipenv install [list of package_name]</em> to install the packages you need for your program. Finally, <em>pipenv lock</em> after you’ve done installations to lock all these requirements to your app. You’ll need to type this command again if you install any additional packages, before pushing the app to Heroku, otherwise the deployment will give you errors saying that there&#39;s no such modules.</p><h4>SQL &lt;-&gt; Flask (app.py)</h4><p>Now that I had the ready-made results stored in schema.sql, I went ahead to load it into my Flask app. In app.py, to easily extract the information from the table, I used a package called <a href="https://flask-sqlalchemy.palletsprojects.com/en/2.x/quickstart/">Flask-SQLAlchemy</a>. First of all, I had to <a href="https://flask-sqlalchemy.palletsprojects.com/en/2.x/config/">create the engine</a> and <a href="https://flask-sqlalchemy.palletsprojects.com/en/2.x/models/">declare the model</a> with the following syntax:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a18e9f30eefb68047dfe0a461de6936f/href">https://medium.com/media/a18e9f30eefb68047dfe0a461de6936f/href</a></iframe><h4>app.py &lt;-&gt; main.html &lt;-&gt; javascript</h4><p>The main.html file in “templates” folder is used by our Flask app to create the interface for the website. But in order to draw the figures and customize the colors, we need Javascript and CSS. Flask requires that we put .js and .css files in a different folder called static. I used Javascript&#39;s <a href="https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial">Canvas API</a> and the R<a href="https://github.com/anomal/RainbowVis-JS">ainbowVis</a> package to produce the drawings. This stage required a lot of trials and errors before arriving at the final products, but it was also the most interesting part. The <strong>RainbowVis</strong> package provides a tool to generate an array of HEX numbers representing a gradient of 1000 colors from Blue (=Sad) to Green (=Neutral) to Yellow (= Happy). The idea is to round the mood scores to 3 decimal places, multiply them by 1000, and get the HEX color at that index.</p><p>Therefore, I had to pass the scores from app.py to the html file to the javascript file. After a round of Googling, I came up with the solution:</p><ul><li>To <strong>pass the scores from app.py to main.html</strong>, I used Flask-SQLAlchemy functions to query the score, or the “results&quot; column, and passed it into html as an array through <em>render_template(). </em>I put this function under the default route since I wanted the drawings to be rendered right when we visit the front page.</li></ul><pre><a href="http://twitter.com/app">@app</a>.route(&#39;/&#39;, methods=[&#39;GET&#39;])<br>def main():<br>    table = Mood.query.with_entities(Mood.results).all()<br>    table = [r for r, in table]<br>    # table is currently storing the mood scores<br>    return render_template(&#39;main.html&#39;, results = table)</pre><ul><li>The scores are now stored in html in an array called results. To get the information in the array, we have to use the double curly braces. We can use <strong><em>console.log({{results}}) </em></strong>to confirm that the array is successfully passed in.</li><li>To <strong>pass the scores from main.html to canvas.js</strong>, I wrapped the codes in canvas.js in a function called <em>draw()</em>, which took in one argument: the array of values. Inside HTML, I called draw() and passed the table of mood scores in. The code is as followed. Note that the HTML file for Flask has slightly different syntaxes from a normal HTML file for including src and href.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d349b901bfdfa539c5a9a85138ea0ef/href">https://medium.com/media/3d349b901bfdfa539c5a9a85138ea0ef/href</a></iframe><ul><li>Now inside canvas.js, you can access the values in results with normal array indexing!</li></ul><p>At this point, we&#39;ve done setting up the links between different components in our app! If you type <strong><em>flask run</em></strong> we can see our application running on our localhost. What&#39;s left now, is to push it on Heroku, so that other people can see it!</p><h4>Flask &lt;-&gt; Heroku</h4><p>Following the next steps under Deploy, add, commit and push our files to Heroku (remember to pipenv lock before carrying out this step). Your terminal should show something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*JJ206FQIcYjaeURZsWoIHw.png" /></figure><p>And if you go to the URL, it should show the exact state as was seen on the Flask app hosted locally on your computer when you do <em>flask run. </em>Voila!</p><h4>Schedule to run everyday:</h4><p>The very final step is to automate the program so that it runs at the end of each day and update the graph accordingly. To do this, I wrote a <a href="https://ole.michelsen.dk/blog/schedule-jobs-with-crontab-on-mac-osx/">crontab</a> script which ran clock.py every night at 11:59pm to update the SQL table with a new score for that day, then re-pushed the whole project to Heroku.</p><p>Note that for crontab to work properly on macOS, you&#39;ll have to authorize its use of your local folders. Go to System Preferences -&gt; Security and Privacy -&gt; Full Disk Access. Click on the lock below to enable making changes. Click on the ‘+’ sign, then go to the path ‘/usr/sbin/cron’. Check the box for cron, hit the lock again to lock the changes. And we&#39;re all set.</p><p>Type <em>crontab -e </em>to start writing the crontab script:</p><pre>59 23 * * * cd /Users/irenechang/Desktop/PORTFOLIO/Fall2021/mood-journaling &amp;&amp; /opt/anaconda3/bin/python /Users/irenechang/Desktop/PORTFOLIO/Fall2021/mood-journaling/clock.py &amp;&amp; /usr/local/bin/git add /Users/irenechang/Desktop/PORTFOLIO/Fall2021/mood-journaling/. &amp;&amp; /usr/local/bin/git commit -m &quot;commits&quot; &amp;&amp; /usr/local/bin/git push heroku HEAD:master</pre><p>And Done! Our program is set off to update on a daily basis!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*fCm7X_uuQMdPpnvb31apNA.png" /><figcaption>Final result — Image by Author</figcaption></figure><h4>Conclusions:</h4><p>This was a fun and interesting idea-to-deployment ML project that I started out for the purpose of getting hands-on experience with Heroku and Flask, as well as familiarizing myself with working on an A-Z pipeline of a data science model. Hopefully you will enjoy the insights into your daily mood that this online bullet journal reveals as much as I do. Additionally, I hope this gives you a helpful guide for your own personal project, especially when it comes to deploying the model and figuring out the connections between multiple different elements.</p><p>Thank you very much for reading! My codes can be found in this <a href="https://github.com/irenechang1510/mood-journaling">repo</a>! Feel free to reach out to me for any further idea or feedback through my <a href="https://www.linkedin.com/in/irene-chang-4356a013a/">LinkedIn</a>, I would love to connect!</p><h3>References:</h3><ul><li><a href="https://towardsdatascience.com/k-means-clustering-and-pca-to-categorize-music-by-similar-audio-features-df09c93e8b64">K-Means Clustering and PCA to categorize music by similar audio features</a></li><li><a href="https://towardsdatascience.com/end-to-end-deployment-of-a-machine-learning-model-using-flask-dc456abcc6da">End to End Deployment of A Machine Learning Model using Flask</a></li><li><a href="https://towardsdatascience.com/pipenv-to-heroku-easy-app-deployment-1c60b0e50996">Pipenv to Heroku: Easy App Deployment</a></li></ul><ul><li><a href="https://python-adv-web-apps.readthedocs.io/en/latest/flask_db2.html">https://python-adv-web-apps.readthedocs.io/en/latest/flask_db2.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14b3b5c92ac9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/build-a-flask-heroku-mood-tracker-web-app-using-the-spotify-api-14b3b5c92ac9">Build a Flask-Heroku Mood Tracker Web App Using the Spotify API</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[The struggles and the tips: What I learn from doing my own classification project]]></title>
            <link>https://medium.com/data-science/the-struggles-and-the-tips-what-i-learn-from-doing-my-own-classification-project-dc1e70937b09?source=rss-6d381bb66361------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc1e70937b09</guid>
            <category><![CDATA[editors-pick]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[hands-on-tutorials]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Irene Chang]]></dc:creator>
            <pubDate>Thu, 26 Aug 2021 14:19:32 GMT</pubDate>
            <atom:updated>2021-08-30T19:27:43.025Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsdatascience.com/tagged/hands-on-tutorials">Hands-on Tutorials</a></h4><h4>Unlike the Iris dataset, once you start doing your first project on some unconventional dataset, 1001 problems emerge</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3ge-rwXsB_YcP34E" /><figcaption>Photo by <a href="https://unsplash.com/@octadan?utm_source=medium&amp;utm_medium=referral">Octavian Dan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>So it has come to the point that you are advised to “find your own dataset and produce some *interesting* analyses”. It’s even better if that dataset is somewhat less popular, or, the task is more ambiguous, less clearly defined, and there are not hundreds of available notebooks on Kaggle. From my (a probably a lot of people&#39;s) experience, such datasets are as messy as they can be, with missing entries, having too many/too few observations, and all the features being in their rawest form possible. My dataset is no difference, and having gotten over this first-project experience, I&#39;d love to share my process, as well as highlight some the issues with data I encountered along the way and how I handled them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*2m5blY080ftDF6shYKqMbg.png" /><figcaption>Snapshot of the dataframe I&#39;m working with</figcaption></figure><p>To start out, the dataset I was working on is about Indian cuisine from <a href="https://www.kaggle.com/nehaprabhavalkar/indian-food-101/code">Kaggle</a>, which has been used by many people for EDA task. It contains only around 250 observations (dishes), and 9 features. Despite getting such a small sample size, I decided to try and see if I can build a good machine learning model out of this dataset. Here goes the story, chronologically:</p><h3>“Defining problem” stage: The only 2 numerical variables!!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6NcsnUbOc8fFG3p4" /><figcaption>Photo by <a href="https://unsplash.com/@lunarts?utm_source=medium&amp;utm_medium=referral">Volodymyr Hryshchenko</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplas</a>h</figcaption></figure><p>The first question that interested me was predicting the cooking time from other variables, since I thought flavors could be too predictable—spicy dishes definitely have some specific ingredients, say; diet is, on the other hand, fairly simple because it is only binary (vegetarian vs non vegetarian); there are a wide range of dishes in each state and region so it doesn&#39;t make sense to have ingredients and flavors as indicators of the geography of these dishes; and lastly, knowing what course a dish belongs to is not super interesting nor helpful. Being able to predict cooking or preparation time is, however, can help we study the combinations of characteristics (ingredients, flavors, etc) that are not quite obvious that make a dish slow/quick to cook.</p><p>There are only 2 numerical variables in the dataset (preparation time and cooking time), and if cook time was set to be the target variables, preparation time would be the only continuous independent variable, which is not ideal for a regression task (I&#39;ve in fact tried it out and got a very big RMSE that was difficult to reduce).</p><p>To solve this problem, I converted it to a classification task by discretizing my target variable into 3 ranges: 1-quick (&lt;30 mins), 2-medium (30-60 mins), and 3-slow (&gt;1hr).</p><pre>&gt;&gt; bins = [0, 30, 60, 720]</pre><pre>&gt;&gt; group_names = [&#39;quick&#39;, &#39;medium&#39;, &#39;slow&#39;]</pre><pre>&gt;&gt; df_train[&#39;cook_time&#39;] = pd.cut(df_train[&#39;cook_time&#39;], bins, labels=group_names)</pre><h3>“Preprocessing data” stage 1: Missing values</h3><pre>&gt;&gt; df.isnull().mean().round(4)*100</pre><pre>name               0.00 <br>ingredients        0.00 <br>diet               0.00 <br>prep_time         11.76 <br>cook_time         10.98 <br>flavor_profile    11.37 <br>course             0.00 </pre><p>More than 10% of the observations contain at least one NA value. For such a small dataset, removing all these rows would leave very few data points for training a model, so it’s not an option here. Instead, I&#39;m going to impute the missing values of <em>prep_time</em> and <em>flavor_profile</em> using <em>impute</em> module from sklearn.<em> cook_time</em> should not be imputed since it&#39;s our target variable and thus it doesn&#39;t make sense to use other data to fill it in beforehand, so we have to remove all the missing values for this feature. We start off by imputing preparation time. Taking a look at the distribution of cooking and preparation time, we can see that they are both highly skewed to the right:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*RdTdBBbJiaicXyiSyFnX3Q.png" /><figcaption>Histograms of preparation and cooking time</figcaption></figure><p>Thus, it&#39;s most appropriate to use mode to replace missing values, rather than using median or mean. The code is followed:</p><pre>from sklearn.impute import SimpleImputer</pre><pre>imp = SimpleImputer(missing_values=np.nan, strategy=&#39;most_frequent&#39;)</pre><pre>df.dropna(subset=[&#39;cook_time&#39;], inplace=True)</pre><pre><em># fit transform the prep_time column </em><br>df[&#39;prep_time&#39;] = imp.fit_transform(df[&#39;prep_time&#39;].values.reshape(-1, 1))</pre><p>For flavor_profile, I&#39;m going to impute its missing values using k-nearest neighbors. For that reason, this has to be done after preprocessing all other columns, most of which in this case are currently strings in multiple formats, some of which are detailed below. The code for this part after preprocessing other features is:</p><pre>from sklearn.impute import KNNImputer<br>imputer = KNNImputer(n_neighbors=3)</pre><pre>df= imputer.fit_transform(df)</pre><h3>“Preprocessing data” stage 2: Ingredients column</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ts1d61Z3j_QEGZJc" /><figcaption>Photo by <a href="https://unsplash.com/@calumlewis?utm_source=medium&amp;utm_medium=referral">Calum Lewis</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>There are 2 ways I can engineer this feature: doing one hot encoding the most popular ingredients, or using raw TF-IDF scores for each ingredient. From experiment, the latter resulted in better accuracy scores than the former. For both methods, I employed <strong>TF-IDF score</strong> as a measure of how much one ingredient represents, characterizes the whole dish. (You can read more about TF-IDF <a href="https://monkeylearn.com/blog/what-is-tf-idf/">here</a>). The idea is that, the common ingredients such as salt, pepper, etc, might not be indicative of the cooking time of a dish, nor flavors for that matter because a large number of the dishes contain such ingredients. On the other hand, there might exist some combinations of ingredients that indicates that the dish is going to take long to cook, the pattern of which we are trying to mine.</p><p>I will summarize how I did both methods below:</p><h4>One hot encoding:</h4><p>This method is widely used as an example for building a movie recommendation algorithm where we encode the genres of each movie into this format:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*hzuRzN5fAf8uYbaC0dUqtw.png" /><figcaption>Movie genres—one hot encoded</figcaption></figure><p>I will be doing the same thing, but instead of one hot encoding all the ingredients, I choose only the most “tf-idf important” ingredients by cooking time only. First, I split the ingredients columns into 3 categories of cooking time:</p><pre>quick_dish = df[df[&#39;cook_time&#39;] == &quot;quick&quot;][&#39;ingredients&#39;]<br>medium_dish = df[df[&#39;cook_time&#39;] == &quot;medium&quot;][&#39;ingredients&#39;]<br>slow_dish = df[df[&#39;cook_time&#39;] == &quot;slow&quot;][&#39;ingredients&#39;]</pre><p>Then I turn each of them into a long document:</p><pre><strong>def</strong> one_doc(dishList):<br>    string = &#39;&#39;<br>    <strong>for</strong> dish <strong>in</strong> dishList:<br>        string = string + &quot; &quot; + dish<br>    <strong>return</strong> string<br><br>quick = one_doc(quick_dish)<br>medium = one_doc(medium_dish)<br>slow  = one_doc(slow_dish)</pre><p>The output of which looks like this:</p><pre>&#39; Maida flour, yogurt, oil, sugar Gram flour, ghee, sugar Flour, ghee, kewra, milk, clarified butter, sugar, almonds, pistachio, saffron, green cardamom Cashews, ghee, cardamom, sugar Milk, cottage cheese, sugar Yogurt, milk, nuts, sugar Refined flour, besan, ghee, powdered sugar, yoghurt, green cardamom Firm white pumpkin, sugar...</pre><p>Then I used TfidfVectorizer from sklearn to compute their TF-IDF scores:</p><pre>vectorizer = TfidfVectorizer()<br>vectors = vectorizer.fit_transform([quick, medium, slow])<br>feature_names = vectorizer.get_feature_names()<br>dense = vectors.todense()<br>denselist = dense.tolist()<br>pd.DataFrame(denselist, columns=feature_names)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*UqK47IMjv47q368COK7QIQ.png" /><figcaption>The resulting tfidf dataframe “dummies”</figcaption></figure><p>Then I extracted the “important&quot; ingredients of each cooking time type, which I arbitrarily defined here as the 60 highest scoring ingredients in each document, which will be 180 ingredients at most in total (accounting for duplicates), which is ideal because initially I don&#39;t want to have a lot more features than observations, but you can vary this number and see which threshold gives the highest accuracy.</p><pre>all_important_ingre = []<br><strong>for</strong> index, item <strong>in</strong> enumerate(denselist):<br>    scores = {feature: tfidf <strong>for</strong> feature, tfidf <strong>in</strong> <br>              zip(feature_names, item)}<br>    sorted_words = sorted(scores.items(), key=<strong>lambda</strong> x: x[1], <br>                          reverse=<strong>True</strong>)<br>    <strong>for</strong> word, score <strong>in</strong> sorted_words[:60]:<br>        all_important_ingre.append(word)<br><br>top_ingre = list(set(all_important_ingre))</pre><p>My all_important_ingre variable will now store all the distinct important ingredients, and we are ready to create a dummy encoded dataframe:</p><pre>zeros = np.zeros((len(df_train), len(top_ingre)))<br>dummies = pd.DataFrame(zeros, columns = top_ingre)</pre><pre>ingredients = df_train[&#39;ingredients&#39;]<br>sep_ingre = ingredients.apply(str.split, sep= &quot;, &quot;)<br><strong>for</strong> i, dish <strong>in</strong> enumerate(sep_ingre):<br>    dish = list(map(str.lower, dish))<br>    indices = dummies.columns.get_indexer(dish)<br>    dummies.iloc[i, indices] = 1<br>dummies</pre><pre><em># joining the original dataframe</em><br>df = df.join(dummies.add_prefix(&#39;ingre_&#39;))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*63ZCa_fTUSMZqBUyGgBcTA.png" /><figcaption>Part of the final table looks like this</figcaption></figure><p><strong>Reason why I think this method does not yield the best results</strong>: Apart from having hundreds of ingredients and way fewer observations, our data fail to cluster into distinct groups when visualized with PCA and t-SNE. It appears that indicating whether an ingredient is in a dish or not is not informative enough for the algorithm to learn and make decision since our dataframe is already consisted of all categorical variables except for <em>prep_time</em> (which is also why keeping the raw tf-idf scores—the 2nd strategy—helps the model perform better).</p><h4>Raw TFIDF scores</h4><p>For this method, I decided to keep all the ingredients because unlike merely binary indicating whether an ingredient is included in a dish or not, the raw tfidf scores already suggest if that ingredient is unimportant. In other words, in the previous method, ingredient X has score 1 on dish A, as well as on dish B if it’s in both dishes, making X in A the same as X in B; but in this method, X may be more indicative of the cooking time for dish A than of B, hence X&#39;s score at A is 0.6, while X&#39;s score at B might only be 0.1. The process of this task is similar to the previous method, but even simpler:</p><pre>vectorizer = TfidfVectorizer()<br>vectors = vectorizer.fit_transform(df_train[&#39;ingredients&#39;])<br>feature_names = vectorizer.get_feature_names()<br>dense = vectors.todense()<br>denselist = dense.tolist()<br>dummies = pd.DataFrame(denselist, columns=feature_names)<br>one_hot_encode_data = one_hot_encode_data.join(dummies.add_prefix(&#39;ingre_&#39;))</pre><p>That’s it!</p><p>I do suggest trying out both methods, unless your dataframe strongly suggests than one method will be better than the other based on the reasoning above. To connect briefly to the previous parts, this is where we move on to impute the missing value for <em>flavor_profile</em> using KNNImputer.</p><h3>“Model building” stage: some good practice</h3><p>These are things I didn&#39;t know prior to doing this project, but after learning about them, I save myself a lot of work!</p><ul><li>Use <a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.cross_val_score.html?highlight=cross%20val%20score#sklearn.model_selection.cross_val_score"><em>sklearn.model_selection.cross_val_score</em></a><em> </em>to perform <strong>cross-validation</strong> on your dataset easily. It returns a list of accuracy scores (or another metric of your choice) achieved on each fold. I use cross-validated scores (the mean and standard deviation of this list) in all my evaluations of the models. All my models (Logistic regression, Random forest, Multiple Bayes, SVM) improve by 10-20% when applied on the resampled dataset.</li></ul><pre><em># example</em><br>rf = RandomForestClassifier(random_state=0)<br>scores = cross_val_score(rf, X, y, scoring=&#39;accuracy&#39;, cv=4, n_jobs=-1)<br>print(&#39;Mean Accuracy: %.3f (%.3f)&#39; % (mean(scores), std(scores)))</pre><ul><li>For your <strong>baseline model</strong>, use <a href="https://scikit-learn.org/stable/modules/generated/sklearn.dummy.DummyClassifier.html?highlight=dummy%20classifier#sklearn.dummy.DummyClassifier"><em>sklearn.dummy.DummyClassifier</em></a><em>. </em>It classifies the data using simple rules such as using the most frequent class label, or generating predictions uniformly at random.</li></ul><pre>model = DummyClassifier(strategy=&#39;most_frequent&#39;)<br>scores = cross_val_score(model, X, y, scoring=&#39;accuracy&#39;, cv=4, n_jobs=-1)<br>print(&#39;Mean Accuracy: %.3f (%.3f)&#39; % (mean(scores), std(scores)))</pre><ul><li><strong>Do error analysis</strong>: Beside accuracy, we should also look into f1-score and recall rates. Initially, I only resampled class 3 (so after that, there are 131 examples of class 1 and 131 of class 3 but only 84 of class 2). Fitting the model on this dataset, I observed that the accuracy and precision rates across all 3 classes are very high. But the recall rate of class 2 is very bad. Further examination showed that a lot of class 2 examples were predicted to belong to class 1. It&#39;s this over-prediction behavior that led me to realize that class 2 was underrepresented compared to other classes. Fixing this by fixing the resampling method has improved the recall rate of class 2, resulting in a better, more consistent model in general. This is an example of how looking into the error your model makes can be extremely fruitful.</li></ul><p>Besides parameter tuning, feature engineering and feature selection are two processes that are indispensable to building a machine learning model. Feature engineering should always come before feature selection, which comes before parameter tuning. In <strong>feature engineering</strong>, I often think about the common tasks such as scaling/normalizing the features, creating new columns (the way we preprocess the ‘ingredients&#39; column is also feature engineering), as well as more context-specific tasks like dealing with imbalanced dataset as detailed below. For <strong>feature selection</strong>, I utilize the <em>feature_selection</em> module of sklearn, and <a href="https://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.SelectKBest.html">SelectKBes</a>t is one of my favorite techniques. I tried out ‘chi2’ and ‘mutual_info’ methods on 4 ML models I built, each with the 3 datasets I’ve had so far (the one “pre-feature engineering”, the one “post-feature engineering, pre-resampling”, and the resampled dataset). For each fit, I varied the number of features retained (parameter k) against the accuracy and picked the threshold that yielded the best results.</p><h3>“Feature engineering” stage: Imbalanced dataset</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ytl7kbWy9qHUhj3V" /><figcaption>Photo by <a href="https://unsplash.com/@saltsup?utm_source=medium&amp;utm_medium=referral">Piret Ilver</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>One thing that greatly improves my model&#39;s performance is having a balanced dataset among the 3 classes of cooking time. Currently, I have 131 dishes in the quick category, 84 in medium and only 12 in slow. <a href="https://imbalanced-learn.org/stable/references/index.html">Imbalanced learn</a> is a package built on scikit-learn that provides tools for handling imbalanced dataset such as resampling, computing balanced accuracy score, etc. Here I use an oversampling strategy called SMOTENC to over-sample class 2 and 3 so that they have the same observations as class 1. SMOTE is a common technique for oversampling; SMOTENC builds upon SMOTE, but can be used for a dataframe with both numerical and categorical features.</p><pre>X_resampled, y_resampled = SMOTENC(categorical_features=range(1, <br>11),random_state=0,sampling_strategy=&#39;minority&#39;).fit_resample(x_full2, y_full2)</pre><p>It&#39;s worth noting that while oversampling helps yield better results, it has some pitfalls, since it makes exact copies of the minority class examples. So if there&#39;s only 1 example in the minority class, we will have hundreds of its copies in the resampled dataframe. This is going to result in serious overfitting. It would normally be better to under-sample the majority class. However, since our dataset is very small, this is not a good strategy. As a matter of fact, my various models perform really well with class 3, but it is more confused with some examples of class 1 and 2.</p><h3>“Model tuning” stage: Stacking models</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OIvF4pg3cGPvzOvw" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I would usually stop after doing parameter tuning on some selected models, calling it a day. But when I came across <a href="https://www.dummies.com/programming/big-data/data-science/10-ways-improve-machine-learning-models/">this post</a> on improving ML model, I saw stacking models, a technique that I have not tried out before. Stacking is an efficient ensemble method in which the predictions, generated by using various machine learning algorithms, are used as inputs in a second-layer learning algorithm <a href="https://blogs.sas.com/content/subconsciousmusings/2017/05/18/stacked-ensemble-models-win-data-science-competitions/">[1]</a>. The way we build a Stacking Classifier is similar to how we make a pipeline, with all the best parameters we have achieved in previous tuning phases:</p><pre>models = [<br>(&#39;lr&#39;, LogisticRegression(C=2.976351441631316, max_iter=500) ),<br>(&#39;svm&#39;, SVC(random_state=0, C=6.158482110660261) ),<br>(&#39;rfc&#39;, RandomForestClassifier(n_estimators=130, random_state=0, max_depth=46))]</pre><pre>level1 = LogisticRegression()</pre><pre>stacking = StackingClassifier(estimators=models, final_estimator=level1, cv=5)<br></pre><p>After which, we will fit the model on the dataset that has gone through feature engineering and feature selection. It&#39;s observed that the k value that yields the best results on individual models (even if all the models have the same best k value) is not the best k value of the combined model. Thus we should also vary this threshold to see which k value performs best.</p><h3>Some closing remarks…</h3><p>At last, my best-performing model is a stacking model of random forest and SVM, using mutual_info feature selection technique, which reaches 81% cross-validated accuracy. I think it’s essential to make a lot of trials (and errors) with your dataset and your models. The more you test, the more certain you will obtain the best results. It&#39;s widely known that building a good ML model is a cycle of explorations and corrections, so be patient with it, break the task down do conquer it one stage at a time. I hope this post helps on your journey to building your own project, especially beginners. If you made it this far, thank you so much for reading, and good luck with your project!</p><p>A full version of this notebook can be found in this Github repo:</p><p><a href="https://github.com/irenechang1510/indian-cuisine-EDA">GitHub - irenechang1510/indian-cuisine-EDA: Carry out EDA and build model to predict whether cooking time is slow, quick, or medium</a></p><p>Feel free to reach out to me via my <a href="https://www.linkedin.com/in/irene-chang-4356a013a/">LinkedIn</a>, if you have any question, I would love to connect!</p><p>[1] Güneş, Funda. <em>Why do stacked ensemble models win data science competitions?</em> The SAS Data Science Blog, 2017. <a href="https://blogs.sas.com/content/subconsciousmusings/2017/05/18/stacked-ensemble-models-win-data-science-competitions/">https://blogs.sas.com/content/subconsciousmusings/2017/05/18/stacked-ensemble-models-win-data-science-competitions/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc1e70937b09" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/the-struggles-and-the-tips-what-i-learn-from-doing-my-own-classification-project-dc1e70937b09">The struggles and the tips: What I learn from doing my own classification project</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-19 Policies Multi-classification with Neural Network]]></title>
            <link>https://medium.com/data-science/covid-19-policies-multi-classification-with-neural-network-d85cbc0f90c0?source=rss-6d381bb66361------2</link>
            <guid isPermaLink="false">https://medium.com/p/d85cbc0f90c0</guid>
            <category><![CDATA[text-classification]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Irene Chang]]></dc:creator>
            <pubDate>Sat, 26 Jun 2021 04:40:46 GMT</pubDate>
            <atom:updated>2021-06-28T14:42:05.324Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>Documenting my learning curve for tuning an ML model that can categorize 20 classes (~ and even more in the future)</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*n73f9KYOR5oOEygD" /><figcaption>Photo by <a href="https://unsplash.com/@thenewmalcolm?utm_source=medium&amp;utm_medium=referral">Obi Onyeador</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>Little intro~</strong></h3><p>Before getting into the detail of the work, I want to spare some space to share a summary of the motivation behind this project as well as this article.</p><p>I have been having a great time at <a href="https://www.coronanet-project.org/about.html">Coronanet.org</a>, an amazing multinational team with more than 500 research assistants (RAs) working together to collect data on COVID-19 policies around the globe. Our end goal is to publish as many datasets on the policies in their most usable form as possible, which then can be used for different kinds of research/journalism work. One of many ways we organize collected data is to manually read through and classify them into one of the 20 different policy types (Social Distancing, Lockdown, etc, you name it) and other subtypes. The fact that many policies don&#39;t appear as clear that they belong to any specific policy types and the enormous daily amount of incoming data prove it difficult to double check every single policy for the labeling accuracy. This is where we get to experiment with different ML models in search of an algorithm that can identify miscoding and clean up these errors more effectively than manual work.</p><p>There has been, and will be, a lot of changes as the search for the optimal model continues. Thus, I want to document some personal progress I make, successes and limitations as I keep on learning and reaching for a better model in hope that I can make meaningful contributions, small or large, to the common goal of the team! So…</p><h3>Let’s get into it</h3><h4>Data collection</h4><p>I scraped the data from the public repo of our organization, which can be found <a href="https://github.com/CoronaNetDataScience/corona_tscs/tree/master/data/CoronaNet/data_country/coronanet_release">here</a>. I used s<em>elenium</em> to collect the datasets from some selected countries only (countries with many published records of policies). [Note: If you also use Chrome, you&#39;ll need to <a href="https://chromedriver.chromium.org/downloads">download <em>chromedriver</em></a><em> </em>first to your computer in order to run and open the browser.</p><pre>from selenium import webdriver</pre><pre>driver=webdriver.Chrome(&#39;/Users/irenechang/Downloads/chromedriver&#39;)<br>driver.get(&#39;<a href="https://github.com/CoronaNetDataScience/corona_tscs/tree/master/data/CoronaNet/data_country/coronanet_release&#39;">https://github.com/CoronaNetDataScience/corona_tscs/tree/master/data/CoronaNet/data_country/coronanet_release&#39;</a>)</pre><p>Since the dataset filenames have the same format, I&#39;m going to make a list for all the country names I want to scrape and parse them into this format.</p><pre><em>#showing only a few countries</em><br>country_names = [&#39;Germany&#39;, &#39;United States of America&#39;, &#39;Spain&#39;, &#39;Australia&#39;, &#39;India&#39;]<br>countries_to_scrape = []</pre><pre><em>#parse string together</em><br>for country in country_names:<br>    countries_to_scrape.append(&quot;coronanet_release_&quot; + country + &quot;.csv&quot;)</pre><p>Here comes the beauty of selenium that makes all the scraping enjoyable as you stand back at what the browser moves to pages on its own. We’re going to</p><p>(1) create xpath for each link →</p><p>(2) go into each link → navigate to the download button →click on it,</p><p>all automated with the following snippets of codes:</p><pre><em># get the link for each data file</em><br>urls = []<br>for country in countries_to_scrape:<br>    xPath = &quot;//a[<a href="http://twitter.com/title">@title</a>=&#39;&quot;+ country + &quot;&#39;]&quot;<br>    print(xPath)<br>    link = driver.find_element_by_xpath(xPath).get_attribute(&quot;href&quot;)<br>    urls.append(link)</pre><p>[Note: In case you haven’t used it before, XPath is a query language, just like SQL, but used on XML documents, aka the web ‘structure&#39; that can be viewed in ‘Developer Tools&#39;. Here, we want to extract the links (aka the <em>href</em> attribute) to the csv&#39;s of these countries, which can be found in &lt;a&gt; tags that happen to have the titles (<em>title</em> attribute) being the same as the text shown]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*ysFHkJwGdn6Pd_duFuSpOg.png" /><figcaption>The highlighted part is where we are navigate towards</figcaption></figure><pre>//a[@title=&#39;coronanet_release_Germany.csv&#39;]<br>//a[@title=&#39;coronanet_release_United States of America.csv&#39;]<br>//a[@title=&#39;coronanet_release_Spain.csv&#39;]<br>//a[@title=&#39;coronanet_release_Australia.csv&#39;]<br>//a[@title=&#39;coronanet_release_India.csv&#39;]</pre><p>☝️ is the result from the <em>print()</em>, these are our <em>xpaths</em>. Next, following similar processes, we move on to the second stage, getting the raw csv files, and concat all these dataframes.</p><pre>from parsel import Selector<br>csv_urls = []<br>for url in urls:<br>    driver.get(url)<br>    sel = Selector(text=driver.page_source)<br>    raw_csv = driver.find_element_by_id(&#39;raw-url&#39;).get_attribute(&quot;href&quot;)<br>    csv_urls.append(raw_csv)</pre><pre>dfs = []<br>for csv in csv_urls:<br>    # read each csv into a separate dataframe<br>    dfs.append(pd.read_csv(csv))</pre><pre>big_frame = pd.concat(dfs, ignore_index=True)</pre><h4>Data Preprocessing</h4><p>From big_frame, I’m only interested in 2 columns, “description” and “type”.</p><p>For the rest of the preprocessing steps, I followed closely Miguel&#39;s notebook, which can be found <a href="https://github.com/miguelfzafra/Latest-News-Classifier/blob/master/0.%20Latest%20News%20Classifier/03.%20Feature%20Engineering/03.%20Feature%20Engineering.ipynb">here</a>. His explanations at each step are very clear and helpful, especially for those who just started handling text data like me. Generally, the checklist should be:</p><ol><li>Special characters and punctuation</li><li>Lowering cases</li><li>Remove numbers</li><li>Stemming and lemmatization</li><li>Stopwords (country names, region names, and words that are used in formal documents and policies)</li><li>Label encodings</li><li>Train-test spilt</li></ol><p>Here is a snippet of my step 5:</p><pre>#stopwords<br>nltk.download(&#39;stopwords&#39;)<br>stop_words = list(stopwords.words(&#39;english&#39;))</pre><pre># include country names in stopwords<br>country_text = []<br>for text in df[&quot;description_1&quot;].tolist():<br>    for c in pycountry.countries:<br>        if c.name.lower() in text:<br>            text = re.sub(c.name.lower(), &#39;&#39;, text)<br>    country_text.append(text)</pre><pre>df[&quot;description_2&quot;] = country_text</pre><pre>for stop_word in stop_words:<br>    regex_stopword = r&quot;\b&quot; + stop_word + r&quot;\b&quot;     </pre><pre>    df[&#39;description_2&#39;] = df[&#39;description_2&#39;].str.replace(regex_stopword, &#39;&#39;)</pre><h4>Fit the model</h4><p>First of all, since the data is imbalanced, so we will calculate the class weights for later use in the neural network:</p><pre>from sklearn.utils import class_weight</pre><pre>class_weights = list(class_weight.compute_class_weight(&#39;balanced&#39;,                np.unique(df2[&#39;type&#39;]), f2[&#39;type&#39;]))</pre><pre>class_weights.sort()<br>class_weights</pre><pre><em># assign labels to these weights</em><br>weights = {}<br>for index, weight in enumerate(class_weights) :<br>    weights[index] = weight<br>    <br>weights</pre><p>Out:<br>{0: 0.3085932721712538,<br> 1: 0.4814408396946565,<br> 2: 0.49128529698149953,<br> 3: 0.6827469553450609,<br> 4: 0.6949724517906336,<br> 5: 0.7166903409090909,<br> 6: 0.7187321937321938,<br> 7: 0.8298519736842105,<br> 8: 1.0577568134171909,<br> 9: 1.1733720930232558,<br> 10: 1.3105194805194804,<br> 11: 1.4883480825958701,<br> 12: 1.7955516014234876,<br> 13: 2.156196581196581,<br> 14: 2.787569060773481,<br> 15: 2.9505847953216375,<br> 16: 3.1933544303797468,<br> 17: 3.2977124183006534,<br> 18: 10.091,<br> 19: 11.733720930232558}</p><p>Next, we transform our train and test sets into usable object form and print them out to take a look at:</p><pre>dataset_train = tf.data.Dataset.from_tensor_slices((X_train.values, y_train.values))<br>dataset_test = tf.data.Dataset.from_tensor_slices((X_test.values, y_test.values))</pre><pre>for text, target in dataset_train.take(5):<br>    print(&#39;Desc: {}, label: {}&#39;.format(text, target))</pre><p>Here is the result of the first 5 descriptions with their labels attached:</p><pre>Desc: b&#39; us embassy montevideo consular section  closed   routine consular services   notice    emergency situations   considered   time &#39;, label: b&#39;Restriction and Regulation of Government Services&#39;</pre><pre>Desc: b&#39; pennsylvania governor signed  senate bill    waives  requirement  schools    session  least  days  provides  continuity  education plans  ensures school employees  paid   closure   provides  secretary  education  authority  waive student teacher  standardized assessments   march  &#39;, label: b&#39;Closure and Regulation of Schools&#39;</pre><pre>Desc: b&quot;dumka   district   n state  jharkhand   defined  government services  would remain operational   lockdown   follows    law  order agencies -  function without  restrictions   officers attendance - compulsory  grade &#39;&#39;  &#39;b&#39; officers  reduced  %  grade &#39;c&#39;      district administration  treasury officials -   function  restricted staff    wildlife  forest officers -  function  taking necessary precautions &quot;, label: b&#39;Restriction and Regulation of Government Services&#39;</pre><pre>Desc: b&#39;texas     reopening  non-essential businesses starting may      per executive order ga-    hair salons  barber shops  nail salons   tanning salons must maintain mandatory ft distance  patrons    swimming pools  operate  % capacity     may   jail time  removed   enforcement mechanism  update   may   gov  abbott removed jail time   penalty  failing  follow covid- restrictions &#39;, label: b&#39;Restriction and Regulation of Businesses&#39;</pre><pre>Desc: b&#39; public safety curfew   imposed  mobile  alabama  effective   pm  april      remain  effect  april      persons shall remain   places  residence  shall    public places &#39;, label: b&#39;Lockdown&#39;</pre><p>Our next task is to one-hot encode the 20 labels. To do this, I created a hash table to conveniently look up the values by category codes:</p><pre>table = tf.lookup.StaticHashTable(<br>    initializer=tf.lookup.KeyValueTensorInitializer(<br>        keys=tf.constant(list(category_codes.keys())),<br>        values = tf.constant(list(category_codes.values()))<br>    ),<br>    default_value=tf.constant(-1),<br>    name=&quot;target_encoding&quot;<br>)</pre><pre><a href="http://twitter.com/tf">@tf</a>.function<br>def target(x):<br>    return table.lookup(x)</pre><p>Using these functions, we can encode the labels in our train and test sets into arrays of numbers. Print out the results with<em> next()</em></p><pre>def fetch(text, labels):<br>    return text, tf.one_hot(target(labels), 19)</pre><pre>train_data_fetch = dataset_train.map(fetch)<br>test_data_fetch = dataset_test.map(fetch)</pre><pre>next(iter(train_data_fetch))</pre><p>Output (The first tf.Tensor is our train data, and the second one is our transformed train labels):</p><pre>(&lt;tf.Tensor: shape=(), dtype=string, numpy=b&#39;   april   mha writes  states  ensure smooth harvesting  sowing operations   maintaining social distancing   -day lockdown  fight covid-  -  union ministry  home affairs  mha   sent  advisory   states regarding granting   exception  agricultural operations  lockdown restrictions  fight covid-  keeping  mind  harvesting  sowing season   -   advisory  exceptions   allowed  farming operations  farmers  farm workers  procurement  agricultural productions  operation  mandis  movement  harvesting  sowing related machinery  etc &#39;&gt;,<br> &lt;tf.Tensor: shape=(19,), dtype=float32, numpy=<br> array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0.,<br>        0., 0.], dtype=float32)&gt;)</pre><h4>Start creating a model</h4><p>First of all, we need to tokenize our text data before feeding it into our model. I used an already implemented model from Google that will create an embedding layer for us. Briefly, this is how it works:</p><blockquote>Google has developed an <strong>embedding</strong> model, <strong>nnlm</strong>-en-<strong>dim128</strong> which is a token-based <strong>text embedding</strong>-trained model that uses a three-hidden-layer feed-forward Neural-Net Language Model on the English Google News 200B corpus. This model maps any body of <strong>text</strong> into 128-dimensional <strong>embeddings — </strong>Dipanjan (DJ) Sarkar</blockquote><p>To use it, simply pass in the link to the model, which can be found on this <a href="https://tfhub.dev/google/nnlm-en-dim128/2">website</a> [Note: you might want to check to make sure the version you are using is the most up-to-date one, or else it will give you errors]:</p><pre>embedding = &quot;<a href="https://tfhub.dev/google/nnlm-en-dim128/2">https://tfhub.dev/google/nnlm-en-dim128/2</a>&quot;<br>hub_layer = hub.KerasLayer(embedding, output_shape=[128],input_shape=[], dtype=tf.string,<br>                          trainable=True)<br>hub_layer(train_data[:1])</pre><p>Sneak peak into what this layer gives us:</p><pre>&lt;tf.Tensor: shape=(1, 128), dtype=float32, numpy=<br>array([[ 1.85923278e-01,  3.82673025e-01,  8.69123638e-02,<br>        -2.36745372e-01, -1.19763926e-01, -5.65516986e-02,<br>         2.45870352e-01,  5.02816178e-02, -2.10541233e-01,<br>        -4.42932360e-02,  1.28366366e-01,  1.47269592e-01,<br>         1.41175740e-04,  4.45434526e-02,  2.13784329e-03,<br>         1.61750317e-01, -2.32903764e-01, -2.10702419e-01,<br>        -2.09106982e-01,  1.55449033e-01,  4.53584678e-02,<br>         4.31233309e-02,  1.48296393e-02, -1.68935359e-01,<br>         1.12579502e-01, -1.03304483e-01,  1.61703452e-01,<br>         2.13061482e-01, -4.74388264e-02,  1.27027377e-01,<br>        -3.04564610e-02, -1.92816645e-01, -3.22420187e-02, ... ]])</pre><p>Neural network model’s pitfall is overfitting, as always, therefore we usually have to use dropout layers to regularize it. Dropout layer is a tool to regularize neural network, in which a number of layer outputs at random are ignored so that the sparser network will have to adapt to correct mistakes from prior layers (read more <a href="https://machinelearningmastery.com/dropout-for-regularizing-deep-neural-networks/">here</a>).</p><p>Without knowing whether my model will be in this situation or not, I trained 2 models, one with the dropout layers and one without, and compare their results. For these model, don&#39;t forget to use Early Stopping as well.</p><pre><em>#build the basic model without dropout</em><br>model_wo_dropout = tf.keras.Sequential()<br>model_wo_dropout.add(hub_layer)<br>for units in [128, 128, 64, 32]:<br>    model_wo_dropout.add(tf.keras.layers.Dense(units, activation=&#39;relu&#39;))<br>model_wo_dropout.add(tf.keras.layers.Dense(19, activation=&#39;softmax&#39;))</pre><pre>model_wo_dropout.summary()</pre><pre><em>#compile the model</em><br>model_wo_dropout.compile(optimizer=&#39;adam&#39;,loss=tf.keras.losses.CategoricalCrossentropy(from_logits=<strong>True</strong>), metrics=[&#39;accuracy&#39;])</pre><pre>train_data_fetch = train_data_fetch.shuffle(70000).batch(512)<br>test_data_fetch = test_data_fetch.batch(512)</pre><pre><em>#fit the model</em><br>from keras import callbacks<br>earlystopping = callbacks.EarlyStopping(monitor=&quot;val_loss&quot;, mode=&quot;min&quot;, patience=5, restore_best_weights=<strong>True</strong>, verbose=1)<br>text_classifier_wo_dropout = model_wo_dropout.fit(train_data_fetch, epochs=25, validation_data = test_data_fetch,<br>                   verbose=1, class_weight=weights, callbacks =[earlystopping])</pre><p>Evaluation on our test and train sets~</p><pre><em>#training errors</em><br>y_train_pred = model_wo_dropout.predict(train_data)<br><br>print(classification_report(train_labels.numpy().argmax(axis=1), y_train_pred.argmax(axis=1)))</pre><pre><em># test errors</em><br>test_data, test_labels = next(iter(dataset_test.map(fetch).batch(test_length)))<br>y_pred = model_wo_dropout.predict(test_data)<br><br>print(classification_report(test_labels.numpy().argmax(axis=1), y_pred.argmax(axis=1)))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*UyNlw3efoqdSK0z0iC3CgQ.png" /><figcaption>Training results</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*E9dqUdasIojSsHpMPK3hgg.png" /><figcaption>Testing results</figcaption></figure><p>The result, compared to Logistic Regression model that I tried out as a baseline model before building this neural network, improved by 10%, which is a really good sight. I will discuss about these results further after I finish implementing the model with dropout layers.</p><h4>Model with Dropout layers for confirmation of overfitting</h4><p>As I said earlier, to confirm whether our model overfits the data or not, I trained a secondary neural network with several dropout layers and compare the results. We can grid search the best dropout parameter between the range 0.1–1.0. Here, I used 0.3 as the parameter.</p><p>We have to recreate the train and test sets. The only difference in this model is in the layer building process. Everything from that point onwards is the same as the model without the dropout layers. It&#39;s important to note that we should not have the dropout layer right before the output layer (aka the last layer) because the output layer can’t correct the errors from the previous layers anymore, so adding another dropout layer will end up hurting the model’s performance (which was the case for me).</p><pre><em># re-create train, test data for fitting the model</em><br>train_data_fetch_dropout = dataset_train.map(fetch)<br>test_data_fetch_dropout = dataset_test.map(fetch)</pre><pre><em># build a similar model but with the dropout layers</em><br>model = tf.keras.Sequential()<br>model.add(hub_layer)<br><strong>for</strong> units <strong>in</strong> [128, 128, 64]:<br>    model.add(tf.keras.layers.Dense(units, activation=&#39;relu&#39;))<br>    model.add(tf.keras.layers.Dropout(0.3))<br>model.add(tf.keras.layers.Dense(32, activation=&#39;relu&#39;))<br>model.add(tf.keras.layers.Dense(19, activation=&#39;softmax&#39;))<br><br>model.summary()</pre><p>Here are the results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*hGOQgx-4aIqWiWUTVe1o0g.png" /><figcaption>Training results</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*IZxqRwpNlObX3mTPoHhMEA.png" /><figcaption>Testing results</figcaption></figure><h3>~Discussion and extended questions:</h3><ul><li>The performance of the model with and without dropout layers are pretty much the same. The diverge between train and test errors don’t improve even after using the dropout layers. In fact, with the dropout layer, the model fails to predict the labels for a lot more categories than the model without the dropout layer (many have 0% accuracy). However, after examining the big dataset and the fact that regularization doesn’t significantly improve the model, I don’t think that overfitting is not that big of a problem in this model. Further analysis can involve fitting models on different dropout values to confirm if the performance doesn’t improve because we didn’t choose a good dropout rate, or because of the dataset itself.</li><li>The logistic regression, as well as other ML models, don’t have that big of a gap between the training and testing errors. It can be said that these ML models don’t suffer from overfitting as much as the neural network model, however, these models can hardly be improve further, given that we already use the best parameters. Meanwhile, the neural network stands a good chance of improving beyond this point. And since our interest lies in getting more accurate prediction, we will go with the neural network.</li><li>It is observed that the overall accuracy for both models goes up after I added more data points (more countries). This makes me wonder if getting all the data available will even increase the accuracy more.</li><li>The accuracy shows slight fluctuations across different fitting attempts (due to the fact that neural network model can fall into the ‘local max/min&#39; trap), but on average, the result is in the range [0.66–0.71], which is ~5–10% increase from the average of the results of the machine learning models I fitted (which is ~59–60%). Looking at the confusion matrix, the metrics within each category also improves.</li><li>Another source that might affect the predictive power of the model is the fact that a lot of categories (take health resources, health monitoring and health testing) share many words in common, so one of the next steps from here is to identify and develop a collection of stopwords that appear a lot across different categories to reduce the similarity between these categories and see if this increases the performance even further.</li></ul><p>To conclude, this neural network model is pretty simple and there is definitely room for improvement, with the emphasis on the data preprocessing procedure (more stopwords, over-/undersampling), as well as further cross validation to average out the accuracy. That being said, this is a very fulfilling learning experience and first exposure to neural network for me! If you have made this far, thank you so much! I look forward to updating you more on my future version of this model.</p><p>A full version of this notebook can be found in this Github repo:</p><p><a href="https://github.com/irenechang1510/Topic-classification-NN/blob/main/Topic%20classification%20with%20Neural%20Network.ipynb">irenechang1510/Topic-classification-NN</a></p><p>Feel free to reach out to me via my <a href="https://www.linkedin.com/in/irene-chang-4356a013a/">LinkedIn</a>, if you have any question, I would love to connect!</p><p>References:</p><p>[1] Dipanjan (DJ) Sarkar, <a href="https://towardsdatascience.com/deep-transfer-learning-for-natural-language-processing-text-classification-with-universal-1a2c69e5baa9">Deep Transfer Learning for Natural Language Processing — Text Classification with Universal Embeddings</a> (2018), towardsdatascience</p><p>[2] Miguel Fernández Zafra, <a href="https://towardsdatascience.com/text-classification-in-python-dd95d264c802">Text Classification in Python</a> (2019), towardsdatascience</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d85cbc0f90c0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/covid-19-policies-multi-classification-with-neural-network-d85cbc0f90c0">COVID-19 Policies Multi-classification with Neural Network</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>