<?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 ds_mt on Medium]]></title>
        <description><![CDATA[Stories by ds_mt on Medium]]></description>
        <link>https://medium.com/@ds_mt?source=rss-d785ece0c4ff------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dvzMt_vOHIst_cgz3b2CEw.png</url>
            <title>Stories by ds_mt on Medium</title>
            <link>https://medium.com/@ds_mt?source=rss-d785ece0c4ff------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 16:47:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ds_mt/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[Using K-Means to detect changes in a retail store]]></title>
            <link>https://medium.com/data-science/using-k-means-to-detect-changes-in-a-retail-store-96af1476dd9f?source=rss-d785ece0c4ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/96af1476dd9f</guid>
            <category><![CDATA[marketing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[unsupervised-learning]]></category>
            <dc:creator><![CDATA[ds_mt]]></dc:creator>
            <pubDate>Fri, 15 May 2020 19:43:59 GMT</pubDate>
            <atom:updated>2020-05-15T23:31:37.942Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*l0qtcDYgfenycwLQ" /><figcaption>Photo by <a href="https://unsplash.com/@mikepetrucci?utm_source=medium&amp;utm_medium=referral">Mike Petrucci</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Unsupervised techniques to identify changes in consumer behavior</h3><p>Unsupervised machine learning algorithms can be very useful when identifying changes between certain periods.</p><p>I’ll look at a retail store for wholesalers. As a store, you might expect or might aim for some regularity in your customer base. Given that, I will explain how to identify the clients that in a certain period experience a change in their purchase behavior. This type of analysis can be used in different fields. For example, it can be used to target those clients who are purchasing less. In this case, the store could benefit from offering them a discount to retain them.</p><p>I won’t go through the whole Data Science process for the sake of the post. To make it short and clear, I will skip the steps. If you want to learn more about the Data Science process for solving business problems take a look at this post about <a href="https://towardsdatascience.com/once-again-crisp-dm-methodology-13f02557b632">CRISP-DM methodology</a>.</p><h4>Data</h4><p>It is a tubular dataset that contains transactions from different clients in a UK retail store. It is publicly available <a href="http://archive.ics.uci.edu/ml/datasets/Online+Retail">here</a>.</p><p>It contains invoices for material purchases. With 541909 different invoices from 4372 different customers in 38 countries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*lnNLMGIXRZ4nDTHwwEYY0Q.png" /></figure><p>The transactions range from December 2011 to December 2012.</p><h4>Problem</h4><p>At first sight, the dataset doesn’t give any hint about the clients that experience a change in their purchase behavior. The lack of labels makes it impossible to apply supervised techniques as there is nothing that makes explicit what kind of customers they are. That increases on one level the difficulty of the problem with many nuances and open questions.</p><p>In all machine learning problems, having a good understanding of the problem is crucial to give a tailored solution. There will be many different approaches depending on what the business problem is.</p><h4>Considerations</h4><p>We are going to group the clients depending on their behavior. To do so, we are going to use two variables, the monthly purchasing frequency, and monetary values.</p><p>In the 13 months of purchasing activity, I will compare the activity between two periods. The first one to create the baseline of behavior and a second one to evaluate it. For the prior, we will use 8 months and the 5 for the latter. It will respectively constitute 60% and 40% of the time.</p><p>Talking about technicalities, K-Means is a good algorithm to find similarities in the data. Separating the data into 5 groups will be big enough but it is not that big that it will be sensitive to small changes.</p><p>As the goal of the store is to increase either the purchase frequency or the amount spent, the groups can be classified with the following names:</p><ul><li>Dormant — Very few visits and little money spent. They might need big stimulations in order to reactivate them.</li><li>Potential — Similar to the last group with the distinction that the stimulations to make them better customers will be smaller.</li><li>Medium — Average user.</li><li>Irregular — They visit very few times, but when they do they tend to spend a lot of money.</li><li>Loyal — They visit the shop very often but don’t spend a lot.</li></ul><p>The names and group numbers may vary depending on the strategy of the company. Great communication and understanding between data science and stakeholders are important to properly translate the business needs into the models.</p><p><strong>A quick introduction to K-Means</strong></p><p>It’s the most famous and used unsupervised algorithm. It allows clustering the data in groups or categories that you wouldn’t have thought of yourself. Furthermore, K-Means belongs to the group of hard clustering algorithms, and the reason for this is because once the classification is done, the data points belong to one and only one group. On the other hand, the soft clustering algorithms assign the data to different groups at the same time.</p><p>The way K-Means works is, given the number of clusters it will automatically adjust the center of all the groups based on the distance to the data points until the algorithm converges. One side note, there are different types of distances! K-Means uses euclidean distance (it is the geometrical distance between two data points).</p><p>The main problem when using K-Means is that the optimal number of clusters cannot be automatically calculated by the algorithm. So the number of clusters depends on the business problem to solve and the user behind the screen. However, some techniques can help the user to estimate the number of clusters that fit the best. This is called the elbow method but it’s not covered in this post.</p><h4>How can K-Means be useful to detect changes?</h4><p>After performing some data preprocessing operation this is how the data looks like.</p><pre>tx.describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/1*ciqADeEKFPhLSIuqMgyfeQ.png" /></figure><p>Remarkably, there are some outliers for both variables (frequency and monetary values):</p><ul><li>In the price, the median is 136 pounds, the mean 390 pounds (with quite a big standard deviation of 1887). Following this, I won’t include the clients who spent more than 20.000 pounds.</li><li>Regarding the total invoices per month, the median is 1 visit a month, the mean 0.8 visits (with a standard deviation of 1.2). Following this, the clients with more than 15 visits per month won’t be included in the analysis.</li></ul><p>Note that choosing what outliers to remove may change depending on the nature of the analysis.</p><h4>Splitting the dataset</h4><p>Now, it’s time to split the dataset between the baseline period (8 months), and the evaluation period (5 months).<br>This is how both periods look:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*xM0_ShveiwRbTpWw66zklw.jpeg" /></figure><p>Besides their close similarity, there isn’t much we can obtain from them. Let’s jump to making the groups.</p><h4>K-Means hands-on!</h4><p>As explained earlier, K-Means works using Euclidean distances, which makes it sensitive when the scales of the variables are different. This is the case of the two variables. I will apply a scale between 0 and 1.</p><pre>from sklearn.preprocessing import MinMaxScaler<br>scaler = MinMaxScaler(feature_range = (0, 1))</pre><pre>baseline_norm = pd.DataFrame(scaler.<strong>fit_transform(baseline)</strong>, <br> index = baseline.index, columns = [‘PriceInvoices’,’TotalInvoices’])</pre><pre>evaluation = pd.DataFrame(<strong>scaler.transform(evaluation)</strong>, <br>                          index = evaluation.index, columns = [&#39;PriceInvoices&#39;,&#39;TotalInvoices&#39;])</pre><p>Now we are ready to apply K-Means and see some results:</p><pre>from sklearn.cluster import KMeans</pre><pre><strong>kmeans = KMeans(n_clusters = 5, init = ‘k-means++’, random_state = 1)</strong><br>y_kmeans_train = kmeans.<strong>fit_predict(baseline_norm)</strong></pre><p>A couple of explanations about the parameters for K-Means function.</p><ul><li>The number of clusters is set to 5 as explained before.</li><li>The initialization method we use is k-means++, it selects the cluster centers smartly so it can speed up converge.</li><li>The random state is used to make the algorithm deterministic, in other words, to always return the same results.</li></ul><p>Below, how both periods look like after applying K-Means. Note that firstly, I run the algorithm with the baseline dataset, to create the groups. To later see which are the closest groups for every data point in the evaluation dataset.</p><pre>y_kmeans_test = kmeans.<strong>predict</strong>(evaluation.values)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*IZYgIAmmWtj88H97chRFag.jpeg" /></figure><p>After computing the number of clients that move from one cluster to another, there are 785 different ones. That is 40% of the clients in the evaluation dataset. However, checking the differences in the clusters’ changes, we can see that many of these clients have very small changes. This is explained by the fact that many clients moved from the edge of one cluster to the edge of a different one. We can see the distances’ distribution in the next histogram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*AE8B6nw8IyYJ1sNJnPZSCQ.jpeg" /></figure><p>To reduce the number of flagged clients we can set a threshold and pick up all the clients that are above that level. In our case, I chose 0.25 so they will be visible in the chart.</p><p>And to finalize this is how the changes look like. The yellow lines are the movements of the clients, whereas the X marker is the first position and the dop is where they end up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*9xMRDT376bzGg-lX_W_S7A.jpeg" /></figure><h3>Conclusions:</h3><p>We have seen how we can use machine learning techniques to model the purchasing behavior in a retail store, and we did it using K-Means. The results obtained can be used for different purposes, the one I explained here will suit for marketing purposes. It can help to identify clients that are moving to groups with less activity (e.g. loyal to medium). However, it can be extrapolated to another kind of analysis.</p><p><strong>Downsides and improvements<br></strong>The analysis has a few downsides:</p><ul><li>When the analysis is done, the clients might already be lost and it will be difficult to reactivate them. One way to solve this issue will be adding a new variable for when they did their last transaction, the recency. For example, the RFM analysis will solve this issue, adding the recency of transactions as a new variable in the classification.</li><li>The big number of clients flagged. Soft clustering techniques, such as Gaussian mixtures models (GMMs) will serve as an alternative to K-Means to mitigate the problem. GMMs will give the probability of the data points to belong to every cluster. For example, the data points at the edge of a cluster will have a probability close to 50%-50% of the two clusters.</li></ul><p>To increase the performance of the model capturing changes, K-Means can cope with as many variables as possible, and K-Means will group following the same criteria. However, adding more variables will make the visualization more difficult.</p><p><strong>Keep learning</strong></p><p>As I just wrote a few lines above, you can explore the RFM analysis, it is a great analysis widely used in the industry.</p><p>You might want to try other unsupervised techniques such as hierarchical clustering, or Gaussian mixture models. They solve the main issues of K-Means, but keep in mind that, even though they solve some of K-Means’ problems, they will have their own drawbacks! As said, “there is no free lunch”!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96af1476dd9f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/using-k-means-to-detect-changes-in-a-retail-store-96af1476dd9f">Using K-Means to detect changes in a retail store</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[Once again, CRISP-DM methodology]]></title>
            <link>https://medium.com/data-science/once-again-crisp-dm-methodology-13f02557b632?source=rss-d785ece0c4ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/13f02557b632</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-measurement]]></category>
            <category><![CDATA[crisp-dm]]></category>
            <category><![CDATA[project-management]]></category>
            <category><![CDATA[methodology]]></category>
            <dc:creator><![CDATA[ds_mt]]></dc:creator>
            <pubDate>Mon, 17 Feb 2020 20:09:28 GMT</pubDate>
            <atom:updated>2020-02-20T21:03:26.111Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*c4eKNvMTa71ZNvu0" /><figcaption>Photo by <a href="https://unsplash.com/@franki?utm_source=medium&amp;utm_medium=referral">Franki Chamaki</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>A quick look at one of the famous methodologies for Machine Learning projects</h4><p>If you are reading this, it means you are interested in Machine Learning and Data Science. You might be trying to start a career in this field. Or simply, you want to refresh this methodology.</p><p>In any case, you are more than welcome to keep reading!</p><p>Being honest, this is one of many posts about this methodology. You will not find something new here that is not in other posts. However, I’ll give it a different approach. Not how to apply this methodology to a dataset you found on the internet, but how to use it in a real business problem.</p><p>Long story short <em>CRISP-DM</em>, stands for <em>Cross Industry Standard Process for Data Mining</em>, and it is an iterative process composed of several steps. It sets the framework for how to build from scratch a Data Minning project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Vr4pSn9oJYgT3gGSGa73A.png" /><figcaption>Image by Miguel Torres based in CRISP-DM flow</figcaption></figure><p><strong>Business understanding</strong></p><p>If you want to succeed as a Data Scientist, you need to have a high degree of business understanding. I’m certainly sure you’ve already heard this statement many times.</p><p>Well, surprise, it’s me telling you again, and no matter how much you think you know about the industry or the business, you don’t know enough.</p><p>I’m not talking about understanding the columns of your Kaggle project. I mean, about having a high level of business expertise, and it takes many years to achieve this. Just don’t forget to always learn about the business, and study the industry you are working with.</p><p>Basically, without business expertise, you do not know what are the key features your model needs. Moreover, you will not have infinite time to focus only on learning about the industry or the area. And you will have many other tasks to do, such as, taking care of the data, maintain, run and deploy other models.</p><p>In conclusion, relying on business-related people will help you to achieve this faster. Ask, learn and create synergies with them.</p><blockquote>Be extremely curious about the business</blockquote><p>Once you know the business, and you have a problem to solve, set the objectives, write them, and make them clear and public so business people can be aligned. (<em>Be aware, most probably these objectives are going to change</em>)</p><p><strong>Data Understanding</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9pVsdZe2OmUUZ2JE" /><figcaption>Photo by <a href="https://unsplash.com/@adeolueletu?utm_source=medium&amp;utm_medium=referral">Adeolu Eletu</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Now you think you understand the business? Understanding the data is a whole new world. It requires technical skills, and mostly, a lot of time and patience. Which probably you won’t have. It is not going to be a few tables or just a simple sorted and cleaned CSV. It is going to be a little more than that, luckily few big databases.</p><p>Data understanding, as well as Business understanding, is a long process, and you will be iterating through it your whole career.</p><blockquote>Be obsessively curious about the data</blockquote><p><strong>Data preparation</strong></p><p>Think about what would be the pieces you need to create the ideal dataset and go wild getting them. Don’t focus only on what there is in the databases. Go out of them, go to other web pages (aka, web-scrapping), go to repositories, or even, ask your company to buy it.</p><p>This step is sometimes called feature engineering, and it comprises tasks such as data cleansing, categorization and removing correlated variables.</p><p>It is known as a creative process and it is here where resides the real value in the project. Certainly, it is going to be where you will spend most of your time. Some people say about 80% of the time is spent on data wrangling.</p><p>So…</p><blockquote>Get obsessed about the features</blockquote><p><strong>Modelling and evaluation</strong></p><p>I’m not going to spend a lot of time on this but if you want to save time and headaches…</p><blockquote>Try XGBoost first</blockquote><p>It is going to give you very good results. And you will not have to spend a lot of time choosing what is the most appropriate algorithm and changing the hyperparameters. You can spend a lot of time just to slightly reduce the error of your model. It is really worth it? Would it be better to use this extra time in the feature engineering phase, where you can have a higher impact?</p><p><strong>Deployment and monitoring</strong></p><p>If you get here, the hype is real. It means business people are happy with what you did, and it’s ready to be used. Otherwise, you wouldn’t be doing this.</p><p>The goal here is…</p><blockquote>Automatise as much as possible.</blockquote><p>There are many different deployments. It can be just a report, or a nightly batch, or a CSV file. Most of the time, you will have to place your model in a production server, and it will be consumed by third parties. The accuracy of the model will decrease over time and it will have to be replaced by a new one. Therefore, create the necessary metrics to automatically track when it is not working properly.</p><p><strong>Conclusion</strong></p><p>This is iterative, meaning that you will go back and forth many times over the different steps. Hence, this might cause that not always the project reaches the final step. Try not the get frustrated, everything is part of the learning process and basically, statistics. You can always blame the data :)</p><p>This is the perfect methodology for general projects, no matter the field you are approaching. It will give you the power to keep some organization, and you will not get lost through the process. Basically, the benefits you will get it just following this structure are high.</p><p>However, once you dig in a concrete industry you might have other methodologies that will fit better. It will always depend on the problem you are solving!</p><p>You liked the post? Check the others I have, they are more hands-on with real data and I’m sure you will enjoy them :D</p><p><a href="https://towardsdatascience.com/facing-the-arima-model-against-neural-networks-745ba5a933ca">Facing the ARIMA Model against Neural Networks</a></p><p>Thanks for reading! And don’t forget to keep your data projects clean, documented and organised! :D</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13f02557b632" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/once-again-crisp-dm-methodology-13f02557b632">Once again, CRISP-DM methodology</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[Facing the ARIMA Model against Neural Networks]]></title>
            <link>https://medium.com/data-science/facing-the-arima-model-against-neural-networks-745ba5a933ca?source=rss-d785ece0c4ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/745ba5a933ca</guid>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[arima]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-neural-network]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[ds_mt]]></dc:creator>
            <pubDate>Tue, 16 Apr 2019 13:40:57 GMT</pubDate>
            <atom:updated>2021-08-23T13:57:17.566Z</atom:updated>
            <content:encoded><![CDATA[<h4>Time series Forecasting for Beijing Contamination</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zuQaPup99WdWr77r" /><figcaption>Photo by <a href="https://unsplash.com/@linglivestolaugh?utm_source=medium&amp;utm_medium=referral">Ling Tang</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Introduction</strong></p><p>The purpose of this small project is to go through the ARIMA model to evaluate its performance in a univariate dataset. Also, its performance will be compared with other techniques that are currently available to create predictions in time series using neural networks.</p><p>The dataset that is going to be used, belongs to the UCI repository (<a href="http://archive.ics.uci.edu/ml/datasets/Beijing+PM2.5+Data">http://archive.ics.uci.edu/ml/datasets/Beijing+PM2.5+Data</a>)</p><p>It has an hourly measurement of the quantity of PM2.5 in the air in the city of Beijing. This dataset comes with other information such as the meteorological data from that city. However, as the purpose of this exercise is to make a model from a univariate variable, this other information is not going to be taken into account. <br>We will go step by step through the whole process: starting by importing the data, getting some insights to it, applying the ARIMA model and finally comparing the results with a neural network to evaluate the performance of each model.</p><p>(Disclosure)<br>This post consists of different methods for forecasting time series. However, none of these methods is perfect as there is no perfect way to predict the future, so these results should be taken with care and always with the advice of an expert.</p><p>If the code is what you are looking for is all accessible in a Jupyter Notebook <a href="https://github.com/miguelTorresPorta/TimeSeries/blob/master/timeSeries.ipynb">here</a></p><h3>Understanding the data</h3><p>As I mentioned previously this dataset contains the information about the amount of PM2.5 (ug/m³) concentration of particles in the air of Beijing.</p><p>These are particles with a diameter of fewer than 2.5 micrometres that are floating in the air.<br>(<a href="https://www.who.int/news-room/fact-sheets/detail/ambient-(outdoor)-air-quality-and-health)">https://www.who.int/news-room/fact-sheets/detail/ambient-(outdoor)-air-quality-and-health)</a><br>The world health organization states that exposure to these particles can cause cardiovascular and respiratory diseases and cancer. They estimate that this air pollution caused 4.2 million premature death per year in 2016.</p><h3>Exploratory Data Analysis (EDA)</h3><p>A quick look at the data to see what we need to handle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0HAqK6Sj1a_zQBiSNCPwJg.png" /></figure><p>Regarding this first plot, we can see that at the end and at the beginning of each year the concentration of PM2.5 particles is higher than in other periods of the year, but it is still fuzzy data and we can barely have a better understanding of what is really happening. Because of this, some transformations are needed to be able to get a deeper insight into our data. There are many tools available, and here we are only going to use two, but there are many others that can provide better or different insights.</p><p><strong>Grouping by different frames of time</strong></p><p>The first method is as simple as to compute the mean of the data measurements by week or month.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TOs8zwWYA7NAvYL6I3aDIA.png" /><figcaption>Weekly average.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8zAwIu9O5IvTuiEyetFmJA.png" /><figcaption>Monthly average,</figcaption></figure><p>As we can see from the plots, the information that we get from the data using this method is not very clear.</p><p><strong>Moving average</strong></p><p>This time we are still going to use the mean but in a different way, by using the Moving Average, that computes the average of N given time steps. It will smooth the data allowing the viewer to infer some visible patterns or trends.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*vHYuPv49RdgAiyEqV1vFsQ.png" /><figcaption>Weekly Moving average</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*e-X0KrnU7ueQu8VQjVfHhA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*mA0CqxVNsHa3B8_GuLNZmg.png" /></figure><p>In this last plot, we can clearly spot some regular patterns. However, these methods are very sensitive to outliers and as we can see in the first plot our data has many of them.</p><p>Please note the difference between these two transformations because they look similar but they are not the same. In the average, we just compute the average per week and in the Moving Average (MA) we compute the average of N lagged observations. Although, the second one is more useful because it will help us to smooth the data removing the noise.</p><p><strong>First Conclusion</strong></p><p>There is nothing clear we can get from the data even though it seems to have many outliers. and one can think of these outliers as faulty measures by the devices related to any kind of misfunction. However, doing some research we will find that these levels have been already reached and documented in the capital of China.</p><p><a href="https://www.theguardian.com/world/2013/jan/13/beijing-breathe-pollution">Top tip if you&#39;re going out in Beijing: don&#39;t breathe</a></p><p><strong>Getting closer to the last weeks</strong></p><p>The data that we have evaluated so far looks quite messy, and as the objective of this small project is to apply different forecasting techniques, we are going to focus the efforts in the last four weeks of the entire dataset. By doing so the visualizations are going the be easier and we will see clearly how the predictions fit in our data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*SQM6H3HFWqhlngN23ixA6A.png" /><figcaption>The caption of the last four weeks</figcaption></figure><p>In the distribution of the data, we can see that most of the data is grouped in the first values, looking like the exponential distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*6a4v5OHmRu9746W_9WNyVA.png" /></figure><p>In this data dataset, there are 716 measures of the particle’s concentration, around one month of data. With a mean of 78 particles per hour. This means is considered as unhealthy and people should not be exposed during long periods of time to these levels.</p><p><strong>Stationarity</strong></p><p>Before applying any statistical model it’s important to check if our data is considered as stationary</p><p>Stationarity basically means that the properties such as the mean and variance don’t change over time. <br>(<a href="https://www.itl.nist.gov/div898/handbook/pmc/section4/pmc442.htm">https://www.itl.nist.gov/div898/handbook/pmc/section4/pmc442.htm</a>)</p><p>There are various ways to check if data is stationary, and one good way is the Test Dickey-Fuller, which states that if the p-value is lower than a given threshold it won’t be considered as stationary.</p><p><strong>Test Dickey-Fuller</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*beXxhvnKrXKk5BNTC0ZQng.png" /></figure><p>As we proved with Dickey-Fuller Test, fortunately, our data is stationary which means that it doesn’t have any kind of trend and therefore it doesn’t need any transformations and we can directly to apply ARIMA.</p><p>Sometimes the time series are non-stationary. For these cases, it is possible to apply transformations to the data that will make them stationary.</p><h3>ARIMA</h3><p>Before going through ARIMA we are going to split the data that will help us to train the model, and after that evaluate how accurate it is with the test dataset.</p><pre>train_dataset = last_weeks[&#39;2014-12&#39;: &#39;2014-12-29&#39;]<br>test_dataset = last_weeks[&#39;2014-12-30&#39;: &#39;2014&#39;]</pre><p>Train dataset has the data of 29 days and the test set has 2 days.</p><p>The purpose of splitting the dataset is because the model has to be tested with some labelled data, that means to see how the predictions are close to the real data.</p><p>ARIMA stands for Autorregresive Integrated Moving Average. It is used for time series forecasting.</p><p>It contains three different components. The autoregressive the regression of the time series onto himself, the Integrated (I) component is to correct the non-stationarity of the data. The last component Moving Average (MA) models the errors based on past errors.</p><p>Each component receives different parameters AR(p), I(d), MA(q). To estimate the value of each parameter we need to get the Autocorrelation Function (ACF) and the Partial Autocorrelation Function (PACF)</p><p><strong>Autocorrelation Function (ACF) and Partial Autocorrelation Function (PACF)</strong></p><p>This functions will tell us how correlated are the observations in the time series.</p><p>Also, and the main purpose is that the will indicate us which are the best coefficient to use in our ARIMA model.</p><p>In our case the pattern in the PACF (significant correlations at the first or second lag followed by correlations that are not significant). The number of significant correlations in the PACF tells us the term of the autoregressive (AR) model. In our case, the coefficient is three.</p><p>However, based on the pattern of the ACF (the function progressively decrease), we cannot infer the term for the Moving Average (MA) so the best option is to use zero.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*KKcHxNJZw51hAu3Pfy51PQ.png" /></figure><p><strong>Applying ARIMA</strong></p><p>This first plot shows the residuals of our data, and we can observe that most of the data is distributed around zero. Let’s see more in detail how this is distributed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*goMkrDJOR8Yy0xEYWNi_Ww.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*dlOKuuMSYtav3--ftk205Q.png" /></figure><p>As we can see it has a similar shape as the Normal or Gaussian distributions (Symmetrical bell-shaped curve<strong>)</strong>.</p><p><strong>Get some predictions</strong></p><p>Now it is time to get some predictions from the model, to evaluate how accurate our model is, we are going to use the test dataset we have made.<br>Also, we need to perform a rolling forecast, that means after calculating each prediction add it and recalculate the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RyUsbKDg9W3aTbxmCIOhQw.png" /><figcaption>Predictions compared with the test dataset</figcaption></figure><p>In the plot above we can see the result of our data in the test data, looking like pretty well fitted!</p><p><strong>Evaluation</strong></p><p>Calculate the Mean Squared Error to obtain the accuracy</p><p>MSE: <strong>338.9</strong></p><h3>Neural Networks</h3><p>Now a model of neural networks is going to be applied, concretely we are going to use Recurrent Neural Networks</p><p><strong>Recurrent Neural Networks (RNN)</strong></p><p>RNN is a type of neural networks, which mainly are used in natural language processing (NLP) and predicting Time Series. The basic idea behind these type is that the state of each neuron is stored and fed to the next layer. This is why it is so used in NLP and Time series because it has in count the last observations to predict the next one.</p><p>There is a type of RNN called Long Short-Term Memory, it was proposed to solve a huge problem that all the RNN presented, this is called The Vanishing Gradient Problems but we are not going to enter in this kind of details. This is all we need to know to apply to our dataset.</p><p>This part is going to be much shorter than the previous one because basically to apply Neural Networks is easier than to apply ARIMA Model</p><p>For the sake of the example, we are going to work on the last four weeks.</p><p>Also, the datasets to train and test the network are going to be the same to correctly compare the two models.</p><p>To have better accuracy in our network we need to first normalize the values of our data.</p><p>Now our dataset is ranged between 0 and 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*aUZfXhPO-4c010mwIHYNhg.png" /></figure><p>The Recurrent Neural Networks predict the new observation based on X lagged observations. For our case, let’s try with 168 lagged observations what means around one week to get a new prediction.</p><p>Now it’s time to create the architecture of the Neural Network! We are going to use Keras, which is a popular framework that is made on top of TensorFlow (the neural network library published by Google). Keras is so famous because it makes the task to build the Networks really easy.</p><p>Now it’s time to create the architecture of the Neural Network! We are going to use Keras, which is a popular framework that is made on top of TensorFlow (the neural network library published by Google). Keras is so famous because it makes the task to build the Networks really easy.</p><p><strong>The architecture of the network</strong></p><p>Our network is made by LSTM layers, it contains five layers with 100x200x300x200x100 neurons.<br>I used dropout to improve accuracy and reduce the loss after epoch.<br>In order to calculate the loss of the network, I used the same loss function as before, the Mean Squared Error (MSE) function.</p><pre>regressor.fit(X_train, y_train, epochs = 100, batch_size = 32)</pre><p>Now the model is fitted to our train dataset the model and it’s time to create the predictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oQFA4wW24C9DYIvaJfPGkQ.png" /></figure><p>Luckily, it looks that the predictions suit well to the real values, but the MSE tells a different thing.</p><p>MSE: <strong>409.1</strong></p><p>It looks like we have a winner, as we can see the result with the Neural Networks is worse than the one obtained by ARIMA!</p><h3>Conclusions</h3><p>During this practical case, we saw many different things starting by different concepts of statistical model and time series manipulations (different transformations, stationarity in time series, autocorrelation functions). Following by one statistical model (ARIMA) and Recurrent Neural Networks applied to our particular data set.</p><p>We can see that ARIMA performs better to our test set with a smaller Mean squared error of <strong>338.96</strong> compared to <strong>409.1</strong> provided by the neural networks.</p><p>There are still some other things to try but for this specific dataset with around 720 observations the price goes to the statistical model!</p><p><strong>Future projects</strong></p><p>Once this is understood the first thing that comes to mind is to apply the same methods to the whole dataset (with more than 41.000 observations. Here we will see which one behave better with a higher amount of data.</p><p>The next (still with the same dataset) is to use the other variables to create the forecasting. In the beginning, we have got rid of around 7 different variables with valuable information that we are not using in our model.</p><p>We can also, improve the architecture of the neural network until we reach an optimal point. There is another statistical model such as Seasonal Arima (SARIMA) that can maybe improve the metrics.</p><p>Finally and the purpose of all of this study is to extract useful insights from the data, in our case, it will be about the PM2.5 levels in Beijing.</p><p>… but let’s see all these things in new posts.</p><h3>References</h3><p><a href="https://towardsdatascience.com/an-end-to-end-project-on-time-series-analysis-and-forecasting-with-python-4835e6bf050b">https://towardsdatascience.com/an-end-to-end-project-on-time-series-analysis-and-forecasting-with-python-4835e6bf050b</a></p><p><a href="https://towardsdatascience.com/forecasting-exchange-rates-using-arima-in-python-f032f313fc56">https://towardsdatascience.com/forecasting-exchange-rates-using-arima-in-python-f032f313fc56</a></p><p><a href="https://www.kaggle.com/berhag/co2-emission-forecast-with-python-seasonal-arima/data">https://www.kaggle.com/berhag/co2-emission-forecast-with-python-seasonal-arima/data</a></p><p><a href="https://machinelearningmastery.com/arima-for-time-series-forecasting-with-python/">https://machinelearningmastery.com/arima-for-time-series-forecasting-with-python/</a></p><p><a href="https://www.udemy.com/deeplearning/">https://www.udemy.com/deeplearning/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=745ba5a933ca" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/facing-the-arima-model-against-neural-networks-745ba5a933ca">Facing the ARIMA Model against Neural Networks</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>