<?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 María García Gumbao on Medium]]></title>
        <description><![CDATA[Stories by María García Gumbao on Medium]]></description>
        <link>https://medium.com/@mggumbao?source=rss-c472d69983cc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*KjJZzFynZ4mM7GNyoXN0HQ.jpeg</url>
            <title>Stories by María García Gumbao on Medium</title>
            <link>https://medium.com/@mggumbao?source=rss-c472d69983cc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 16:26:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mggumbao/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[Best clustering algorithms for anomaly detection]]></title>
            <link>https://medium.com/data-science/best-clustering-algorithms-for-anomaly-detection-d5b7412537c8?source=rss-c472d69983cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5b7412537c8</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[anomaly-detection]]></category>
            <category><![CDATA[clustering]]></category>
            <dc:creator><![CDATA[María García Gumbao]]></dc:creator>
            <pubDate>Mon, 03 Jun 2019 16:31:00 GMT</pubDate>
            <atom:updated>2019-06-04T13:01:18.342Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7mvRV5bUo6KIeH7Fc21veA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@olloweb?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Agence Olloweb</a> on <a href="https://unsplash.com/search/photos/magnifying-glass?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Let me first explain how any generic clustering algorithm would be used for anomaly detection.</p><p>The main idea behind using clustering for anomaly detection is to learn the normal mode(s) in the data already available (train) and then using this information to point out if one point is anomalous or not when new data is provided (test).</p><p>General steps (after general preprocessing):<br>1 — Select the best model according to your data.<br>2 — Fit the model to the training data, this step can vary on complexity depending on the choosen models, some hyper-parameter tuning should be done at this point.<br>3 — Once new data is received, compare it with the results of the model and determine if it’s a normal point or an anomaly, the way to perform this classification depends highly on the model (I’d talk about how to do it for the explained models), some are based on distance, whilst others use probabilities.</p><p>4 — If there is any kind of data evolution over time the model should be retrained after a while, in order to learn new behavior (otherwise this new behavior might always be classified as anomalous).</p><p><strong>Note</strong>: Of course clustering is not ideal for all the problems related to anomaly detection (just like any other method, you know, there is no <em>free lunch</em>), but combining this technique with other like smart feature extraction can help you solve a lot of problems; for example, what happens when you have time series and the problem it’s a that a value is increasing too fast, but still in a normal range of values? Adding the derivatives into the clustering algorithm can help you find that anomaly.</p><h3>DBSCAN</h3><p>DBSCAN is a density based clustering algorithm (actually DBSCAN stand for <strong><em>D</em></strong><em>ensity-</em><strong><em>B</em></strong><em>ased </em><strong><em>S</em></strong><em>patial </em><strong><em>C</em></strong><em>lustering of </em><strong><em>A</em></strong><em>pplications with </em><strong><em>N</em></strong><em>oise), w</em>hat this algorithm does is look for areas of high density and assign clusters to them, whereas points in less dense regions are not even included in the clusters (they are labeled as anomalies). This is, actually, one of the main reasons I personally like DBSCAN, not only I can detect anomalies in test, but anomalies in training will also be detected and not affect my results.</p><p>There are two key parameters in this models:<br> — <em>eps: </em>Maximum distance between two points to consider them as neighbors. If this distance is too large we might end up with all the points in one huge cluster, however, if it’s too small we might not even form a cluster.<br> — <em>min_points:</em> Minimum number of points to form a cluster. If we set a low value for this parameters we might end up with a lot of really small clusters, however, a large value can stop the algorithm for creating any cluster, ending up with a dataset form only by anomalies.</p><p>The way this algorithm creates the clusters is by looking at how many neighbors each point has, considering neighbors all the points closer than a certain distance (<em>eps</em>). If more than <em>min_points </em>are neighbors, then a cluster is created, and this cluster is expanded with all the neighbors of the neighbors. But, since one picture is worth more than a thousand worths I’ve borrowed this picture from this <a href="https://medium.com/@elutins/dbscan-what-is-it-when-to-use-it-how-to-use-it-8bd506293818">Medium post explaining DBSCAN</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*m58lXVJTehxIM0CqA4lbaQ.png" /><figcaption>Image obtain from the post “<a href="https://medium.com/@elutins/dbscan-what-is-it-when-to-use-it-how-to-use-it-8bd506293818">DBSCAN: What is it? When to use it? How to use it?</a>”</figcaption></figure><p>Now we have the clusters…</p><p><strong><em>How can we detect anomalies in the test data?</em></strong></p><p>The approach I’ve followed to classify the point as anomalous or not is the following:<br>1 — Calculate the distance from the new points to all the <strong>Core</strong> points (only the Core points, since they are the ones actually defining the clusters) and look for the minimum (distance to the closest neighbor inside a cluster).<br>2 — Compare the distance to the closest neighbor inside a cluster with <em>eps</em>, since this is the limit between two points to be consider neighbors, this way, we find if any of the Core points are actually neighbors with our test data.<br>3 — If the distance is larger than <em>eps</em> the point is labeled as anomalous, since it has no neighbors in the clusters.</p><h3>Gaussian mixture models</h3><p>Probabilistic model that assumes all the data points are generated from a mixture of a finite number of gaussian distributions. The algorithms try to recover the original gaussian that generated this distribution. To do so it uses the expectation-maximization (EM) algorithm, which initialize a random of <em>n</em> initial gaussian distribution and then tweaks the parameters looking for a combination that maximizes the likelihood of the points being generated by that distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ccIDkAqeZKTM-aRCQ6yOQw.png" /><figcaption>Figure obtained from Angus Turner’s blog: “<a href="https://angusturner.github.io/generative_models/2017/11/03/pytorch-gaussian-mixture-model.html">Gaussian Mixture Models in PyTorch</a>”</figcaption></figure><p>One of the problems of Gaussian Mixture Models is that the number of clusters needs to be specified, another possibility is to use Variational Bayesian Gaussian Mixture, to avoid this problem.</p><p>Of course, just as K-Means, since the initialization of the clusters is <strong>random</strong> we can end up with a local minimum that is not optimal for our problem. That is something that can be solved with multiple executions and then creating an average of the probabilities. However, this solution is not optimal if the model needs to be put into production, I’m still looking for the best approach to solve this problem when a model needs to be deployed in a streaming environment.</p><p><strong>Variational Bayesian Gaussian Mixture</strong></p><p>I don’t want to get into much detail here, there’s the scikit-learn page with the full explanation for that. But this variation is worth mentioning. The idea behind this model is similar to Gaussian Mixture, however, the implementation is different, here, instead of EM, variational inference algorithm is used.</p><p>Here, only a maximum number of clusters needs to be specified, the algorithm then can find the actual number of clusters and set the weight of the non-relevant ones very close to zero.</p><p>Of course this alternative is not perfect either, there are many hyperparameters to chose, more than in Gaussian mixture actually. One of the most important is the <em>weight_concentration_prior</em>, which will largely affect the number of effective clusters you end up with.</p><p><strong><em>How can we detect anomalies in the test data?</em></strong></p><p>Once the algorithm it’s trained and we get new data we can just pass it to the model and it would give us the probability for that point to belong to the different clusters. Here, a threshold can be set, to say that if the probability is below that value the point should be consider an anomaly. In the case of Bayesian Gaussian Mixture there is an important thing to keep in mind: <strong>Not all clusters should be considered</strong>, remember that the algorithm disregards <strong>non important clusters</strong> giving them a <strong>weight close to zero</strong> (they are not removed, but you can know which ones should be removed), what I’ve done in the past is check the probability of the point belonging <strong>only</strong> to the important clusters, to do that I’m setting a threshold for the cluster weights, to remove the non-important ones.</p><h3>Why not K-Means?</h3><p>While K-Means is maybe the best-known and most commonly used clustering algorithm for other applications it’s not well suited for this one.</p><p>The main reason for this is that it’s only well suited when clusters are expected to have quite regular shapes, as soon as this is not fulfilled the model is not able to successfully separate the clusters.</p><p>Another reason is that all points are fitted into the clusters, so if you have anomalies in the training data these point will belong to the clusters and probably affect their centroids and, specially, the radius of the clusters. This can cause you to not detect anomalies in the test set due to the increase in the threshold distance.</p><p>Another posibility is that you even form a cluster of anomalies, since there is no lower limit for the number of points in a cluster. If you have no labels (and you probably don’t, otherwise there are better methods than clustering), when new data comes in you could think it belongs to a normal-behavior cluster, when it’s actually a perfectly defined anomaly.</p><p>Another disadvantage in this case is the need to specify the number of clusters a priori, we’ve already discussed that there are some parameters that are not easy to tune in the other algorithms, but I find this one to be specially tricky. Since the data we can change with time, the number of clusters can also vary, and once we have deploy our model into production there is no easy way to decide that other without human exploration.</p><p><strong><em>How can we detect anomalies in the test data?</em></strong></p><p>Not everything is bad for K-Means, it actually is the simplest case for the testing phase, since we have the centroids of the clusters and the shape is expected to be quite regular we just need to compute the boundary distance for each cluster (usually it’s better not to choose the maximum distance to the centroid, in case we have outliers, something like the 95th or 99th percentile should work, depending on your data).</p><p>Then, for the test data the distance to the centroids is computed. This distance is then compared with the boundary of each cluster, if the point doesn’t belong to any cluster (distance &gt; boundary) it gets classified as an anomaly.</p><h3>To sum up</h3><p>I’ve presented here some clustering algorithms and explain how to use them for anomaly detection (some of them being more successful than others), obviously these are not the only methods, and I might be bias towards some of them based on the data I’ve dealt with.</p><p>I really think DBSCAN and (Bayesian) Gaussian Mixture models are the most useful clustering algorithms for this application. If you’re getting started with anomaly detection it’s worth it to find out more about them, if they aren’t useful to you now at least is something new you’ve learnt.</p><p>Some interesing links:</p><ul><li><a href="https://medium.com/@elutins/dbscan-what-is-it-when-to-use-it-how-to-use-it-8bd506293818">DBSCAN: What is it? When to Use it? How to use it.</a></li><li><a href="https://towardsdatascience.com/how-dbscan-works-and-why-should-i-use-it-443b4a191c80">How DBSCAN works and why should we use it?</a></li><li><a href="https://scikit-learn.org/stable/modules/mixture.html">2.1. Gaussian mixture models</a></li></ul><p>If there are more clustering algorithm that you’ve found useful for anomaly detection and I haven’t mentioned them please let me know, I would love to expand this list!</p><p>Feel free to contact me through <a href="https://www.linkedin.com/in/mariagumbao/">LinkedIn</a> if you want to chat some more!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5b7412537c8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/best-clustering-algorithms-for-anomaly-detection-d5b7412537c8">Best clustering algorithms for anomaly detection</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[Don’t make this mistake when clustering time series data!]]></title>
            <link>https://medium.com/data-science/dont-make-this-mistake-when-clustering-time-series-data-d9403f39bbb2?source=rss-c472d69983cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9403f39bbb2</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[timeseries]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[paper-review]]></category>
            <dc:creator><![CDATA[María García Gumbao]]></dc:creator>
            <pubDate>Sat, 09 Mar 2019 12:13:52 GMT</pubDate>
            <atom:updated>2019-03-09T20:51:02.074Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>Disclaimer:</strong> This is not original work, the aim of this post is to spread and make more accesible the content of the paper “<a href="http://www.cs.ucr.edu/~eamonn/meaningless.pdf"> Clustering of Time Series Subsequences is Meaningless: Implications for Previous and Future Research</a>” by Eamonn Keogh &amp; Jessica Lin.</blockquote><p>Recently, I’ve started doing some research in how to apply clustering techniques to time series and I was surprise to find very little posts about the topic (specially comparing it to the number of posts I found when I wanted to learn about LSTMs). Luckily, I found this paper from Eamonn Keogh &amp; Jessica Lin, which is really interesting (and I encorage you to read), but for those of you who don’t have time (or don’t feel like it) I decided to sum it up in a post.</p><p>There are two types of clustering when dealing with time series data:</p><ul><li>Whole clustering: When you have several time series which can come from different machines and want to compare them.</li><li>Subsequence clustering: When the original data is one long time series that needs to be broken into parts to do clustering on those parts.</li></ul><p>This papers focuses on the second type of time series clustering, and makes the disruptive claim that clustering of time series subsequences is meaningless!</p><p>Specifically they talk about subsequences obtain by a sliding windows, they make a note that other methos for obtaining this subsequences can produce successful results and even propose a new method (which I won’t get into here).</p><h3>What’s their proof?</h3><p>To proof this claim they perform a series of experiments using different clustering algorithms and different datasets to make sure the difference is only made by the subsequencing algorithm.</p><p>What they are doing is generate <em>k </em>clusters from the subsequences of a given dataset and <em>k </em>clusters from the subsequences of a random dataset. Once this is done they compare the clusters obtain in the two cases and observe that this clsuters are similar, even though the data is not. This doesn’t happen using a whole clustering approach, as it can be seen in this figure from the paper:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*qWeHE_vg9VRZZt9g6WU57Q.png" /><figcaption>Image obtained from the original paper</figcaption></figure><p>The way to measure the “<strong>cluster meaningfulness</strong>” (z axis) is obtaining a value for the stability of the clusters (similar clusters for different runs with different initial centroids) and dividing it by the difference of the clusters obtain for the different datasets (one of them being random).</p><p>If this value is close to zero it means that the clusters are stable and far from the clusters generated for the random dataset. This clusters can be said to be meaningful. However, if this is close to one it means that the differences between different runs over the same data are similar to the differences with the clusters from the random dataset, this doesn’t make sense, since clusters generated from different datasets shouldn’t be similar; a value of 1 means that the clusters are not meaningful at all.</p><p>As we can see in the picture this is exactly what happens when doing subsequence clustering, the clusters obtained are not meaningful. Since this happens for many different algorithms and datasets they conclude this is a consequence of the way the subsequence extraction is done.</p><h3>But why?</h3><p>When studying the results obtain in this clusters they found that when the length of the subsequences are much smaller than the original length all cluster centers are found to have a sinusoidal shape. The cluster center is the average value of all the subsequences in the cluster, but whatever the shape of these subsequences is the result is a perfect sine wave.</p><p>In the paper they show this with an example, I won’t explain it in depth here, but even though the shapes of the subsequences looks nothing like a sine wave, the results after clustering are the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*1-RNsZ2B647uyLdcYh6rFw.png" /><figcaption>Image obtain from the original paper</figcaption></figure><h3>Conclusion</h3><p>We need to be careful when doing clustering over subsequences of time series data. This has proven that a sliding window technique for obtaining the subsequences yields meaningless clusters, even though this technique was supposed to be usefull and definitely well known (it had been used in many published papers). There are other ways of obtaining this subsequences and some of them can give optimal results, however, we always have to keep an eye on the clusters generated, to make sure the centers make sense with our data and they are representated of behaviours really present on the dataset.</p><p>If you want to understand this in more detail I recommend you read the original paper, is all very clear and well explained, the aim of this post was to sum it up so I didn’t want to get into much detail. Feel free to ask me any doubts you may have, of course, but remember I haven’t done the original work, just read it and made most I could out of it.</p><p>Feel free to contact me through <a href="https://www.linkedin.com/in/mariagumbao/">LinkedIn</a> if you want to chat some more!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9403f39bbb2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/dont-make-this-mistake-when-clustering-time-series-data-d9403f39bbb2">Don’t make this mistake when clustering time series data!</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Time Series Forecasting (1): Initial analysis]]></title>
            <link>https://medium.com/data-science/time-series-forecasting-1-initial-analysis-87e017501e98?source=rss-c472d69983cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/87e017501e98</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[María García Gumbao]]></dc:creator>
            <pubDate>Thu, 07 Feb 2019 19:25:56 GMT</pubDate>
            <atom:updated>2019-02-08T17:18:21.019Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>All this info can be found in my kaggle profile on <a href="https://www.kaggle.com/mariagumbao/time-series-forecasting-1-initial-analysis">this jupyter notebook</a>.</blockquote><p>Let’s start this series by defining what time series are. I opted for the simplest option and asked wikipedia and this is the answer:</p><blockquote>A time series is a series of data points indexed (or listed or graphed) in time order. Most commonly, a time series is a sequence taken at successive equally spaced points in time. Thus it is a sequence of discrete-time data. — Wikipedia</blockquote><p>So time series are basically like any other dataset but with two important characteristics:</p><ul><li>The order of the data is important, we don’t only care abour the values of the data but also **when** do those values happen.</li><li>We have information of the time in which each instance was observed: We either have a column with datetime information or we know that the data is equally space in time (one value every second, for example).</li></ul><p>Here I’m introducing the concept of time series and doing the initial analysis and tuning of the data; since Kaggle data is usually pretty clear this work is way easier than in real life, but the idea is to represent what would be the process, not to write complex code. The process I’m going to follow is this:</p><ol><li>Loading the data and subsetting (I won’t be using the whole dataset here)</li><li>Visualizing the data</li><li>Cleaning the data: Are there missing values? Is all the data in the desired format?</li><li>Looking at the statistics: Are there outliers?</li><li>Looking for stationarity and autocorrelation</li><li>Trend and seasonality decomposition</li></ol><h4>The Data</h4><p>I’m using the <a href="https://www.kaggle.com/selfishgene/historical-hourly-weather-data/home">Historical Hourly Weather Data</a> from Kaggle’s repository. This dataset contains ~5 years of weather information for different cities, including information about the temperature, humidity, pressure, wind and description of the weather. I am going to focus on <strong>temperature</strong> data, since it’s the property I find to be more intuitive.</p><p>To do the examples I’m going to use the temperature data for two cities, the chosen ones will be San Francisco (because I like it) and the city with the highest variation.</p><h3>Loading the data</h3><p>I will be using Pandas through the entire notebook to handle the data and matplotlib for the visualization.</p><pre>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt</pre><p>Let’s start by loading the data a having a quick look at its shape and first values. Since I already know this is a time series I’m going to set the datetime column as the index.</p><pre>temp = pd.read_csv(&#39;../input/temperature.csv&#39;, parse_dates=[&#39;datetime&#39;])<br>temp = temp.set_index(&#39;datetime&#39;)<br>print(&#39;Dataset shape: {}&#39;.format(temp.shape))<br>temp.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0GSmxuzhslPVoJEM5t1VMQ.png" /></figure><p>This dataset is composed by 36 columns, corresponding to 36 different cities, and 45253 rows, giving the value of the temperature every hour from late 2012 to late 2017.</p><p>As I said, one of the cities I’m going to use is the one with the highest variation in yearly temperature. Let’s find out which one.</p><pre>all_std = temp.std(axis=0)<br>max_std = all_std.max()<br>city_max_std = temp.columns[all_std==max_std][0]</pre><pre>print(&#39;City with highest temperature variation: {} ({} degrees)&#39;.format(city_max_std,round(max_std,2)))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XyAipTeFdO3hHflDkTHtGg.png" /></figure><p>Let’s subset the data now so it only contains values for San Francisco and Minneapolies and see some statistics.</p><pre>data = temp[[&#39;San Francisco&#39;,&#39;Minneapolis&#39;]]<br>data.describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*QAYedcECZu8liR_9IKwFRw.png" /></figure><p>First thing I see is that there are missing data in both columns, I’ll deal with that soon. Also, this temperature values are obviously not in a normal scale for day-to-day temperature. Since I live in Europe I’m going to transform the data from Kelvin to Celsius (sorry if you use Farenheit, but International Systemm baby).</p><pre>data = data-273.15<br>data.describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*2K5tzDw35ReVywmSsEJ2xg.png" /></figure><h3>Visualizing the data</h3><p>Let’s see what the temperature for these two cities looked like along the years.</p><pre>_=data.plot(<br>    figsize=(15,5),<br>    subplots=False,<br>    title=&#39;Temperature&#39;,<br>    alpha=0.7<br>)<br>_=plt.xlabel(&#39;Date&#39;)<br>_=plt.ylabel(&#39;Temperature&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-ygN8PYkdNTnp_FJ3HPYuQ.png" /></figure><p>Not bad, the weather seems quite cold in Minneapolis, maybe I wouldn’t go there during the winter.</p><p>Also, there is a clear seasonality in the data with a period of a year. There is also more variation, I’ll check later if this variation has something to do with some daily seasonality or it’s more random.</p><p>Something I can see in this figure is that we have less data for San Francisco. The blue line doesn’t get that close to 2018.</p><h3>Cleaning the data</h3><p>As we saw, there are clearly missing values, something that caughts my attention in the figure may be a reason for this. As I mentioned, the data for San Francisco finishes earlier, to work with both series at the same time I’m going to lose the final values in the Minneapolis series.</p><p>To do so I’m going to keep all the non-missing values of San Francisco and see the maximum date they reach. Then, we’ll cut all data with date larger than that.</p><pre>SF_non_missing = data[&#39;San Francisco&#39;].dropna()<br>max_date = SF_non_missing.index.max()<br>data = data[data.index &lt;= max_date]</pre><p>Let’s see if we still have missing values.</p><pre>print(data.isna().sum())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k-zqac9cINQUV--aBjcyrA.png" /></figure><p>Ok, we still have to deal with the problem of missing data, but there is something I want to deal with first. My intention here is to study the yearly behaviour of the data, I’m not interested in the daily variation, so I’m going to resample the data into a daily frequency by taking the average, minimum and maximum of all the temperatures through that day.</p><pre>data_mean = data.resample(&#39;D&#39;).mean()<br>data_min = data.resample(&#39;D&#39;).min()<br>data_max = data.resample(&#39;D&#39;).max()<br>print(&#39;Resample shape: {}&#39;.format(data_mean.shape))<br>data_mean.describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6HJBRUVG-E2r4HsUHsYjMA.png" /></figure><p>This could also have solved our problem with missing data, if there was more any row with non-missing data everyday. Let’s check.</p><pre>print(&#39;Missing data now?&#39;)<br>print(data_mean.isna().sum())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A4GVM2ZSD_1ledNma5yTrA.png" /></figure><p>No missing data now! This means that we have at least one value per day.</p><p>If this were not the case I would have used the values from the previus day. I like this solution for time series more than just dropping the row (is better to have the same temporal separation between all rows) or just using the mean value (since this would mess with the shape of the curve).</p><p>Let’s check how our data looks after resampling.</p><pre>_=data_mean.plot(<br>    figsize=(15,5),<br>    subplots=False,<br>    title=&#39;Temperature&#39;,<br>    alpha=0.7<br>)<br>_=plt.fill_between(<br>    x=data_mean.index,<br>    y1=data_min[&#39;San Francisco&#39;].values,<br>    y2=data_max[&#39;San Francisco&#39;].values,<br>    alpha=0.3<br>)<br>_=plt.fill_between(<br>    x=data_mean.index,<br>    y1=data_min[&#39;Minneapolis&#39;].values,<br>    y2=data_max[&#39;Minneapolis&#39;].values,<br>    color=&#39;orange&#39;,<br>    alpha=0.3<br>)<br>_=plt.xlabel(&#39;Date&#39;)<br>_=plt.ylabel(&#39;Temperature&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Czr_kJ4X9IW1CLNrzoX_hA.png" /></figure><p>The shadow around the curve shows the min-max values during that day, while the main line shows the mean value.</p><p>Now both curves end at the same point, and we have less daily variation.</p><h3>Outliers</h3><p>Some times weird things happen and we end up with values that can mess up an entire model. One sensor can fail, for example, and measure a temperature of -10º in summer, which definitely is not normal. Other times you can see 10º in the summer, that’s low, but maybe not an error, sometimes it can get cold, you can’t remove this type of value, because there can be some reason to it. We have to be carefull how we treat outliers, we shouldn’t remove it unless we know it’s an error or is a one-time-thing that shouldn’t affect our model.</p><p>It’s not always easy to identify which points are outliers, and what to do with them, but a good place to start is to inspect the data to see if there are points with extremely high or low values. One good way to see this visually is to use histograms.</p><pre>_=plt.hist(data_mean[&#39;San Francisco&#39;], alpha=0.5, label=&#39;San Francisco&#39;)<br>_=plt.hist(data_mean[&#39;Minneapolis&#39;], alpha=0.5, label=&#39;Minneapolis&#39;)<br>_=plt.legend()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*h9Kb9p9_yaSybJYam_wN4g.png" /></figure><p>Let’s look into each of the cities individually:</p><ul><li>Values for San Francisco seem to follow a gaussian distribution with a small standard deviation, we can’t see any outliers in this data.</li><li>For Minneapolis the curve is less perfect, with a high skewness to the right side (negative skewness). We cannot say that any of this points are outliers though, since there is quite a few of them, also, in the visual representation of the temperatures we could see that really low values are reached every year.</li></ul><p>I don’t see any outliers and don’t think I should remove any points.</p><h3>Looking for stationarity and autocorrelation</h3><p>Ths gaussian-shaped histagram we plotted earlier is a first clue the time series can be stationary.</p><p>Another clue is to compute some statistics on the time series in different time ranges and looking for a variation.</p><pre>cut = data_mean.index[int(0.5*len(data_mean))]<br>print(&#39;Mean before {}:&#39;.format(cut))<br>print(data_mean.loc[:cut].mean())<br>print(&#39;&#39;)<br>print(&#39;Mean after {}:&#39;.format(cut))<br>print(data_mean.loc[cut:].mean())<br>print(&#39;&#39;)<br>print(&#39;---------------------------&#39;)<br>print(&#39;&#39;)<br>print(&#39;Std before {}:&#39;.format(cut))<br>print(data_mean.loc[:cut].std())<br>print(&#39;&#39;)<br>print(&#39;Std after {}:&#39;.format(cut))<br>print(data_mean.loc[cut:].std())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hv-IiXPnOFhKp27BnPaPIw.png" /></figure><p>We can see that the values are pretty close for San Francisco, but further away for Minneapolis, they are still close enough for the time series to be stationary since we need to take into account the standard deviation.</p><p>This method doesn’t prove or deny that our time series are stationary, it’s just indicates that it can be.</p><p>We can also use a statistical test to see if the non-stationarity hypothesis should be rejected <strong>Augmented Dickey-Fuller test.</strong></p><pre>from statsmodels.tsa.stattools import adfuller</pre><pre>result = adfuller(data_mean[&#39;San Francisco&#39;])<br>print(&#39;San Francisco&#39;)<br>print(&#39;--------------------------&#39;)<br>print(&#39;ADF Statistic: %f&#39; % result[0])<br>print(&#39;p-value: %f&#39; % result[1])<br>print(&#39;Critical Values:&#39;)<br>for key, value in result[4].items():<br>    print(&#39;\t%s: %.3f&#39; % (key, value))</pre><pre>print(&#39;\n\n&#39;)<br>    <br>result = adfuller(data_mean[&#39;Minneapolis&#39;])<br>print(&#39;Minneapolis&#39;)<br>print(&#39;--------------------------&#39;)<br>print(&#39;ADF Statistic: %f&#39; % result[0])<br>print(&#39;p-value: %f&#39; % result[1])<br>print(&#39;Critical Values:&#39;)<br>for key, value in result[4].items():<br>    print(&#39;\t%s: %.3f&#39; % (key, value))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QryGPxjWgOuCSMlPcr4eHg.png" /></figure><p>So, what do any of these values mean?</p><ul><li>The ADF Statistic is the Augmented Dicken-Fuller score, the more negative this value is, the higher the certainty that we can reject out null hypothesis (the probability that the time series is stationary).</li><li>p-value is the level of confidance for the null hypothesis. A usual threshold for this value is 0.05, meaning that if <em>p_value &lt;= 0.05</em> we can reject the null hypothesis.</li><li>The rest of the values are the critical values for a 99%, 95% and 90% confidence intervals respectively.</li></ul><p>So, what all this means in this case is that we can reject the null hypothesis for San Francisco since <em>p</em> is lower than 0.05, and also, the ADF score is lower than the limit for a 99% confidence interval. However, we fail to reject this hypothesis for Minneapolis, we could say it is stationarity with a confidence interval of 90%, but since the threshold was 95% (<em>p = 0.05</em>), we cannot reject it. This means we should difference the data before applying any model.</p><p>Some references to understand this tests can be found here:</p><ul><li><a href="https://pythondata.com/stationary-data-tests-for-time-series-forecasting/">Stationary Data Tests for Time Series Forecasting</a></li><li><a href="https://machinelearningmastery.com/time-series-data-stationary-python/">How to Check if Time Series Data is Stationary with Python</a></li></ul><h3>Autocorrelation</h3><p>Last thing to check is if the data is autocorrelated. I want to use some autoregression methods to do forecasting in future posts, I can only do that if the data is autocorrelated (meaning that the value in a specific temporal point depends on previous values).</p><p>The statmodels library offers a great tool to check this. Everything outside of the shadowed area has a strong probability of being autocorrelated (over 95% confidence interval).</p><pre>import statsmodels.api as sm<br>print(&#39;San Francisco&#39;)<br>_=sm.graphics.tsa.plot_acf(data_mean[&#39;San Francisco&#39;])<br>plt.show()<br>print(&#39;Minneapolis&#39;)<br>_=sm.graphics.tsa.plot_acf(data_mean[&#39;Minneapolis&#39;])<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LiSuGpcoExpFjxZgamnyJg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i7zRelnHmWd0OXM6YaaM3Q.png" /></figure><p>Let’s focus on the most important lags (the ones closer to the point), for example, data from one-year range.</p><pre>import statsmodels.api as sm<br>print(&#39;San Francisco&#39;)<br>_=sm.graphics.tsa.plot_acf(data_mean[&#39;San Francisco&#39;], lags=365)<br>plt.show()<br>print(&#39;Minneapolis&#39;)<br>_=sm.graphics.tsa.plot_acf(data_mean[&#39;Minneapolis&#39;], lags=365)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tKfdCl1ELwxp_V90IdZbIg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rJDqjUu_04SVe1eaMRSUTg.png" /></figure><p>We can also check for partial autocorrelation, which calculates the correlation removing the effect of any other previous point (points closer to the new value). Here further away points lose importance, I&#39;ll focus on one-month range.</p><pre>print(&#39;San Francisco&#39;)<br>_=sm.graphics.tsa.plot_pacf(data_mean[&#39;San Francisco&#39;], lags=30)<br>plt.show()<br>print(&#39;Minneapolis&#39;)<br>_=sm.graphics.tsa.plot_pacf(data_mean[&#39;Minneapolis&#39;], lags=30)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S2PkOSSuuZhqRwnjeJb_KQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cyW2w6Ekg4td2aiCrRPstg.png" /></figure><p>Here are some references about autocorrelation:</p><ul><li><a href="https://www.statsmodels.org/dev/generated/statsmodels.tsa.stattools.acf.html">Statsmodels reference to acf function</a></li><li><a href="https://www.statsmodels.org/dev/generated/statsmodels.tsa.stattools.pacf.html">Statsmodels reference to pacf function</a></li><li><a href="https://machinelearningmastery.com/gentle-introduction-autocorrelation-partial-autocorrelation/">A Gentle Introduction to Autocorrelation and Partial Autocorrelation</a></li></ul><h3>Trend — Seasonality decomposition</h3><p>We can think about time series as a composition of trend, seasonality and residuals (noise or other random behaviour). The composition of the time series from this components can be bouth aditive or multiplicative:</p><ul><li>Additive: <em>data = Trend + Seasonality + Residuals</em></li><li>Multiplicative: <em>data = Trend · Seasonality · Residuals</em></li></ul><p>The Statsmodels package offers a function to extract this 3 component at once: <a href="https://www.statsmodels.org/dev/generated/statsmodels.tsa.seasonal.seasonal_decompose.html">Seasonal_decompose</a></p><p>The decomposition here is easy because we know the period to be 365 days.</p><pre>from statsmodels.tsa.seasonal import seasonal_decompose as sd<br>sd_SF = sd(data_mean[&#39;San Francisco&#39;], freq=365)<br>sd_M = sd(data_mean[&#39;Minneapolis&#39;], freq=365)</pre><pre>_=plt.figure(figsize=(15,10))<br>ax1=plt.subplot(311)<br>_=ax1.plot(sd_SF.trend, label=&#39;San Francisco&#39;, alpha=0.7)<br>_=ax1.plot(sd_M.trend, label=&#39;Minneapolis&#39;, alpha=0.7)<br>_=plt.legend()<br>ax2=plt.subplot(312)<br>_=ax2.plot(sd_SF.seasonal, label=&#39;San Francisco&#39;, alpha=0.7)<br>_=ax2.plot(sd_M.seasonal, label=&#39;Minneapolis&#39;, alpha=0.7)<br>_=plt.legend()<br>ax3=plt.subplot(313)<br>_=ax3.plot(sd_SF.resid, label=&#39;San Francisco&#39;, alpha=0.7)<br>_=ax3.plot(sd_M.resid, label=&#39;Minneapolis&#39;, alpha=0.7)<br>_=plt.legend()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Psx6XKmz-PR6OXIf9cZMKA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8HEAyR-fRXziRVU8-jcXRA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S6D48_qE8shN2xs0DzrdtQ.png" /></figure><p>Looking at this we can understand why we found the Minneapolis data to be non-stationary, there has been a clear increase in the temperature.</p><p>We can also find the trend by doing the moving average, I won’t do that here since it’s what the seasonal_decompose function does behing the scenes.</p><p>This is it for now. I’ll start with some forecasting algorithms in future posts.</p><p>I hope this can help some beginners like myself, thanks for reading! :)</p><p>Pd.: I would really appreciate some feedback</p><p>Pd2.: I want to give credit to Jason Brownlee’s blog machinelearningmastery since is where I learnt most of what I know about time series data, he has many posts about this topic and his explanations and examples are really clear, I totally recommend it if you’re getting started, or want to expand your knowladge about this or any other machine learning topic</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87e017501e98" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/time-series-forecasting-1-initial-analysis-87e017501e98">Time Series Forecasting (1): Initial analysis</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>