<?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 Khanin Artur on Medium]]></title>
        <description><![CDATA[Stories by Khanin Artur on Medium]]></description>
        <link>https://medium.com/@khaninartur?source=rss-445fbfc6e8c1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vhQC6fmhdCUVlpV7p6XGrg.jpeg</url>
            <title>Stories by Khanin Artur on Medium</title>
            <link>https://medium.com/@khaninartur?source=rss-445fbfc6e8c1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 19:05:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@khaninartur/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[Time Series and How to Detect Anomalies in Them — Part III]]></title>
            <link>https://becominghuman.ai/time-series-and-how-to-detect-anomalies-in-them-part-iii-f72e800e15e2?source=rss-445fbfc6e8c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/f72e800e15e2</guid>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[metrics]]></category>
            <category><![CDATA[anomaly-detection]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Khanin Artur]]></dc:creator>
            <pubDate>Tue, 01 Dec 2020 15:44:44 GMT</pubDate>
            <atom:updated>2020-12-03T18:48:09.025Z</atom:updated>
            <content:encoded><![CDATA[<h3>Time Series and How to Detect Anomalies in Them — Part III</h3><h4>Eventually easier than it seemed</h4><p><em>Hello there, my name is Artur.</em></p><p><em>You might be reading this intro for the third time — and if this is the case, I appreciate your sticking with this article series.</em></p><p><em>I am the head of the Machine Learning team in </em><a href="https://kzn.akvelon.com/"><em>Akvelon-Kazan</em></a><em> and you are about to read the last part of the tutorial for anomaly detection in time series.</em></p><p><em>During our research, we’ve managed to gather a lot of information from tiny useful pieces all over the internet and we don’t want this knowledge to be lost so we are sharing it with you!</em></p><p><em>We already dove into the theory and data preparation in</em><strong><em> </em></strong><em>Part I and defined and trained three models in Part II:</em></p><ul><li><a href="https://khaninartur.medium.com/time-series-and-how-to-detect-anomalies-in-them-part-i-7f9f6c2ad32e"><strong><em>Part I — Intro to Anomaly Detection and Data Preparation</em></strong></a></li><li><a href="https://khaninartur.medium.com/time-series-and-how-to-detect-anomalies-in-them-part-ii-bde9e69d0aaf"><strong><em>Part II — Implementation of ARIMA, CNN, and LSTM</em></strong></a></li></ul><p><em>We reuse our code so if something seems unclear, consider visiting the previous parts once more.</em></p><p><em>Fantastic, let’s complete this series!</em></p><figure><a href="https://aijobsboard.com/?fbclid=IwAR0GcsLs8A6CFM-fynrZMM3sTgo_Zpbto2CjglJm0Dmi6otC6YWc7CDFpQk"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dAlwXfVrtYspdCzmC8iADw.png" /></a><figcaption>Big Data Jobs</figcaption></figure><p>Just to briefly remind the tools that we use:</p><ul><li><a href="https://jupyter.org/"><strong>Jupyter Notebooks</strong></a> environment for the implementation of the models</li><li><a href="https://scikit-learn.org/stable/"><strong>Scikit-learn</strong></a> for some data preprocessing</li><li><a href="https://www.statsmodels.org/stable/index.html"><strong>Statsmodel</strong></a> library for ARIMA model</li><li><a href="https://pytorch.org/"><strong>PyTorch</strong></a> for neural networks</li><li><a href="https://plotly.com/python/"><strong>Plotly</strong></a> for plots and graphs</li></ul><p>And what type of models and how we trained:</p><ol><li><a href="https://en.wikipedia.org/wiki/Autoregressive_integrated_moving_average"><strong>ARIMA</strong></a> statistical model — <em>predicts next value</em></li><li><a href="https://en.wikipedia.org/wiki/Convolutional_neural_network"><strong>Convolutional Neural Network</strong></a> — <em>predicts next value</em></li><li><a href="https://en.wikipedia.org/wiki/Long_short-term_memory"><strong>Long Short-Term Memory Neural Network</strong></a> — <em>reconstructs current value</em></li></ol><h3>Anomaly Detection with Static and Dynamic Threshold</h3><p>Amazing, we trained all three models! But every line of the code before was just the preparation for the anomaly detection.</p><p>So just after a very small amount of additional preparations, we will be able to finally detect anomalies.</p><p>What exactly lies behind these <em>“additional preparations”</em>? These things <em>(remember the “Saying what we want from our models out loud” from Part I?)</em>:</p><ol><li><strong>Calculation of the errors</strong> for each item in datasets</li><li><strong>Threshold calculation </strong>based on errors</li></ol><p>And then we will be able to <strong>detect anomalies extremely fast</strong> like literally just <strong>comparing errors with the threshold</strong>.</p><p>What are we waiting for? We’re ready for this!</p><p>The error calculation differs for each model due to different implementations of Datasets. The algorithm stays the same.</p><h4>ARIMA’s errors calculation:</h4><p>Just as a reminder — we use <strong>absolute error </strong>for ARIMA because it causes better results. <em>And if you are wondering how we came to this, the answer is — </em><strong><em>we just tried and it worked.</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66fd4658ef3190422e2cbc0e463e3f75/href">https://medium.com/media/66fd4658ef3190422e2cbc0e463e3f75/href</a></iframe><h4>CNN’s errors calculation:</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a45f5f390b5390b55f0d14999a0ff67/href">https://medium.com/media/5a45f5f390b5390b55f0d14999a0ff67/href</a></iframe><h3>Trending AI Articles:</h3><blockquote><a href="https://becominghuman.ai/how-to-automatically-deskew-straighten-a-text-image-using-opencv-a0c30aed83df">1. How to automatically deskew (straighten) a text image using OpenCV</a></blockquote><blockquote><a href="https://becominghuman.ai/explaining-yolov4-a-one-stage-detector-cdac0826cbd7">2. Explanation of YOLO V4 a one stage detector</a></blockquote><blockquote><a href="https://becominghuman.ai/5-best-artificial-intelligence-courses-for-beginners-in-2020-38db08617b12">3. 5 Best Artificial Intelligence Online Courses for Beginners in 2020</a></blockquote><blockquote><a href="https://becominghuman.ai/a-non-mathematical-guide-to-the-mathematics-behind-machine-learning-4b71d9e16dcd">4. A Non Mathematical guide to the mathematics behind Machine Learning</a></blockquote><h4>LSTM’s errors calculation:</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6be964568055a92d0290ef6cdb259aa1/href">https://medium.com/media/6be964568055a92d0290ef6cdb259aa1/href</a></iframe><h4>Threshold calculation — common for all three models:</h4><p><strong>Static threshold</strong></p><p>This threshold is calculated with this formula of the <em>three-sigma rule</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dcd83c72cdb1d90c80c73e44124caf10/href">https://medium.com/media/dcd83c72cdb1d90c80c73e44124caf10/href</a></iframe><p><strong>Dynamic threshold</strong></p><p>For the dynamic threshold, we will need two more parameters — window inside which we will calculate threshold and std_coef that we will use instead of 3 from the static threshold formula.</p><ul><li>For ARIMA window=40 and std_coef=5</li><li>For CNN and LSTM window=40 and std_coef=6</li></ul><p>These two parameters are <strong>empirically chosen</strong> for each model <strong>using only</strong> the <strong>training data.</strong></p><p>You may wonder — “Why does he always emphasize the usage of only training data? Why can’t I also use validation to choose better parameters?”.<br>The reason why we use just training data for choosing the parameters of our models is that this is the only way we can be sure that our models will work on data from the real world outside the training dataset. The validation part of the dataset imitates such real-world data and provides a better understanding of models’ capabilities because we know — it wasn’t used to train our models.</p><p>Let’s get down to business! Here is the code to calculate the dynamic threshold:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c19a3bed0001b33b89ceb09e6ac65aaf/href">https://medium.com/media/c19a3bed0001b33b89ceb09e6ac65aaf/href</a></iframe><p>And the last element to fulfill our puzzle is <strong>metrics calculation</strong>. What kind of metrics? I am glad you asked. We calculate <strong>every base metric</strong> to fully analyze the models’ performance:</p><ul><li><a href="https://en.wikipedia.org/wiki/Confusion_matrix"><strong>Confusion matrix</strong></a><strong> </strong>to see how a model performs in detail</li><li><a href="https://en.wikipedia.org/wiki/Precision_and_recall#Precision"><strong>Precision</strong></a> to see how precisely our model predicts</li><li><a href="https://en.wikipedia.org/wiki/Precision_and_recall#Recall"><strong>Recall</strong></a><strong> </strong>to see how a model detects true anomalies</li><li><a href="https://en.wikipedia.org/wiki/F1_score"><strong>F2-score</strong></a> to see the<em> combined precision and recall</em>, we are using F2 instead of F1 because detection of true anomalies is more important than avoiding false anomalies <em>(recall is more important than precision)</em></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3ee63a56c48af1785326edd6f777b87/href">https://medium.com/media/c3ee63a56c48af1785326edd6f777b87/href</a></iframe><p>Excellent! We can move to the piece of code with <strong>exact anomaly detection</strong>.</p><h4>ARIMA with static threshold:</h4><p>For each model, we are going to filter errors with the given threshold and then simply return indexes of unfiltered ones. These unfiltered values we will consider as detected anomalies!</p><p>And of course, we are going to visualize everything that we detected! <em>(By still using the same code from the </em><strong><em>Part I</em></strong><em>)</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/15333b7f7e5cb668fe224c008d22a227/href">https://medium.com/media/15333b7f7e5cb668fe224c008d22a227/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*MzzjghqUF6RjWmdPV7BThQ.png" /><figcaption>Detected anomalies on training data</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*paN62pjNokG7G1t94TPj6Q.png" /><figcaption>Detected anomalies on validation data</figcaption></figure><p>We will leave the metrics until the results part. But here are the code and printed confusion matrices:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5f00d3b76df4380456b4dc90050f3ce/href">https://medium.com/media/e5f00d3b76df4380456b4dc90050f3ce/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*Gaq-uXDIuYRF4dr8-9op3w.png" /><figcaption>Confusion matrix for training data</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da27d917a49615ff69d4e0483acd8f3d/href">https://medium.com/media/da27d917a49615ff69d4e0483acd8f3d/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*B8EW_kiVmYhFcA1KmoClZw.png" /><figcaption>Confusion matrix for validation data</figcaption></figure><p>Yeah, seems not so good <em>(because of many falsely detected anomalies)</em>, but it still catches every anomaly.</p><h4>ARIMA with dynamic threshold:</h4><p>Let’s do the same for the dynamic threshold and see if it can change the situation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b51b03f488558361f0a84ab9313e926/href">https://medium.com/media/8b51b03f488558361f0a84ab9313e926/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*sLcW-kF1NbvczXoIaedlRQ.png" /><figcaption>Detected anomalies on training data</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*UA6FwuDEODAzXvIa8gqizw.png" /><figcaption>Detected anomalies on validation data</figcaption></figure><p>The code for metrics is the same, so we can skip it and take a look at the confusion matrices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*94GcnzkebE4CrnjgEv5SxQ.png" /><figcaption>Confusion matrix for training data</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*KqvbkE1O4b2rB19bbgc9HQ.png" /><figcaption>Confusion matrix for validation data</figcaption></figure><p>Well, these look much better <em>(no more huge amount of incorrectly detected anomalies)</em>! A tough baseline for our neural nets!</p><h4>NN’s anomaly detection</h4><p>For both neural nets, we will provide a unified generic function for anomaly detection.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/368f22eb16a71e94563e86edba0ce573/href">https://medium.com/media/368f22eb16a71e94563e86edba0ce573/href</a></iframe><p>And that’s it! We can effortlessly process the results of neural nets.</p><h4>CNN with static threshold:</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/930f078f73d1ab78cd972a20cc901860/href">https://medium.com/media/930f078f73d1ab78cd972a20cc901860/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*zfMH4Axjyus85tvEyeO7gg.png" /><figcaption>Detected anomalies on training data</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*qUJ__C4_O76w3Wz3bJ2i5g.png" /><figcaption>Detected anomalies on validation data</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03c6ee36e8ff51b95d52034ca8474336/href">https://medium.com/media/03c6ee36e8ff51b95d52034ca8474336/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*vQxOT8EvyRoaH8A1D-WXFA.png" /><figcaption>Confusion matrix for training data</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c7a9650f4724643fb82ebdb3a0a2532/href">https://medium.com/media/7c7a9650f4724643fb82ebdb3a0a2532/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*bdyRMicstYSn_538hOpY4Q.png" /><figcaption>Confusion matrix for validation data</figcaption></figure><p>It seems that our CNN model overfitted — it has an enormous amount of incorrect anomalies — but there is no need to make hasty decisions, it is better to look onto results with the dynamic threshold.</p><h4>CNN with dynamic threshold:</h4><p>And let’s do the same with the dynamic threshold:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1e9c5bab1b8ebf4a41fde0daaa734d5/href">https://medium.com/media/d1e9c5bab1b8ebf4a41fde0daaa734d5/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*jLvCTK5whoEJKQWFs2tgbA.png" /><figcaption>Detected anomalies on training data</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*gwtakEnxkrqbGVqAxEWR5w.png" /><figcaption>Detected anomalies on validation data</figcaption></figure><p>The metrics calculation is still the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*jIxQrV1ZKm0xvxP1gxebdg.png" /><figcaption>Confusion matrix for training data</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*zGStPSeITol_fRDUk1S2Yg.png" /><figcaption>Confusion matrix for validation data</figcaption></figure><p>These results are better than ARIMA’s. We already can say that we didn’t waste time on this!</p><p>And the last model (but certainly not the least) is LSTM.</p><h4>LSTM with static threshold:</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1622f6111364bac6d8f786193ea017b3/href">https://medium.com/media/1622f6111364bac6d8f786193ea017b3/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*JClKJKQcBAdoGr9UcuF-aA.png" /><figcaption>Detected anomalies on training data</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*IwKuBnJsVARRWrbfd_hhNw.png" /><figcaption>Detected anomalies on validation data</figcaption></figure><p>Once again, metrics calculations are identical to CNN’s.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*pgvcwt7PWqFz2GeCH35PQQ.png" /><figcaption>Confusion matrix for training data</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*oJc5cPOi_VMd6U_qf13YDw.png" /><figcaption>Confusion matrix for validation data</figcaption></figure><p>Here we have the same situation as with <a href="http://becominghuman.ai/">CNN</a>, but now we know that the dynamic threshold will reveal the truth!</p><h4>LSTM with dynamic threshold:</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d90d99ea5656f969f4c586d5dcbf383/href">https://medium.com/media/6d90d99ea5656f969f4c586d5dcbf383/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*ukJuKVXhfPvgCIdtIoXM1Q.png" /><figcaption>Detected anomalies on training data</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*Qh271pVzxl84BmNGVkjapg.png" /><figcaption>Detected anomalies on validation data</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*1g2nvcYPT5hrpoyouSChVA.png" /><figcaption>Confusion matrix for training data</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*L17Zi1ww_wIO3HWZnYKD_Q.png" /><figcaption>Confusion matrix for validation data</figcaption></figure><p>And the dynamic evaluation certainly made a near-perfect detector out of our LSTM model.</p><h3>Real-time evaluation with static/dynamic threshold</h3><p>If it is hard to figure out from the code how to use these models in real-life data (<em>and this is normal</em>), so here are some visualizations of the real-time evaluation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UcX-09ll-b8d8Cok" /><figcaption>Evaluation with the static threshold (gif)</figcaption></figure><p>The top chart shows the original data with true anomalies and detected anomalies. On the bottom chart, we can see the error of a model with the purple <strong>static threshold line</strong>.</p><p>And here is the visualization of the same process with the dynamic threshold.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Xp1Et5vFpFN4x8oc" /><figcaption>Evaluation with the dynamic threshold (gif)</figcaption></figure><p>As you can see, the dynamic threshold <strong>adapts</strong> to the dispersion of the error. <strong>That is why the threshold is low when the error deviates a bit and high otherwise.</strong></p><h3>Results of the models</h3><p>Finally, we can compare the metrics to be sure that we correctly put the LSTM onto the first place. We are using F2-score to decide which model is the best. Precision and recall are shown separated for the understanding of weak and strong sides of our models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ywQPuGme4T33ImFGX_GbLQ.png" /><figcaption>Results with the <strong>static </strong>threshold</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*udp47UFHsOACjI09B_M1kQ.png" /><figcaption>Results with the <strong>dynamic </strong>threshold</figcaption></figure><p>However, ARIMA<strong> </strong>performs slightly better with the static<strong> </strong>threshold, and the <strong>neural networks</strong> <strong>outperforms</strong> it with dynamic<strong> </strong>threshold<strong> </strong>— especially <strong>LSTM</strong>.</p><h3>Ultimate Conclusion</h3><p>Lastly, I would like to emphasize that these models can <strong>already be taken for production</strong> with not so much effort.</p><p>Nevertheless, these models are far from their limits and can be enhanced via:</p><ol><li>Increasing the amount of training data</li><li>Adding other metrics such as memory, network, etc</li><li>Combination of LSTM and CNN architectures</li><li>Feature Engineering</li></ol><p>Thank you very much for your attention, I hope that this tutorial gave you some understanding and hints on implementation.</p><p>And don’t stop looking for anomalies!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9_5fnj-jyxxxMhyX" /></figure><h3>About us</h3><p><em>We at </em><a href="http://akvelon.com/"><em>Akvelon Inc</em></a><em> love cutting edge technologies in mobile development, blockchain, big data, </em><a href="https://becominghuman.ai/digital-processes-inspiring-analog-paintings-a358eb7801a0"><em>machine learning</em></a><em>, </em><a href="https://becominghuman.ai/6-ai-subscriptions-to-keep-you-informed-4cfc6cb024a"><em>artificial intelligence</em></a><em>, computer vision, and many others. This article is the result of one of many projects developed in our Office Strategy Labs where we’re testing new technologies and approaches before delivering them to our clients.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bQVKqeqDCOCrLG1A" /><figcaption>Akvelon company official logo</figcaption></figure><p><em>If you would like to work with our strong Akvelon team — </em><a href="http://akvelon.com/careers/"><em>please see our open positions</em></a><em>.</em></p><p><strong><em>Designed and implemented with love in Akvelon: <br></em></strong><em>Team Lead — </em><a href="https://www.linkedin.com/in/artur-khanin/"><em>Artur Khanin</em></a><em><br>Delivery Manager — </em><a href="https://www.linkedin.com/in/volynkin/"><em>Sergei Volynkin</em></a><em><br>Technical Account Manager — </em><a href="https://www.linkedin.com/in/maxkostin/"><em>Max Kostin</em></a><em><br>ML Engineers — </em><a href="https://www.linkedin.com/in/irina-nikolaeva-5a26a11b4/"><em>Irina Nikolaeva</em></a><em>, Rustem Saitgareev</em></p><h3>Don’t forget to give us your 👏 !</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/0*2lvCls4yjxVMfZSR" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F8f5f8b%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2F8f5f8b&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/c43026df6fee7cdb1aab8aaf916125ea/href">https://medium.com/media/c43026df6fee7cdb1aab8aaf916125ea/href</a></iframe><figure><a href="https://becominghuman.ai/artificial-intelligence-communities-c305f28e674c"><img alt="" src="https://cdn-images-1.medium.com/max/255/1*2f7OqE2AJK1KSrhkmD9ZMw.png" /></a></figure><figure><a href="https://upscri.be/8f5f8b"><img alt="" src="https://cdn-images-1.medium.com/max/255/1*v-PpfkSWHbvlWWamSVHHWg.png" /></a></figure><figure><a href="https://becominghuman.ai/write-for-us-48270209de63"><img alt="" src="https://cdn-images-1.medium.com/max/255/1*Wt2auqISiEAOZxJ-I7brDQ.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f72e800e15e2" width="1" height="1" alt=""><hr><p><a href="https://becominghuman.ai/time-series-and-how-to-detect-anomalies-in-them-part-iii-f72e800e15e2">Time Series and How to Detect Anomalies in Them — Part III</a> was originally published in <a href="https://becominghuman.ai/">Becoming Human: Artificial Intelligence Magazine</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 and How to Detect Anomalies in Them — Part II]]></title>
            <link>https://becominghuman.ai/time-series-and-how-to-detect-anomalies-in-them-part-ii-bde9e69d0aaf?source=rss-445fbfc6e8c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/bde9e69d0aaf</guid>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[anomaly-detection]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Khanin Artur]]></dc:creator>
            <pubDate>Wed, 11 Nov 2020 10:01:53 GMT</pubDate>
            <atom:updated>2020-12-01T15:47:58.785Z</atom:updated>
            <content:encoded><![CDATA[<h3>Time Series and How to Detect Anomalies in Them — Part II</h3><h4>Implementation of ARIMA, CNN, and LSTM</h4><p><em>Hello fellow reader (and hello again if you read </em><a href="https://khaninartur.medium.com/time-series-and-how-to-detect-anomalies-in-them-part-i-7f9f6c2ad32e"><em>the first part of this article series</em></a><em>). My name is Artur, and I am the head of the </em><a href="https://becominghuman.ai/cheat-sheets-for-ai-neural-networks-machine-learning-deep-learning-big-data-678c51b4b463"><em>Machine Learning</em></a><em> team in </em><a href="https://kzn.akvelon.com/"><em>Akvelon’s Kazan office</em></a><em> and you are about to read the second part of the tutorial for anomaly detection in a time series.</em></p><p><em>During our own research, we’ve managed to gather a lot of information from tiny useful pieces all over the internet and we don’t want this knowledge to be lost!</em></p><p><em>We already dove into theory and data preparation in Part I:</em></p><ul><li><a href="https://khaninartur.medium.com/time-series-and-how-to-detect-anomalies-in-them-part-i-7f9f6c2ad32e"><strong><em>Part I — Intro to Anomaly Detection and Data Preparation</em></strong></a></li></ul><p><em>And here is the shortcut to the next chapter:</em></p><ul><li><a href="https://khaninartur.medium.com/time-series-and-how-to-detect-anomalies-in-them-part-iii-f72e800e15e2"><strong><em>Part III — Eventually easier than it seemed</em></strong></a></li></ul><p><em>We reuse our code so if something seems unclear, consider visiting the previous part once more.</em></p><p><em>Alright then, let’s move on!</em></p><h3>Trending AI Articles:</h3><blockquote><a href="https://becominghuman.ai/how-to-automatically-deskew-straighten-a-text-image-using-opencv-a0c30aed83df">1. How to automatically deskew (straighten) a text image using OpenCV</a></blockquote><blockquote><a href="https://becominghuman.ai/explaining-yolov4-a-one-stage-detector-cdac0826cbd7">2. Explanation of YOLO V4 a one stage detector</a></blockquote><blockquote><a href="https://becominghuman.ai/5-best-artificial-intelligence-courses-for-beginners-in-2020-38db08617b12">3. 5 Best Artificial Intelligence Online Courses for Beginners in 2020</a></blockquote><blockquote><a href="https://becominghuman.ai/a-non-mathematical-guide-to-the-mathematics-behind-machine-learning-4b71d9e16dcd">4. A Non Mathematical guide to the mathematics behind Machine Learning</a></blockquote><p>Just to briefly remind the tools that we use:</p><ul><li><a href="https://jupyter.org/"><strong>Jupyter Notebooks</strong></a> environment for the implementation of the models</li><li><a href="https://scikit-learn.org/stable/"><strong>Scikit-learn</strong></a> for some data preprocessing</li><li><a href="https://www.statsmodels.org/stable/index.html"><strong>Statsmodel</strong></a> library for the ARIMA model</li><li><a href="https://pytorch.org/"><strong>PyTorch</strong></a> for neural networks</li><li><a href="https://plotly.com/python/"><strong>Plotly</strong></a> for plots and graphs</li></ul><h3>Implemented Approaches</h3><p>Amongst all possible approaches listed in <strong>Part I</strong>, we chose these suitable ones:</p><ol><li><a href="https://en.wikipedia.org/wiki/Autoregressive_integrated_moving_average"><strong>ARIMA</strong></a> statistical model — <em>predicts next value</em></li><li><a href="https://en.wikipedia.org/wiki/Convolutional_neural_network"><strong>Convolutional Neural Network</strong></a> — <em>predicts next value</em></li><li><a href="https://en.wikipedia.org/wiki/Long_short-term_memory"><strong>Long Short-Term Memory Neural Network</strong></a> — <em>reconstructs current value</em></li></ol><p>Let’s start with the ARIMA model.</p><h3>ARIMA Statistical Model</h3><p>ARIMA is an autoregression statistical model that optimizes <em>coefficients</em> (also known as <em>hyperparameters</em>) during training. Then these hyperparameters are used in inference.</p><p>It is logical that during nighttime and daytime CPU usage may vary which is totally normal behavior. To consider this behavior, we can think of night and day times as separate “seasons”. And because of this, we will use <a href="https://www.statsmodels.org/dev/generated/statsmodels.tsa.statespace.sarimax.SARIMAX.html">SARIMAX</a> — which is just a modified ARIMA model with the same idea that adds seasonal causes into ARIMA. SARIMAX will deal with the separation of seasons for us, so we don’t have to provide anything else except our dataset.</p><p>Here you can see the schema for the training process of SARIMAX:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ECn7LxifmlcGGdLE" /><figcaption>Training process and architecture of the SARIMAX model</figcaption></figure><p>The model tries to predict the next value using the current one and then it compares the predicted result with actual value.</p><h4>SARIMAX Implementation</h4><p>Implementation of this model is not so interesting since all we can play with are hyperparameters for this model. To find the model that produces the best predictions we will iterate over hyperparameters and will pick the combination.</p><figure><a href="https://aijobsboard.com/?fbclid=IwAR0GcsLs8A6CFM-fynrZMM3sTgo_Zpbto2CjglJm0Dmi6otC6YWc7CDFpQk"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dAlwXfVrtYspdCzmC8iADw.png" /></a><figcaption>Artificial Intelligence Jobs</figcaption></figure><p>All we need is just the model itself from the statsmodels.api package and product function from itertools for iteration over hyperparameters.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1da777dcaca938cc6df63bb4c9a57d0/href">https://medium.com/media/c1da777dcaca938cc6df63bb4c9a57d0/href</a></iframe><p>And also, it would be a good idea is to write predictions of the best model into the new column of the <em>DataFrame </em>with initial data to ease further metrics calculation.</p><p>Here is the code to pick the best model and write its predictions into training and validation DataFrames:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74bc1d2be5e831f583cd44a617d34846/href">https://medium.com/media/74bc1d2be5e831f583cd44a617d34846/href</a></iframe><p>At this very moment, we have the best set of parameters and predictions for both training and validation data. To understand how good our model is, we should calculate different metrics such as precision, recall, and F-score. We will fully cover the metrics theme in <strong>Part III, </strong>however, we already can visualize the predictions and see how our model performs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*rz3-aUwoUeuXcn21OxhEcg.png" /><figcaption>ARIMA’s predictions on training data</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*VgR-cD-392YX2V1zA7vf-Q.png" /><figcaption>ARIMA’s prediction on validation data</figcaption></figure><p><em>Note: one important thing about ARIMA is that </em><strong><em>time for training and optimizing</em></strong><em> the coefficients </em><strong><em>takes ~10 times longer</em></strong><em> than it takes to complete the same </em><strong><em>training of both neural networks</em></strong><em>.</em></p><h3>Convolutional Neural Network</h3><p>Convolutional neural networks are usually applied to image-connected tasks, such as image classification, segmentation, etc. But the purpose of the <strong>convolutional layers</strong> is to <strong>find and recognize patterns, </strong>which is totally applicable for analysis of the CPU utilization metric.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6Yc-n4kTLQ77FQDx" /><figcaption>The architecture of the CNN model</figcaption></figure><p>We use <a href="https://arxiv.org/abs/1512.03385"><strong>ResNet</strong></a><strong>-ish</strong> architecture <em>(which has already become the best type of architecture to use in CNNs)</em> that consists of <strong>Residual Blocks</strong> (ResBlocks). The idea behind ResBlock is simple yet efficient — add the input of the block to its output. This idea allows neural networks to “remember” each intermediate result and take it into account in the final layers.</p><p>CNN tries to predict the next value using <strong>some number of previous values</strong>. In our case, this number equals <strong><em>10</em></strong>, but of course, it may be configured.</p><h4>CNN Implementation</h4><p>Before coding CNN itself we should make a few additional preparations of the data. In general, since we use PyTorch, the data should be wrapped into something compatible with PyTorch’s Dataset. This may be as well the <strong>class inherited from the </strong><strong>Dataset class</strong>, a <strong>generator,</strong> or even a simple <strong>iterator</strong>.<br>We will use the <strong>class</strong> option due to its readability and implicit PyTorch’s enhancements.</p><p>Once again, there are some necessary imports for Dataset creation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8c4d95efa78dff91cd329279c9558a7/href">https://medium.com/media/c8c4d95efa78dff91cd329279c9558a7/href</a></iframe><p>Let’s recall the task for CNN. We want the model to predict the next value using some amount of the previous values. This means that our Dataset class should contain each item in a specific format — divided into 2 parts:</p><ol><li>n values in sequential order that the model uses for prediction <em>(to easily change the amount of these values, we make </em><em>n the parameter)</em></li><li>1 value that goes next after n values from the first part of the item</li></ol><p>Coming back to the implementation — actually, it is very easy to wrap data with our custom class that just inherits from PyTorch’s Dataset. It should implement only __init__, __len__ and __getitem__ methods:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/899cd27e5adab021822302c0d85f5867/href">https://medium.com/media/899cd27e5adab021822302c0d85f5867/href</a></iframe><p>Now it is the right time to define the number of previous values that are to be used for the prediction of the next one. And, of course, wrap the data with our CPUDataset class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3f66cb2c112a682d2d26ac6c498622a/href">https://medium.com/media/f3f66cb2c112a682d2d26ac6c498622a/href</a></iframe><p>Here comes the best part — the <strong>definition of the neural network</strong>.</p><p>Let’s rewind how <strong>Residual block</strong> looks like in regular <strong>ResNets. </strong>It consists of:</p><ul><li><a href="https://setosa.io/ev/image-kernels/">Convolution</a> layer</li><li><a href="https://en.wikipedia.org/wiki/Batch_normalization">Batch Normalization</a></li><li><a href="https://en.wikipedia.org/wiki/Rectifier_(neural_networks)">ReLU</a> activation</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/0*tUGzivpnmN7i8p8V.png" /><figcaption>Residual Block from the regular ResNet</figcaption></figure><p>The only difference between the regular ResBlock and ours is that we removed the last ReLU activation — it turned out that in our case CNN without the last ReLU in ResBlock generalizes better.</p><p>Many <em>Residual Blocks</em> bring twice more <em>Convolution + Batch Norm. (+ ReLU)</em> combinations. So, such a combination is a good starting point to define.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c8c2bc08935f2d08b458c3a0e111c58/href">https://medium.com/media/4c8c2bc08935f2d08b458c3a0e111c58/href</a></iframe><p>In each <em>Residual Block, </em>we should remember about the case of changing the number of output channels <em>(when </em><em>in_feat != out_feat). </em>One possible way to synchronize the number of channels is to multiply or cut them. However, there is another greater way — we can handle this using a <strong>1x1 convolution without padding</strong>. This trick not only allows us to fit layer input into layer output but also adds more reasonable computations for the neural network.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9732ff47057a7c52e4f4e27dc54a1fb4/href">https://medium.com/media/9732ff47057a7c52e4f4e27dc54a1fb4/href</a></iframe><p>It is widely used to finish the base block of the convolutional net with <a href="https://www.machinecurve.com/index.php/2020/01/30/what-are-max-pooling-average-pooling-global-max-pooling-and-global-average-pooling/"><em>Max Pooling </em><strong><em>or</em></strong><em> Average Pooling</em></a> depending on the task. Here comes another useful trick for Convolutional Neural Nets <em>(thanks to </em><a href="https://en.wikipedia.org/wiki/Jeremy_Howard_(entrepreneur)"><em>Jeremy Howard</em></a><em> and his fantastic </em><a href="https://www.fast.ai/"><em>fast.ai</em></a><em> library) — </em><strong>concatenate <em>Average Pooling</em> </strong>and<strong> <em>Max Pooling. </em></strong>It allows our neural net to decide, which approach is better for the current task and how to combine them to get better results:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c56c4c1651283565aee516d2615d470f/href">https://medium.com/media/c56c4c1651283565aee516d2615d470f/href</a></iframe><p>And here is our resulting <strong>CNN class </strong>that is made of the building blocks that we implemented above:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1cd859b83fad1406b9159accde8cbe1/href">https://medium.com/media/e1cd859b83fad1406b9159accde8cbe1/href</a></iframe><p>Now we have the definition of CNN and can create a randomly initialized model, pass items from our Datasets, and check that data shapes are correct and that no exceptions are raised.</p><p>After the model is defined, we can move to the <strong>training loop. </strong>This loop is quite general and may be used with the majority of the neural nets:</p><ul><li>Loop over the epochs</li><li>Loop over the training part of the dataset making optimization steps</li><li>Loop over the validation part of the dataset</li><li>Calculate losses for each epoch</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/754afa3c82270c8c3429a2d93aeb376a/href">https://medium.com/media/754afa3c82270c8c3429a2d93aeb376a/href</a></iframe><p>Alright, we are almost ready to start fitting our CNN model. The only thing left is to initialize the <strong>model, dataloaders, and training parameters.</strong></p><p>Here we use:</p><ul><li><a href="https://pytorch.org/docs/stable/optim.html#torch.optim.Adam"><strong>Adam</strong></a> optimizer — one of the best general optimizers. <br>If you have no idea which type of optimizer to pick — use Adam. Other optimizers such as<em> SGD, RMSProp</em>, etc. may converge better in some specific situations, but it is not our case.</li><li><strong>Learning rate</strong> scheduler with <a href="https://pytorch.org/docs/stable/optim.html#torch.optim.lr_scheduler.OneCycleLR"><strong>One Cycle</strong></a> policy to speed up the convergence of the neural net. <br>Instead of keeping the learning rate with the same value across all iterations, we can change it. There a lot of policies such as <em>Cosine, Factor, Multi-Factor, Warmup, etc. </em>We choose <em>One Cycle </em>policy because it seems logical for us — warm-up learning rate for the ~1/3 of the iterations and then gradually decrease it.</li><li><a href="https://pytorch.org/docs/stable/nn.html#torch.nn.MSELoss"><strong>Mean Squared Error</strong></a> loss criterion as we described in Part I.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f6841ea33ce17b74dd0a1c00972b774/href">https://medium.com/media/6f6841ea33ce17b74dd0a1c00972b774/href</a></iframe><p>Eventually, we can run the most desired line of code — execution of the training process:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1efc96384d7e4e2615a611546b1b4d22/href">https://medium.com/media/1efc96384d7e4e2615a611546b1b4d22/href</a></iframe><p>And see the losses of our model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e159dd94fa30de8cda7c5b10121e617d/href">https://medium.com/media/e159dd94fa30de8cda7c5b10121e617d/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*H2VgAmRBfruq6DrAKxnrCw.png" /><figcaption>Loss vs Epoch graph</figcaption></figure><p>We always want both training and validation losses to move down because this behavior means that the model has learned something useful about our data. If any loss eventually moves up, then the model can’t figure out how to solve the task, and you should change or modify it.</p><p>These losses on the picture above seem pretty nice because they eventually move down, but it is an early assumption (their niceness) since we haven’t checked the predictions yet.</p><p>At this very moment, we can easily calculate them with our model:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/acacb0400c0481c1d7e5e478bdff92af/href">https://medium.com/media/acacb0400c0481c1d7e5e478bdff92af/href</a></iframe><p>And take a look:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*OolvHtThtMDnfJZu6QCH4Q.png" /><figcaption>CNN’s predictions on training data</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*YdYHKobDqKu_9zMgnKuPGA.png" /><figcaption>CNN’s predictions on validation data</figcaption></figure><p>Just to be clear, <strong>we don’t really want our models to perfectly predict values</strong>, as such perfection would destroy the whole idea of the anomaly detection process <em>(described in “Saying what we want from our models out loud” in Part I)</em>. That’s why when we look at plots, <strong>we want to see our model catch the main trend, not the particular values</strong>.</p><h3>Long Short-Term Memory Neural Network</h3><p>LSTM neural networks have an <strong>internal memory state</strong> that allows them to <strong>remember its’ previous evaluations</strong> that make this architecture the perfect candidate for time series anomaly detection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XdJtxsGIzylANIuR" /><figcaption>LSTM architecture</figcaption></figure><p>Unlike the previous two models, this neural network tries to reconstruct the current value using the value itself. It may seem trivial, but this approach has <strong>extremely good results</strong> in anomaly detection.</p><h4>LSTM Implementation</h4><p>We can simplify the wrapping of data into the Dataset from CNN because we <strong>need </strong>the very<strong> same output as input</strong> for reconstruction. That is why we get rid of the first part of each item and just keep 1 value. We also should consider that LSTM models usually can’t be fed with the whole sequence at once <em>(because of the memory consumption for the whole sequence)</em>— we have to separate data accordingly into <strong>partial sequences</strong> to train. Moreover, as training with the whole sequence may reduce the model’s ability to generalize, it may simply get used to the data this way.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe785e1354f1eda3e7ab27e46a72694a/href">https://medium.com/media/fe785e1354f1eda3e7ab27e46a72694a/href</a></iframe><p>The <strong>definition of the LSTM</strong> neural net is much <strong>easier</strong> than the CNN one. PyTorch already has an implemented class of LSTM cells that we can use.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e91b42b2f9711e436cdf75f5deec6aff/href">https://medium.com/media/e91b42b2f9711e436cdf75f5deec6aff/href</a></iframe><p>Considering that <strong>we changed the Dataset class</strong> a bit we also should<strong> change the training loop </strong>to fit data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95a1102d20b80b3613fd8eb8a453a604/href">https://medium.com/media/95a1102d20b80b3613fd8eb8a453a604/href</a></iframe><p>In LSTM case we also use:</p><ul><li><strong>Adam</strong> optimizer</li><li>Learning rate scheduler with <strong>One Cycle</strong> policy</li><li><strong>Mean Squared Error</strong> loss criterion</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/091e325af5e0617dd0c35a9dd2a7ad46/href">https://medium.com/media/091e325af5e0617dd0c35a9dd2a7ad46/href</a></iframe><p>One more time we face the most desired line of the code with its result:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb5d23db28a9802eb7d1b71d6a7f0113/href">https://medium.com/media/bb5d23db28a9802eb7d1b71d6a7f0113/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*KxRMut1iYCjZKXdwgGcgog.png" /><figcaption>Loss vs Epoch graph</figcaption></figure><p>Because of the training with partial sequences, we can’t directly send the Dataset instance to get the results, but we certainly can extract the entire sequences from DataFrames:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c7616df6a3f21f364089d62fa7d352f/href">https://medium.com/media/5c7616df6a3f21f364089d62fa7d352f/href</a></iframe><p>And then we calculate the predictions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c913ba774adf7254c4fc75ad4e4ba34/href">https://medium.com/media/9c913ba774adf7254c4fc75ad4e4ba34/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*Tv96iFU28sANM5UJNAjNrw.png" /><figcaption>LSTM’s predictions on training data</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*NFBywgPta12J4GoaEv-vlw.png" /><figcaption>LSTM’s predictions on validation data</figcaption></figure><h3>Another intermediate conclusion</h3><p>Terrific, we have 3 trained models and their results on our dataset!</p><p>The toughest part is behind us and now we are prepared to make our final steps towards anomaly detection. In the last chapter, we will do some extra preparations and reveal the detection process along with its results.</p><p>If you want to refresh some theory or data preprocessing, don’t be shy and go to the first part:</p><ul><li><a href="https://khaninartur.medium.com/time-series-and-how-to-detect-anomalies-in-them-part-i-7f9f6c2ad32e"><strong>Part I — Intro to Anomaly Detection and Data Preparation</strong></a></li></ul><p>Otherwise, the third part awaits:</p><ul><li><a href="https://khaninartur.medium.com/time-series-and-how-to-detect-anomalies-in-them-part-iii-f72e800e15e2"><strong>Part III — Eventually easier than it seemed</strong></a></li></ul><h3>About us</h3><p><em>We at </em><a href="http://akvelon.com/"><em>Akvelon Inc</em></a><em> love cutting edge technologies in mobile development, blockchain, big data, </em><a href="http://becominghuman.ai/"><em>machine learning</em></a><em>, </em><a href="https://becominghuman.ai/making-a-simple-neural-network-2ea1de81ec20"><em>artificial intelligence</em></a><em>, computer vision, and many others. This article is the result of one of many projects developed in our Office Strategy Labs where we’re testing new technologies and approaches before delivering them to our clients.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bQVKqeqDCOCrLG1A" /><figcaption>Akvelon company official logo</figcaption></figure><p><em>If you would like to work with our strong Akvelon team — </em><a href="http://akvelon.com/careers/"><em>please see our open positions</em></a><em>.</em></p><p><strong><em>Designed and implemented with love in Akvelon:<br></em></strong><em>Team Lead — </em><a href="https://www.linkedin.com/in/artur-khanin/"><em>Artur Khanin</em></a><em><br>Delivery Manager — </em><a href="https://www.linkedin.com/in/volynkin/"><em>Sergei Volynkin</em></a><em><br>Technical Account Manager — </em><a href="https://www.linkedin.com/in/maxkostin/"><em>Max Kostin</em></a><em><br>ML Engineers — </em><a href="https://www.linkedin.com/in/irina-nikolaeva-5a26a11b4/"><em>Irina Nikolaeva</em></a><em>, Rustem Saitgareev</em></p><h3>Don’t forget to give us your 👏 !</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/0*2lvCls4yjxVMfZSR" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F8f5f8b%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2F8f5f8b&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/c43026df6fee7cdb1aab8aaf916125ea/href">https://medium.com/media/c43026df6fee7cdb1aab8aaf916125ea/href</a></iframe><figure><a href="https://becominghuman.ai/artificial-intelligence-communities-c305f28e674c"><img alt="" src="https://cdn-images-1.medium.com/max/255/1*2f7OqE2AJK1KSrhkmD9ZMw.png" /></a></figure><figure><a href="https://upscri.be/8f5f8b"><img alt="" src="https://cdn-images-1.medium.com/max/255/1*v-PpfkSWHbvlWWamSVHHWg.png" /></a></figure><figure><a href="https://becominghuman.ai/write-for-us-48270209de63"><img alt="" src="https://cdn-images-1.medium.com/max/255/1*Wt2auqISiEAOZxJ-I7brDQ.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bde9e69d0aaf" width="1" height="1" alt=""><hr><p><a href="https://becominghuman.ai/time-series-and-how-to-detect-anomalies-in-them-part-ii-bde9e69d0aaf">Time Series and How to Detect Anomalies in Them — Part II</a> was originally published in <a href="https://becominghuman.ai/">Becoming Human: Artificial Intelligence Magazine</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 and How to Detect Anomalies in Them — Part I]]></title>
            <link>https://becominghuman.ai/time-series-and-how-to-detect-anomalies-in-them-part-i-7f9f6c2ad32e?source=rss-445fbfc6e8c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f9f6c2ad32e</guid>
            <category><![CDATA[anomaly-detection]]></category>
            <category><![CDATA[data-preprocessing]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[time-series-data]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Khanin Artur]]></dc:creator>
            <pubDate>Mon, 02 Nov 2020 10:44:29 GMT</pubDate>
            <atom:updated>2020-12-01T15:48:24.314Z</atom:updated>
            <content:encoded><![CDATA[<h3>Time Series and How to Detect Anomalies in Them — Part I</h3><h4>Intro to Anomaly Detection and Data Preparation</h4><p><em>Hello fellow reader, my name is Artur. I am the head of the</em><a href="http://becominghuman.ai/"><em> Machine Learning</em></a><em> team in </em><a href="https://akvelon.com/"><em>Akvelon</em></a><em> and you are about to read the tutorial for anomaly detection in time series.</em></p><p><em>During our research, we’ve managed to gather a lot of information from tiny useful pieces all over the internet and we don’t want this knowledge to be lost! That’s exactly why you can exhale and dive into these end-to-end working articles.</em></p><p><em>The next part of the series is already published! Check it out after this one (or if you want to go straight to the models):</em></p><ul><li><a href="https://khaninartur.medium.com/time-series-and-how-to-detect-anomalies-in-them-part-ii-bde9e69d0aaf"><strong><em>Part II — Implementation of ARIMA, CNN, and LSTM</em></strong></a></li><li><a href="https://khaninartur.medium.com/time-series-and-how-to-detect-anomalies-in-them-part-iii-f72e800e15e2"><strong><em>Part III — Eventually easier than it seemed</em></strong></a></li></ul><p><em>Let’s get this started!</em></p><figure><a href="https://aijobsboard.com/?fbclid=IwAR0GcsLs8A6CFM-fynrZMM3sTgo_Zpbto2CjglJm0Dmi6otC6YWc7CDFpQk"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dAlwXfVrtYspdCzmC8iADw.png" /></a><figcaption>Artificial Intelligence Jobs</figcaption></figure><h3>First of all, let’s define what an anomaly detection problem is in general</h3><p><a href="https://en.wikipedia.org/wiki/Anomaly_detection"><em>Anomaly Detection</em></a><em> </em>— is the identification of rare items, events, or patterns that significantly differ from the majority of the <a href="https://becominghuman.ai/how-can-we-improve-the-quality-of-our-data-61b55c9063d1">data</a>.</p><p>Well, basically, the anomaly is something that <em>makes no or little sense</em> when you look at it <em>from the high ground</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*S25Gm8bakWRqZ6fZ" /><figcaption>“<strong>It’s over, Anakin. I have the high ground.</strong>” scene from <strong>Star Wars</strong>: <strong>Episode III</strong> — Revenge of the Sith</figcaption></figure><p>And it brings us to the fact that anomalies are<strong> extremely context-dependent</strong>. And also, different people may consider different pieces of data as anomalies.</p><h3>Why do we bother finding anomalies?</h3><p>Imagine the situation — you are the Co-founder and CTO in a small startup company. Your company has 1 web application and every single client really matters for success. One day a smart client found the backdoor in your app and started to send direct large queries to your database. The CPU usage has changed because of these queries but it stayed in normal boundaries.</p><p>The data may leak for a very long period of time, and when somebody else will find this backdoor and make it public, it may cause <em>enormous damage</em>. And this situation is not about the code quality, there is always the risk that mistakes and backdoors may appear in your app and codebase. This situation is about the drawing of your attention (as CTO and one of the main decision-makers) to reveal the issue and save your business.</p><h3>Trending AI Articles:</h3><blockquote><a href="https://becominghuman.ai/how-to-automatically-deskew-straighten-a-text-image-using-opencv-a0c30aed83df">1. How to automatically deskew (straighten) a text image using OpenCV</a></blockquote><blockquote><a href="https://becominghuman.ai/explaining-yolov4-a-one-stage-detector-cdac0826cbd7">2. Explanation of YOLO V4 a one stage detector</a></blockquote><blockquote><a href="https://becominghuman.ai/5-best-artificial-intelligence-courses-for-beginners-in-2020-38db08617b12">3. 5 Best Artificial Intelligence Online Courses for Beginners in 2020</a></blockquote><blockquote><a href="https://becominghuman.ai/a-non-mathematical-guide-to-the-mathematics-behind-machine-learning-4b71d9e16dcd">4. A Non Mathematical guide to the mathematics behind Machine Learning</a></blockquote><p>Generally speaking, if you can <strong>notice</strong> any <strong>variations</strong> of your system from its normal behavior, you can find out the reasons for such behavior, uncover and eliminate hidden issues and find new non-obvious opportunities.</p><p>However, it is quite expensive to hire someone for monitoring all your metrics 24/7. That is why we want to detect unexpected variations <em>(anomalies) </em>automatically, inexpensively <em>(also in terms of damage)</em>, and quickly.</p><p>Alright, now we know <strong>why</strong> we want to solve this problem. But before moving to the <strong>how</strong> part, we need to distinguish between <strong>generic</strong> anomalies and anomalies in <strong>time series</strong>. This will help us to understand what types of techniques are more appropriate for our problem.</p><h4>Generic anomaly detection</h4><p>Here is a generic example, which illustrates the <a href="https://en.wikipedia.org/wiki/Cluster_analysis">cluster-based</a> approach. Shortly speaking, the cluster-based approaches try to group similar data in clusters and consider values that don’t fit in these clusters as anomalies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/0*pdnYUPzsp3xjf3E8" /><figcaption>Example of 2D data with anomalies found via clustering</figcaption></figure><p>Although this picture illustrates some specific approach, <strong>the idea is the same </strong>across any technique used. We have some values with no particular order and we try to figure out which values seem uncommon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/0*rSlx5NWGQICliXzW.jpg" /></figure><h4>Time series anomaly detection</h4><p>On the other hand, when we talk about anomaly detection for time series, the value itself may not seem suspicious, but <strong>it becomes suspicious due to the time</strong> when it appears and the <strong>values before</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*bmXOsrnZgb4FAdMU" /><figcaption>Example of the time series with an anomaly</figcaption></figure><p>For example, it is okay, when the CPU load of some application is about 20%, but it seems strange when the load unexpectedly jumps to 80%. And one more important thing is that the load level around 80% after this jump is not suspicious anymore. That is why some threshold warning values can’t handle such complex situations.</p><p><strong>The moment of the jump</strong> <strong>is way more important than the stabilization after it</strong>.</p><p>When you’re dealing with the anomalies in general, you can shuffle them into any order and the anomalies will still be the same. If a person bought 1000 packs of toilet paper, you probably will always say that this seems anomalous.</p><p>When you’re dealing with the anomalies in time series, the order of data is important. If nobody ever bought a single pack of toilet paper in a particular store, and then a person bought just 1 pack — you already should consider it as an anomaly.</p><p>Cool, now we are ready to move on to the <strong>how </strong>part!</p><h3>How to find anomalies</h3><h4>The general idea</h4><p>One of the most common and the most successful yet approaches can be described as:</p><blockquote>Find out what is normal and if something deviates too much from it — this is an anomaly.</blockquote><p>And almost all of the approaches listed below try to achieve this one way or another.</p><h4>Possible Approaches</h4><p>Here are the most common approaches to use for anomaly detection:</p><ul><li><a href="https://en.wikipedia.org/wiki/Statistics">Statistical Methods</a></li><li>Deviations from <a href="https://en.wikipedia.org/wiki/Association_rule_learning">association rules</a> and frequent itemsets</li><li>One-class <a href="https://en.wikipedia.org/wiki/Support_vector_machines">Support Vector Machine</a></li><li><a href="https://en.wikipedia.org/wiki/Cluster_analysis">Clustering-based techniques</a> (<a href="https://en.wikipedia.org/wiki/K-means_clustering">k-means</a>)</li><li>Density-based techniques (<a href="https://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm">k-nearest neighbor</a>, <a href="https://en.wikipedia.org/wiki/Local_outlier_factor">local outlier factor</a>)</li><li><a href="https://en.wikipedia.org/wiki/Autoencoder#Anomaly_Detection">Autoencoders</a> and replicators (<a href="https://en.wikipedia.org/wiki/Neural_network">Neural Networks</a>)</li></ul><p>These are just some of the popular techniques amongst the <a href="https://en.wikipedia.org/wiki/Anomaly_detection">possible ones</a>.</p><h3>How we find anomalies</h3><p>Of course, every technique listed above can be used for our purposes. But nowadays, neural networks are in trend and <strong>outperform</strong> classical algorithms almost everywhere. After our research, we decided to try 2 types of neural networks and took 1 classic model as a baseline for comparison. And here is why:</p><ul><li><a href="https://en.wikipedia.org/wiki/Autoregressive_integrated_moving_average"><strong>ARIMA</strong></a><strong> statistical model </strong>as a baseline — this is the classic auto-regression model that is made exactly for the time series</li><li><a href="https://en.wikipedia.org/wiki/Convolutional_neural_network"><strong>Convolutional Neural Network</strong></a><strong> </strong>— such neural networks are usually used for image processing, but if you dig deeper into them, you may find that they actually look for the patterns in the images. Our time series also consists of patterns</li><li><a href="https://en.wikipedia.org/wiki/Long_short-term_memory"><strong>Long Short-Term Memory Neural Network</strong></a> — this type was designed especially for time-related data</li></ul><p>And for the development we chose this set of tools:</p><ul><li><a href="https://jupyter.org/"><strong>Jupyter Notebooks</strong></a> environment for the implementation of the models.<br>We prefer using <em>Jupyter Notebooks </em>instead of regular editors (such as JetBrains’ PyCharm) since Notebooks save code into separate cells, which can also be run in any order you need. Most editors use .py files and execute the whole bunch of code every time you run it — this makes the code modification process terrifying <em>(sometimes training of a model consumes hours)</em> because you have to wait to see the outcome of your simple print function at the end of your code. Thus, cells of Notebooks provide flexibility for <a href="https://becominghuman.ai/digital-processes-inspiring-analog-paintings-a358eb7801a0">Machine Learning</a> development and make it easier to try something out.</li><li><a href="https://scikit-learn.org/stable/"><strong>Scikit-learn</strong></a> for some data preprocessing.<br>Scikit-learn has many tools that are already implemented. There are no big secrets behind the data preprocessing, and we don’t really want to waste our time implementing them from scratch, optimizing them for large amounts of data, etc. This is where Scikit-learn comes in handy.</li><li><a href="https://www.statsmodels.org/stable/index.html"><strong>Statsmodel</strong></a> library for ARIMA model.<br>This library is used with the same motivation as scikit-learn. <em>No big secrets behind ARIMA; already implemented tool; no need to waste time.</em></li><li><a href="https://pytorch.org/"><strong>PyTorch</strong></a> for neural networks.<br>It is one of the most used libraries for the construction of neural nets. The alternative is, of course, <a href="https://www.tensorflow.org/"><em>Tensorflow</em></a><em>. </em>They both have pros and cons and we choose <em>PyTorch </em>because it is designed for eager execution that is way more flexible. On the other hand, <em>Tensorflow </em>is designed for building the whole calculation graph with the training/validation phase, metrics calculation, etc., meaning that a lot of stuff has to be done before. For example, you may face some syntax error at the very beginning of a model definition right after you finish coding the whole model.</li><li><a href="https://plotly.com/python/"><strong>Plotly</strong></a> for plots and graphs.<br>When we just started, we decided to use <a href="https://matplotlib.org/"><em>Matplotlib</em></a>, which is used almost everywhere for plots and graphs. However, we’ve noticed a new player — plotly — and it turned out that it plots prettier and more informative graphs with less code.</li></ul><p>Before diving into models architecting and implementation we should load the data and inspect it.</p><h4>Dataset Loading</h4><p>First of all, we should choose the dataset for our experiments. The internet is full of different datasets, for example, you can use <a href="https://datasetsearch.research.google.com/">Dataset Search</a> from Google to find the appropriate one. We already have the perfect repository for time series anomaly detection — <a href="https://github.com/numenta/NAB"><strong>The Numenta Anomaly Benchmark</strong></a><strong> </strong>(NAB)<strong>:</strong></p><ul><li>NAB contains many files with different metrics from different places. It is in the nature of metrics — being ordered in time and thus, being one of the best candidates for time series anomaly detection.</li><li>From NAB we decided to use Real <strong>CPU utilization</strong> from AWS Cloudwatch metrics for Amazon Relational Database Service. These metrics are saved in csv format and the exact timestamps of anomalies in them <em>(let’s call it </em><strong><em>labels</em></strong><em>) </em>are saved in json format. You may use any other metric that you like.</li><li>Just to clarify — these anomalies that we see in the dataset were marked as anomalies by the creators.</li></ul><p>Here are direct links to the files in NAB that we use, you can download them, take a look and play around:</p><ul><li><a href="https://github.com/numenta/NAB/blob/master/data/realAWSCloudwatch/rds_cpu_utilization_cc0c53.csv">Link to <strong>training data</strong></a></li><li><a href="https://github.com/numenta/NAB/blob/master/data/realAWSCloudwatch/rds_cpu_utilization_e47b3b.csv">Link to <strong>validation data</strong></a></li><li><a href="https://github.com/numenta/NAB/blob/master/labels/combined_labels.json">Link to <strong>labels data</strong></a></li></ul><p>The dataset is chosen, great! Certainly, you can pick any other dataset, but we will focus on NAB. Next steps that we should do:</p><ol><li>Go through the <a href="https://github.com/numenta/NAB/blob/master/README.md">README</a> file from NAB repository to understand what we are working with</li><li>Load data into our local filesystem</li><li>Inspect our data of interest visually with anything that can open csv and json. Actually, we can directly open them in GitHub repo</li><li>Load data into our notebook’s environment to make further manipulations inside the notebook using Python. We use <a href="https://pandas.pydata.org/"><strong>Pandas</strong></a> and <a href="https://numpy.org/"><strong>NumPy</strong></a> libraries— pretty standard choice for data loading and manipulation already has several tools that have been implemented</li></ol><p>Assuming that we already went through the README, we can move to the loading into our local filesystem.</p><p>This dataset is located in <em>git, </em>but it doesn’t mean that every dataset should be version controlled. We need just csv with data and json with anomaly labels and they can even be simply on the local hard drive. <em>Git</em> here is for convenience.<br>Let’s grab the data into our local environment to manipulate them any way we want:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2f88356054f619b692450f3723c489a/href">https://medium.com/media/e2f88356054f619b692450f3723c489a/href</a></iframe><p>After some initial inspection in NAB’s GitHub repo, we see that both training and validation files consist of <strong>timestamps with corresponding values</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FUjpiYrSqgjXiYE_juW-dQ.png" /><figcaption>Header and first 5 rows in the training file</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*71BR896G5iOgkkhPXnnvZg.png" /><figcaption>Header and first 5 rows in the validation file</figcaption></figure><p>Each file contains 4032 ordered data rows with a 5-minute rate.</p><p>Let’s find these files in labels <em>(once more, </em><em>json with exact timestamps of anomalies)</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*wvlH2NjIF0-ImWvyTKpWEA.png" /><figcaption>Timestamps of the anomalies for both training and validation data from the file with labels</figcaption></figure><p>We can see that <strong>each</strong> file contains <strong>2 anomalies.</strong></p><p>Since we know what we are dealing with, we can start loading into the notebook with imports of some useful packages:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4644cec6f6141c5ff4d37148eddb9d0a/href">https://medium.com/media/4644cec6f6141c5ff4d37148eddb9d0a/href</a></iframe><p>We already downloaded training and validation files and the file with labels via <em>git. </em>But we also downloaded all other files from the repository, so we need to specify paths to our data of interest:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e76803d31bea818af313dc605f27a415/href">https://medium.com/media/e76803d31bea818af313dc605f27a415/href</a></iframe><p>Finally, we can load timestamps for anomalies from json into our local environment:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8c0893b27c5f94a4ef763eb5a98d702/href">https://medium.com/media/c8c0893b27c5f94a4ef763eb5a98d702/href</a></iframe><p>And read our data with <em>pandas </em>into <em>DataFrame </em>object<em>:</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/17e38b98c21d045b50c4f7dfae642080/href">https://medium.com/media/17e38b98c21d045b50c4f7dfae642080/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*pHzKi1D_H8B0jn8GmaPdPg.png" /><figcaption>Result of train.head()</figcaption></figure><p>As you can see, we’ve managed to load data and take a look at the first 5 rows from the training file. It is enough to understand that we succeeded — these rows are exact 5 first rows that we saw on GitHub.</p><h4>Data Preprocessing</h4><p>Great, we’ve loaded data into our notebook and inspected it a bit, but are we good to go with it and move on to the models part? Unfortunately, the answer is no.</p><p>We have to define exactly what part of the loaded data exactly will be used by our models. We have to think about the <strong>problem</strong> we want <strong>to solve</strong> and what data can be used for this.</p><p>In our case, we want to detect anomalies in <strong>CPU usage. </strong>Well, here is the answer, the clearest choice is value column because it represents CPU usage.</p><p>We also can consider timestamp column — a timestamp encodes a lot of information, i.e. what day of the week it is, what month of the year it is, etc. This information can be extracted and used by the models. We won’t do it in this article, but if you want, you can try it. Maybe, you’ll achieve even better results!</p><p>So, we are going to use value column from training and validation DataFrames<em>. </em>The next step is to transform values from this column into an <strong>appropriate</strong> format. The appropriate format, as you might guess, is numbers. This comes from history — computers use numbers for calculations <em>(and ML models as well), </em>you have to make everything numbers, it’s just the way it works.</p><p>Luckily, value column already <em>consists of numbers</em>, and we can use them in our models as it is. But it is pretty often a good idea to <a href="https://en.wikipedia.org/wiki/Standard_score"><strong>standardize</strong></a><strong> </strong>numbers before feeding our models with data. It helps them generalize better and avoid problems with different scales of values with different meanings <em>(Yes, somebody tried it in ML and it worked). </em>Quite often standardization just means <strong>rescaling</strong> the numbers to <a href="https://en.wikipedia.org/wiki/Mean"><strong>mean</strong></a><strong> = 0</strong> and <a href="https://en.wikipedia.org/wiki/Standard_deviation"><strong>standard deviation</strong></a><strong> = 1.</strong></p><p>That’s why the next thing we have to do is to parse <em>datetime</em> from <em>timestamps </em>(just for convenient visualization) and <strong>standardize values</strong>.</p><p>We will follow the regular rescaling policy (as we said — mean = 0 and standard deviation = 1) and use StandardScaler from Scikit-learn:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5498c7fc0e1fe856e02cef55b614c65/href">https://medium.com/media/b5498c7fc0e1fe856e02cef55b614c65/href</a></iframe><p>Then we can extract anomalies into dedicated variables for both training and validation data from DataFrames:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b9123bb95d7644baf086c16b781530f/href">https://medium.com/media/1b9123bb95d7644baf086c16b781530f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K9SsTWIjJ_tMzPylXu2Vdg.png" /></figure><p>And plot all data with the help of the Plotly library to visualize the whole set of data points and gain more understanding of what it present.</p><p>Firstly, we plot the training data.<br><em>(We are going to use this code for plotting everything we need)</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b01e0c6012d1163a6dc15a31780571f/href">https://medium.com/media/7b01e0c6012d1163a6dc15a31780571f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*WU402FOyg9ikYVKaDLhC_w.png" /></figure><p>Secondly, we plot the validation data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dec1cd29276f6f50cc63922a4dede8a7/href">https://medium.com/media/dec1cd29276f6f50cc63922a4dede8a7/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*51Ptr2Awx8i0TtP_gVF5tQ.png" /></figure><p>I suppose this blue annoying dot between 60 and 70 needs an explanation — why isn’t it marked as an anomaly? The thing is that this dot goes right after the green anomaly dot between 70 and 80. And after ~77% of CPU load, ~67% doesn’t seem suspicious at all. You also should keep in mind that we can’t look ahead because real data comes in real-time so <strong>what looks like an anomaly at some one moment may not look like an anomaly in the full picture</strong>.</p><p>You may notice that at this moment you feel much more comfortable with data. That usually happens due to visual inspection of data values, so it is strongly advised to <strong>visualize and examine it</strong> with your own eyes.</p><h4>Saying what we want from our models out loud</h4><p>Now we know what our data looks like and what kind of data we have. We don’t have much information, actually, just <em>timestamps</em> and <em>CPU loads</em>. But still <strong>enough </strong>to build quite great models.</p><p>So, here comes the best moment to ask a question — <strong>“<em>How our models are going to detect anomalies?</em>”</strong></p><p>To answer it we need to figure out 3 things <em>(remembering the general idea of the anomaly detection and that our data are time series)</em>:</p><ol><li><strong>What is normal?<br></strong>This question can enforce your creativity because there is no strict definition of normality.<br>Here is what we came up with <em>(like many other people). </em>We will use 2 almost identical tasks to teach our models “the normality”:<br>1. Given the value of CPU usage, try to <strong>reconstruct it</strong>. This task will be given to the <strong>LSTM</strong> model.<br>2. Given the values of CPU usage, try to <strong>predict the next value</strong>. This task will be given to the <strong>ARIMA </strong>and <strong>CNN</strong> models.<br>If the model reconstructs or predicts <strong>easily</strong><em> </em>(meaning, with little deviation), then, it is <strong>normal</strong> data.<br>You can change this distribution of the tasks for models. We tried different combinations and this one was the best for our dataset.</li><li><strong>How to measure deviation?<br></strong>The most common way to measure deviation is some kind of <strong>errors</strong>. <br>We will use the <a href="https://en.wikipedia.org/wiki/Mean_squared_error"><strong><em>squared error</em></strong></a> between the predicted value (<strong><em>x*</em></strong>) and the true one (<strong><em>x</em></strong>). <strong><em>Squared error = </em>❨𝑥*−𝑥❩²<br></strong>For ARIMA we will use <a href="https://en.wikipedia.org/wiki/Mean_absolute_error"><strong><em>absolute error</em></strong></a> =<strong>|𝑥*−𝑥<em>|</em></strong>since it performed better. The absolute error may also be used in other models instead of the squared error.</li><li><strong>And what is <em>“too much” </em>deviation?<br></strong>Or in other words how to pick the threshold? You can simply take some numbers or figure out some rules to calculate it. <br>We are going to use the <a href="https://en.wikipedia.org/wiki/68%E2%80%9395%E2%80%9399.7_rule"><strong>three-sigma statistic rule</strong></a><strong> </strong>by measuring the mean and the standard deviation of the errors in all training data <em>(and only training, because we only use validation data to see how our model performs). </em>And then we will calculate the threshold, above which deviation is “<strong>too much</strong>”.<strong><em><br></em></strong>And, looking ahead, we will also use a slightly modified version with <strong>measuring over some window behind the current position</strong> to incredibly enhance accuracy.</li></ol><p>Don’t worry, if it seems too complicated right now, it will become much more clear, when you will see it in the code.</p><h3>Intermediate conclusion</h3><p>Great, most of the theory part is done, and we have loaded, inspected, and standardized our dataset!</p><p>As the practice shows, data preparation is one of the most important fragment sand. We will prove this in the further parts because the code that we implemented here is a strong fundament that we will use in all our models.</p><p>Feel free to move forward:</p><ul><li><a href="https://khaninartur.medium.com/time-series-and-how-to-detect-anomalies-in-them-part-ii-bde9e69d0aaf"><strong>Part II — Implementation of ARIMA, CNN, and LSTM</strong></a></li><li><a href="https://khaninartur.medium.com/time-series-and-how-to-detect-anomalies-in-them-part-iii-f72e800e15e2"><strong>Part III — Eventually easier than it seemed</strong></a></li></ul><h3>About us</h3><p><em>We at </em><a href="http://akvelon.com/"><em>Akvelon Inc</em></a><em> love cutting edge technologies in mobile development, blockchain, big data, machine learning, artificial intelligence, computer vision, and many others. This article is the result of one of many projects developed in our Office Strategy Labs where we’re testing new technologies and approaches before delivering them to our clients.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bQVKqeqDCOCrLG1A" /><figcaption>Akvelon company official logo</figcaption></figure><p><em>If you would like to work with our strong Akvelon team — </em><a href="http://akvelon.com/careers/"><em>please see our open positions</em></a><em>.</em></p><p><strong><em>Designed and implemented with love in Akvelon:<br></em></strong><em>Team Lead — </em><a href="https://www.linkedin.com/in/artur-khanin/"><em>Artur Khanin</em></a><em><br>Delivery Manager —</em><a href="https://www.linkedin.com/in/volynkin/"><em> Sergei Volynkin</em></a><em><br>Technical Account Manager —</em><a href="https://www.linkedin.com/in/maxkostin/"><em> Max Kostin</em></a><em><br>ML Engineers — </em><a href="https://www.linkedin.com/in/irina-nikolaeva-5a26a11b4/"><em>Irina Nikolaeva</em></a><em>, Rustem Saitgareev</em></p><h3>Don’t forget to give us your 👏 !</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/0*2lvCls4yjxVMfZSR" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F8f5f8b%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2F8f5f8b&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/c43026df6fee7cdb1aab8aaf916125ea/href">https://medium.com/media/c43026df6fee7cdb1aab8aaf916125ea/href</a></iframe><figure><a href="https://becominghuman.ai/artificial-intelligence-communities-c305f28e674c"><img alt="" src="https://cdn-images-1.medium.com/max/255/1*2f7OqE2AJK1KSrhkmD9ZMw.png" /></a></figure><figure><a href="https://upscri.be/8f5f8b"><img alt="" src="https://cdn-images-1.medium.com/max/255/1*v-PpfkSWHbvlWWamSVHHWg.png" /></a></figure><figure><a href="https://becominghuman.ai/write-for-us-48270209de63"><img alt="" src="https://cdn-images-1.medium.com/max/255/1*Wt2auqISiEAOZxJ-I7brDQ.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f9f6c2ad32e" width="1" height="1" alt=""><hr><p><a href="https://becominghuman.ai/time-series-and-how-to-detect-anomalies-in-them-part-i-7f9f6c2ad32e">Time Series and How to Detect Anomalies in Them — Part I</a> was originally published in <a href="https://becominghuman.ai/">Becoming Human: Artificial Intelligence Magazine</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>