<?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[When Machines Learn - Medium]]></title>
        <description><![CDATA[A blog to share research and work in applying machine learning in heavy industry. Focus includes asset management and process optimization. - Medium]]></description>
        <link>https://medium.com/utility-machine-learning?source=rss----8f42171d82---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>When Machines Learn - Medium</title>
            <link>https://medium.com/utility-machine-learning?source=rss----8f42171d82---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 11:26:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/utility-machine-learning" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How I landed my data scientist position at Tagup]]></title>
            <link>https://medium.com/utility-machine-learning/how-i-landed-my-data-scientist-position-at-tagup-be90274c96f5?source=rss----8f42171d82---4</link>
            <guid isPermaLink="false">https://medium.com/p/be90274c96f5</guid>
            <category><![CDATA[coding-interviews]]></category>
            <category><![CDATA[visualization]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[autoencoder]]></category>
            <category><![CDATA[anomaly-detection]]></category>
            <dc:creator><![CDATA[Lorenzo Bucci]]></dc:creator>
            <pubDate>Tue, 12 Apr 2022 15:22:58 GMT</pubDate>
            <atom:updated>2022-04-12T15:22:58.691Z</atom:updated>
            <content:encoded><![CDATA[<h4>Mastering technical interviews with autoencoders and visualizations</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WBznaVd1YG4pYVbgc4YTPQ.jpeg" /></figure><p>Working on the cutting edge of disruptive technologies? Getting access to exclusive massive datasets? Contributing to the most exciting field of our times? Whatever your reason to get into the Data Science industry is, in this blog post I’m going to tell you how I mastered my technical interviews and landed my data scientist position at Tagup.</p><p>Emerging businesses in the field of Predictive Maintenance have experienced incredible growth over the past several years, driven by exponential increases in data availability and new computing technologies. Consequently, landing a position in a relative small company today might turn into a fast career growth trajectory in just a short period of time. However, competing for such a role involves tackling several challenges where the technical rounds seem to be the most difficult and perhaps the most dreaded part of the entire interview process. Indeed, just solving these problems is often not enough to stand out in such a competitive landscape, which is why an outstanding presentation of the solution is as important as applying the best algorithmic tools.</p><p>In the following sections I’ll present an autoencoder-based approach to the problem of “anomaly detection” that I leveraged during one of the technical rounds as part of my interview process at Tagup — notice that all the code, figures and explanations in this post were an integral part of my submission.</p><p>This post assumes some background in basic signal processing and machine learning.</p><h4>Content outline</h4><p>– <a href="#b583">The anomaly detection problem</a><br>– <a href="#32ec">Autoencoder for anomaly detection</a><br>– <a href="#0bba">Data cleaning</a><br>– <a href="#41cd">Data formatting and normalization</a><br>– <a href="#4cbb">Training the autoencoder</a><br>– <a href="#1002">Performance evaluation and decision logic</a><br>– <a href="#9272">Conclusion</a></p><h4>The anomaly detection problem</h4><p>Imagine a company running a fleet of very expensive machines (e.g., a set of wind turbines) having three operating modes: <em>normal</em>, <em>faulty</em> and <em>failed</em>. The machines run all the time, and usually they are in normal mode. However, if a machine enters faulty mode, the company should take preventive actions as soon as possible to avoid the machine entering failed mode (which would be detrimental not only to the machine but also very costly for the company).</p><p>Each machine is monitored through a set of sensors streaming data in real-time. Figure 0 shows an example of the data coming from a single machine during the different operating modes. When a machine is operating in normal mode, the data behaves in a fairly predictable way. Before a machine fails, it ramps into faulty mode where the data appears visibly different and unpredictable. If operating in faulty mode, the machine will eventually break with all signals going close to zero (failed mode). Since the breaking point is unpredictable, the goal is to be able to spot faulty patterns and shut down the machine as soon as possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6wMPh-A2GWtN9evXiDVZog.jpeg" /><figcaption><strong>Figure 0:</strong> The four signals (numbered from 0 to 3) coming from the sensors applied on the machine. The signal patterns determine three different operating modes, highlighted using different background colors: normal (green), faulty (magenta) and failed (yellow).</figcaption></figure><h4>Autoencoder for anomaly detection</h4><p>The solution proposed is a self-supervised approach to detecting faulty patterns using a model architecture from a class of deep learning models called <strong>autoencoders</strong>. This approach roots itself in the observation that, while normal behavior is fairly predictable, faulty patterns deviate from this predictable behavior.</p><p>In essence, autoencoders are composed of two networks: an <strong>encoder</strong> and a <strong>decoder (</strong>see Figure 1<strong>)</strong>. The encoder network encodes the input sequence into a smaller dimensional space called the “latent space”. The decoder network tries to reconstruct the original sequence from the latent encoding. The autoencoder has to learn essential features of the data to be able to do a high-quality reconstruction during the decoding step. The difference between the input sequence and its reconstruction can be quantified using an error measure, e.g., the Mean Squared Error (MSE).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CXiW5JdMjByHNTIHrGDGhA.png" /><figcaption><strong>Figure 1:</strong> A representative autoencoder architecture. The encoder network encodes the input sequence (blue curve on the left) into a smaller dimensional space called the “latent space”. The decoder network tries to reconstruct the original sequence from the latent encoding (orange curve on the right). The difference between the input sequence and its reconstruction can be quantified using an error measure, which is proportional to the yellow area between the two curves on the right.</figcaption></figure><p>After being trained on sequences of fixed length showing normal behavioral patterns, the autoencoder is expected to be able to reconstruct other unseen normal sequences fairly well (i.e., resulting in low error values). Instead, when a faulty sequence is provided as input, the autoencoder would struggle to make a good reconstruction resulting in a high error value. Once put to work, the autoencoder observes the real-time sensor data within a time window of the same length of the training sequences. A threshold mechanism on the reconstruction error is then used to discriminate the different behavioral patterns. The animation in Figure 2 provides a visual intuition of the solution’s mechanism.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*jg6srFFk0mAMfBajDTxYTQ.gif" /><figcaption><strong>Figure 2:</strong> The autoencoder observes the time series data within a window of 30 time steps. The model needs to wait until the 30-th time step before starting to make predictions. The sequence falling within the observation window is then labelled as normal or faulty on the basis of the reconstruction error.</figcaption></figure><h4>Data cleaning</h4><p>The time series data shown in Figure 0 and Figure 2 already went through a cleaning process allowing to reduce the variability in the data that will be used to train the autoencoder. So, let’s rewind for a moment and see how this result was actually achieved.</p><p>Figure 3 shows a sample of the raw time series data. In the following snippets of code I will assume the input data to be in CSV format with each column constituting a different signal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LdWhJZ4hNMPsLNuasW7_cw.jpeg" /><figcaption><strong>Figure 3:</strong> Chunk of the raw time series data comprised of four different signals (numbered from 0 to 3) displayed using different colors.</figcaption></figure><p>As visible in Figure 3, the time series data presents 2 main problems:</p><ul><li>Signal spikes due to sensor communication errors;</li><li>High-frequency noise (i.e., the signal looks like a “zigzag”).</li></ul><p>Signal spikes can be removed using a simple threshold mechanism. Snippet 0 shows how to spot the signal portions having an amplitude greater than a fixed threshold (in absolute value) and replace them with the closest previous value using common Python packages.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/416fe5bb375256a9c7d6c0febea7250f/href">https://medium.com/media/416fe5bb375256a9c7d6c0febea7250f/href</a></iframe><p>Figure 4 shows the same signals from Figure 3 after removing the spikes due to sensor communication errors. The high-frequency noise is still present.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DhVbyE8QASW34s2irCNKow.jpeg" /><figcaption><strong>Figure 4:</strong> The same time series data from Figure 3 after removing the spikes due to sensor communication errors. The high-frequency noise is still present.</figcaption></figure><p>Removing the high-frequency noise can be easily achieved using some basic filtering techniques. However, in order to properly set the filter’s parameters, visualizing the signals in the frequency domain would be very informative. Snippet 1 shows how to use the <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.fftpack.fft.html">SciPy Fast Fourier Transform (FFT)</a> Python module to plot the signals’ spectrum shown in Figure 5.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bbb1025214942e77335098fa1d1397b4/href">https://medium.com/media/bbb1025214942e77335098fa1d1397b4/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9SEXJ7V5704BpDXYjZhLuA.png" /><figcaption><strong>Figure 5:</strong> The four signals from Figure 4 in the frequency domain. Only harmonic components between -49 Hz and 50 Hz are shown.</figcaption></figure><p>It is possible to notice from Figure 5 that the relevant information is mainly concentrated in the <em>[0, 10] Hz</em> interval — we are considering the positive spectrum only. Consequently, a simple low pass filter can be used to effectively remove the high-frequency peaks at <em>~30 Hz</em>. Snippet 2 shows an implementation of a low pass filter using the SciPy Python package.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dca5cc3537adbe376c937ff2243d3f82/href">https://medium.com/media/dca5cc3537adbe376c937ff2243d3f82/href</a></iframe><p>Figure 6 shows the same time series data from Figure 4 after removing the high-frequency noise using the filter from Snippet 2 with a cutoff frequency of <em>10 Hz</em>. The four signals now look smooth.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h0XgqwkVKGhSDJb_WoIgsg.jpeg" /><figcaption><strong>Figure 6:</strong> The same time series data from Figure 4 after removing the high-frequency noise.</figcaption></figure><h4>Data formatting and normalization</h4><p>As previously stated, the autoencoder observes the time series data within a time window of fixed size; let’s call it <em>S</em>. Consequently, in order to train the autoencoder, a dataset of sequences of length <em>S </em>has to be generated from the original time series data. Intuitively, having a sequence length of <em>S</em> time steps, the <em>i-th</em> sequence is generated using the data points from step <em>i</em> to step <em>i + S -1</em> (assuming a stride of <em>1</em>).</p><p>Additionally, the generated sequences are normalized in such a way that the amplitude of the four signals would span the range <em>[0,1]</em>. Normalization aims at avoiding that signals with a high amplitude would dominate the learning process — i.e., the autoencoder should learn how to reconstruct all four signals in the same manner.</p><p>Snippet 3 shows an implementation of the formatting and normalization steps described above. The shape of the resulting dataset is <em>(N, S, M),</em> where <em>N</em> is the number of sequences, <em>S</em> is the sequence length and <em>M</em> is the number of features (i.e., the number of signals).</p><p>Remember that only sequences showing normal behaviors should be used for training the autoencoder.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4170c24d90cc838189c307a473ed2bc7/href">https://medium.com/media/4170c24d90cc838189c307a473ed2bc7/href</a></iframe><h4>Training the autoencoder</h4><p>Snippet 4 defines the architecture of the LSTM-based autoencoder using the <a href="https://keras.io/">Keras</a> Python package, while Snippet 5 runs the actual training. Figure 7 shows the training and validation losses over each epoch using <em>10,935</em> normal sequences of length <em>16</em>. Ten percent of these sequences is used for validation with early stopping.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b81958ede4388d9bb079390312805c04/href">https://medium.com/media/b81958ede4388d9bb079390312805c04/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0cf3966ff720ed2714217e82d255cc2/href">https://medium.com/media/c0cf3966ff720ed2714217e82d255cc2/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C-twofNwbYq2ADfh1Ds4Qg.png" /><figcaption><strong>Figure 7:</strong> Training and validation losses over each epoch.</figcaption></figure><h4>Performance evaluation and decision logic</h4><p>To visually assess the performance of the model, Figure 8 shows a comparison between two (randomly chosen) input sequences and their reconstructions made by the autoencoder. We can see that the autoencoder can reconstruct the normal sequence fairly well; but we cannot state the same for the faulty sequence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F2g1YEW6b-hRDFRUPCvjBA.png" /><figcaption><strong>Figure 8:</strong> Autoencoder behavior in the case of normal (left) and faulty (right) sequences. While the normal sequence is reconstructed fairly well (MSE = 0.007), the faulty sequence cannot be reconstructed as accurately (MSE = 0.056). Both sequences have a length of 16 time steps.</figcaption></figure><p>During prediction, a threshold mechanism can be used to label the sequences as <em>normal</em> or <em>faulty</em> on the basis of the resulting MSE — i.e., when the error is lower than a fixed threshold the sequence is labelled as normal; when the error exceeds the threshold the sequence is labelled as faulty. Setting a proper threshold value is critical to minimize the misclassification rate.</p><p>The sequence length is another critical parameter determining a trade-off between accuracy and how quickly faulty patterns can be detected — the shorter the sequence, the faster the model can discriminate machine behaviors. For example, given a sequence of length <em>S</em>, the model needs to wait <em>S</em> time steps before being able to compute the corresponding error value — e.g., in the animation previously shown in Figure 2 the model had to wait 30 time steps before starting to make predictions.</p><p>Finally, Figure 9 shows the autoencoder at work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PLuMi8hMYOmUQnyWSY76RA.jpeg" /><figcaption><strong>Figure 9:</strong> The autoencoder put to work. Using a sequence length of 16, the reconstruction error is outputted with a 16-time step delay. The magenta region highlights when the MSE exceeds the threshold value indicated by the magenta dashed line.</figcaption></figure><h4>Conclusion</h4><p>I hope you enjoyed this quick journey through signal processing and autoencoders — the next time you will run into an anomaly detection problem, give it a try!</p><p>As a final note, keep in mind that the quality and effectiveness of your code are not the only relevant aspects in the interview process. Clarity of thought, thorough documentation, and a cohesive narrative are critical elements of a successful technical challenge submission. Combining a competent technical approach with a clear written and visual description of your work is a surefire way to impress!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be90274c96f5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/utility-machine-learning/how-i-landed-my-data-scientist-position-at-tagup-be90274c96f5">How I landed my data scientist position at Tagup</a> was originally published in <a href="https://medium.com/utility-machine-learning">When Machines Learn</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Methods for Imputation with Hidden Markov Models]]></title>
            <link>https://medium.com/utility-machine-learning/methods-for-imputation-with-hidden-markov-models-be2900cfc2d2?source=rss----8f42171d82---4</link>
            <guid isPermaLink="false">https://medium.com/p/be2900cfc2d2</guid>
            <category><![CDATA[data-imputation]]></category>
            <category><![CDATA[machine-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Anna Haensch]]></dc:creator>
            <pubDate>Fri, 30 Oct 2020 13:54:54 GMT</pubDate>
            <atom:updated>2020-10-30T13:54:54.442Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using inference to fill in missing values in sequential data</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X_r7B_LK3huJ75Ac" /><figcaption><em>Photo by </em><a href="https://unsplash.com/@konkarampelas?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"><em>Kon Karampelas</em></a><em> on </em><a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"><em>Unsplash</em></a></figcaption></figure><h4>TL;DR</h4><p><em>Imputation is a tool for filling in missing data. There are many ways to impute, and in this post we explain a few practical methods. For imputing sequential data, the hidden Markov model will prove particularly useful.</em></p><h3>Collecting Equipment Data</h3><p>These days it’s very common for everything from powerful commercial wind turbines to common household appliances like ceiling fans, refrigerators, and even <a href="https://www.cnet.com/smart-garden/">garden hoses</a> to come equipped with sensors that feed data continuously to the cloud. When everything is working properly, this makes it easy for consumers to track their data and get daily snapshots of their equipment’s performance. However, anytime the Wi-Fi is down, the system might fail to capture data, resulting in unknown values in the historical record. This is especially problematic if we hope to analyze the data using machine learning algorithms that don’t necessarily handle missing data well.</p><p>As data scientists confronted with this situation, we’d like to fill in these values in the smartest way possible. While we can’t know the true value of this missing data, we can get better performance from these algorithms by making an educated guess at what the values would have been. Luckily, missing data points in the context of a more complete dataset leave us with plenty of clues for assigning the missing values.</p><p>Imputation is an inference-based method for assigning values to an otherwise unknown range of data. This practice has many applications in data science. Perhaps the most common — and the topic of discussion in this post — is filling in missing data during preprocessing. You can read more about other applications of imputation in <a href="https://docs.google.com/document/d/1Cvkyuex8FDtafOMWXiWm1Bw5-hQ6VWUgm1p92g1LV04/edit"><em>Applications of Imputation for Sequential Data</em></a>, or if you’re new to imputation, you might start by reading this brief <a href="https://medium.com/utility-machine-learning/an-introduction-to-imputation-solving-problems-of-missing-and-insufficient-data-1814c90c3545"><em>Introduction to Imputation</em></a><em>.</em> In this post we’ll be taking a closer look at some common machine learning approaches for imputation and discussion why they work…or why they don’t.</p><p>To compare different methods of imputation we’ll be intentionally redacting values from a data set of energy production vs demand. The energy production data is gathered from an array of nine 300 watt solar panels located on my roof in Cambridge, MA. This array sends energy production data to a remote server over my home’s Wi-Fi network where it is then broadcast to a website and mobile app. We’ll also be looking at the electricity demand across the <a href="https://www.eia.gov/beta/electricity/gridmonitor/dashboard/electric_overview/regional/REG-NE">New England electrical grid</a> from October 2018 to October 2020. Since the goal of this post is to measure the effectiveness of various imputation strategies, we’re beginning with a dataset that doesn’t have any missing values.</p><p>We’re going to focus on the task of imputation for time series data and evaluate the effectiveness of several different strategies, but before we proceed, a small note about mathematical rigor. In this post we’re going to judge the effectiveness of our imputation by visual inspection only. A lot can be learned by looking at a plot! Of course there are lots of <em>mathematical</em> ways to determine how well an imputation strategy works, but we’ll save those for another post.</p><h3>Exploring the Data</h3><p>Let’s start by looking at the data. As expected, energy production follows a very clear seasonal pattern, with higher energy production in the sunny summer months. The seasonality of the energy demand curve is a bit less obvious, but the demand is highest in summertime with a smaller peak in wintertime. If we look at a scatter plot of energy production against energy demand, we don’t see any obvious clustering of the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Db-FguGr68aasBNT" /><figcaption>Solar Energy Production (Wh) and New England grid Energy Demand (MWh) (data source: <a href="https://www.eia.gov/beta/electricity/gridmonitor/dashboard/electric_overview/regional/REG-NE">eia.gov</a>) for October 2018 through October 2020.</figcaption></figure><p>To test the various imputation strategies, we’re going to “forget” several values over the course of the data; this process is known as <em>redacting</em> data points. In the plots below we’ll highlight the redacted data points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8NCS89xc5OvLg4Np57h1VQ.png" /><figcaption>The circled values have been deleted from the dataset.</figcaption></figure><p>Our goal now is to fill in these missing values in a way that takes advantage of everything we can learn about the underlying distribution of the data.</p><h3>Imputation with IterativeImputer</h3><p>One thing we can do is to impute the missing values using scikit-learn’s built-in <a href="https://scikit-learn.org/stable/modules/generated/sklearn.impute.IterativeImputer.html">IterativeImputer</a>. This method works by fitting a regression model for each feature that has a missing value (in this case that’s “Energy Production” and “Energy Demand”). The regression model is then used to fit the missing values. Unfortunately for our data, this means that the best this method can do is replace the missing value with the mean value for each feature. If we view this as a time series, we can see that the imputed value is never too wrong, since it’s always at the mean.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8JN6CVpnPVFXzoGAgzhPDQ.png" /></figure><p>However, viewed as a scatterplot above on the right we can see that we haven’t really gained any insight into the data from using this method of imputation, since every missing point, regardless of context, was filled in with the same value.</p><h3>HMM Imputation</h3><p>Although the clustered data doesn’t present any obvious Gaussian properties, we know that there is some seasonality signal in the data. Therefore, a smart method of imputation would take advantage of the seasonality in the data, and differentiate between the mean values of the different seasonal components of the data.</p><p>One such method uses hidden Markov models (HMM). If you’ve never heard of a hidden Markov model, you might start by reading the previous post on this blog about <a href="https://medium.com/utility-machine-learning/using-hidden-markov-modeling-to-detect-seasonality-in-sequential-data-3c059649eb70"><em>Using Hidden Markov Models to Detect Seasonality in Sequential Data</em></a>.</p><p>An HMM has the ability to detect latent states in multidimensional data that are not always visible to the naked eye. Training an HMM on the energy data set we can detect three hidden states, roughly corresponding to winter, summer, and a combined state of spring/fall.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TjGz9TqBc7K2BNQt" /></figure><p>There are now several ways that we can use the hidden Markov model to impute the missing data points. Let’s consider two possible strategies, and what we might gain from each.</p><h3>HMM Imputation with Averaging</h3><p>At each moment in time, we have a spread of probabilities across the possible hidden states. If our goal is to impute a value at time <em>t</em>, then we’ll first need to know the relative likelihood of each hidden state at time <em>t</em>, given everything that we know. In terms of probability, we’ll express the relative likelihood of hidden state <em>i</em> at time <em>t</em> as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/146/0*29SPFte_KqX_6wK4" /></figure><p>where <em>h</em>ₜ denotes the hidden state at time <em>t</em> and <em>D</em> denotes the complete data available to us.</p><p>Let’s suppose that each of our hidden states corresponds to a Gaussian distribution. In this case, for each hidden state, <em>i</em>, we’d have the corresponding mean, μᵢ, standard deviation, σᵢ, and therefore observations in this hidden state are drawn from</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/99/0*7etcEKpWKrvSBpV8" /></figure><p>Keep in mind that in a Gaussian distribution the mean acts as the most likely value to be drawn from the distribution. In terms of hidden states, this suggests that the most likely value to occur in any hidden state is the mean itself. This observation is already enough to devise a method of imputation. At any time, <em>t</em>, where data is missing, we can simply take our imputed value to be a weighted average of the means for each hidden state, that is,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/213/0*gJmmMgUvOZm_lejV" /></figure><p>This will deliver an imputed value that is more contextually relevant than scikit-learn’s IterativeImputer, since the relative likelihood of hidden states is completely informed by context. For this reason, we can see in the plot below that each of the missing values is imputed with a slightly different value. However, it is very unlikely that this method will <em>precisely</em> impute the correct value, since the values are typically going to be drawn towards the weighted mean, to the exclusion of extreme values. On the other hand, this method will always be more accurate than the basic scikit-learn IterativeImputer, and there is an upper bound to how wrong it can be. Let’s look at an even smarter version of HMM imputation.</p><h3>HMM Imputation with Argmax</h3><p>Similar to the method above, we will consider the spread of relative probabilities for each hidden state at a missing observation. Unlike the method above, we will impute with only the most probable value, rather than taking a weighted average. Recall that for each hidden state the mean represents the most likely value to appear in the corresponding probability distribution. But also recall that probability distributions have variance associated with them, so in terms of the probability density function, the means of two different Gaussian distributions aren’t considered to be equally likely. To overcome this, we will compute the image of the mean under the probability density function for each hidden state and take only the maximum of those values to be our imputed value, that is,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/151/0*7xB7RNbDi8WTTOru" /></figure><p>where</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/218/0*rJVi0c-jf-5zPJrr" /></figure><p>Imputing with this method, we get the values below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ACJtbQAClDBnVXFNEdz-jQ.png" /></figure><p>Notice how much closer the imputed values are to the original under the HMM Argmax method as compared to the HMM Averaging method. Of course none of these values are precisely correct, but they are far closer than the values produced by the other algorithms we’ve explored so far. Keep in mind that imputation will rarely yield the precisely correct value, since the internal calculations are always balancing the likelihood of multiple plausible values. Imputed values will have a tendency to drift towards the center.</p><p>In summary, each successive method was slightly better at imputing the redacted values. We can see this altogether in the plot below. Notice how each successive imputation attempt is drawn closer and closer to the original values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*GGEzAl1GOZI6d2CwARlIlA.png" /></figure><h3>Conclusion</h3><p>There are many ways to impute missing data, and we’ve presented just three of them here. As always, there are tradeoffs between each method. Scikit-learn’s IterativeImputer is open source, easy to use and requires no setup, but fails to capture the temporal dynamics of the data. When dealing with missing data that has any sort of temporal dependence there is a lot to be gained by HMM imputation. An HMM is sensitive to the underlying distributions of the data, and it is able to accurately impute values that are far from the overall mean of the data. However, the two HMM methods require a custom implementation and more computationally intensive training. As to which of the Argmax or the Average method is best, this depends on the goal of imputation and the nature of the underlying data.</p><p>For more about imputation and machine learning with sequential data, check out <a href="https://medium.com/utility-machine-learning"><em>When Machines Learn</em></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be2900cfc2d2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/utility-machine-learning/methods-for-imputation-with-hidden-markov-models-be2900cfc2d2">Methods for Imputation with Hidden Markov Models</a> was originally published in <a href="https://medium.com/utility-machine-learning">When Machines Learn</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dask Performance Boosts for Model Training]]></title>
            <link>https://medium.com/utility-machine-learning/dask-performance-boosts-for-model-training-89a43d132690?source=rss----8f42171d82---4</link>
            <guid isPermaLink="false">https://medium.com/p/89a43d132690</guid>
            <dc:creator><![CDATA[Daniel Hathcock]]></dc:creator>
            <pubDate>Fri, 16 Oct 2020 18:10:51 GMT</pubDate>
            <atom:updated>2020-10-20T16:54:50.979Z</atom:updated>
            <content:encoded><![CDATA[<h3>Dask Performance Boosts For Model Training</h3><h4><strong>Tips and tricks to speed up distributed training with Dask.</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7fg2_C7HPYOdYkC9h3jrYA.jpeg" /><figcaption><em>Photo by</em><a href="https://unsplash.com/@christianem?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"><em> Christian Englmeier</em></a><em> on</em><a href="https://unsplash.com/s/photos/speed?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"><em> Unsplash</em></a></figcaption></figure><h4>TL;DR</h4><p><em>A distributed computing library like </em><a href="https://dask.org/"><em>Dask</em></a><em> is a great tool for speeding up machine learning model training. We’ll show a few methods for achieving performance boosts by knowing when and how to use techniques like </em><strong><em>batching</em></strong><em>, </em><strong><em>scattering</em></strong><em>, and </em><strong><em>tree-reduction</em></strong><em>.</em></p><h3>Distributing Model Training</h3><p>In supervised machine learning, models are often trained by <a href="https://medium.com/utility-machine-learning/using-jax-to-streamline-machine-learning-optimization-d0da2f53a9fb">defining a problem-specific loss function and trying to minimize it</a>. Intuitively, the loss function quantifies some measure of how different model predictions are compared to the training data labels for a given set of parameter values; the best-known example of this is minimizing the sum-of-squared errors when fitting a linear regression model. In practice, this is done by using first- or second-order optimization algorithms (<a href="https://en.wikipedia.org/wiki/Gradient_descent#:~:text=Gradient%20descent%20is%20a%20first,function%20at%20the%20current%20point.">gradient descent</a>, <a href="https://en.wikipedia.org/wiki/Stochastic_gradient_descent">SGD</a>, <a href="https://en.wikipedia.org/wiki/Newton%27s_method">Newton’s method</a>, etc.) to search for optimal parameters which minimize the loss function. This broad description of training applies to many popular models, including:</p><ul><li>Linear regression</li><li>Logistic regression</li><li>Support Vector Machines</li><li>Neural Networks</li></ul><p>The loss function in these situations can often be written as the sum of loss for the individual training examples (maybe with some additional regularization terms):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*g50Ty4UtkRfTPQ0DYZT6JA.png" /></figure><p>where <em>R(θ) </em>is a regularization term. Linearity of the derivative then gives us the convenient formulation of the gradient with respect to the parameters :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*N_R2csxTZcqohqgmdaPA8g.png" /></figure><p>As such, we can easily distribute computations of the loss and its gradient (and hessian, etc.) by letting multiple threads/cores/cluster workers each compute the loss/gradient for individual training examples concurrently, then gathering and summing the results.</p><h3>Dask for Distributed Computing in Python</h3><p><a href="https://dask.org/">Dask</a> is a popular library for scalable distributed computing in Python. It allows you to distribute tasks on various clusters ranging from a few nodes running locally on your laptop up to thousands of nodes running on a server. Other libraries exist with similar functionality, but this post focuses specifically on how to speed up training in Dask.</p><p>Let’s look at a simple example. Here we have a list of examples (<em>examples</em>) and the parameters for the current training iteration as <em>params</em>:</p><pre>def single_example_loss(examples,params): <br>    ... <br>    return loss, gradient  </pre><pre>def compute_loss(examples, params, client): <br>    futures=client.map(single_example_loss, examples,params=params) <br>    results=client.gather(futures) <br>    return sum(r[0] for r in results), sum(r[1] for r in results)</pre><p>This is the basic formula for distributing the loss computation using Dask. The performance gains from this basic implementation, however, may be lacking for reasons that will be explained shortly. The remainder of this post will discuss ways to improve results.</p><h3>Transmitting Data (<em>scatter)</em></h3><p>In the above example, the parameters array may be very large. Furthermore, we could have a need to transmit other large pieces of data to the workers, like a <a href="https://justindomke.wordpress.com/2009/01/17/hessian-vector-products/">Hessian product vector</a>. Such large pieces of data which are shared between all workers can instead be <strong>scattered</strong> beforehand using <em>client.scatter()</em>:</p><pre>params_future = client.scatter(params, broadcast=True)<br>futures = client.map(single_example_loss, examples,<br>                                      params=params_future)</pre><p><em>client.scatter(…, broadcast=True)</em> efficiently sends a piece of data to all workers, which can eliminate unnecessary network time during a <em>client.map()</em>.</p><p><strong>Be aware of the following:</strong></p><ul><li>Scattering is usually unnecessary for small pieces of data, and in this case it may slow things down slightly because it creates some additional overhead.</li><li>There are some<a href="https://github.com/dask/dask/issues/6027"> known bugs</a> in Dask when using <em>client.scatter()</em>. Be aware of these, as they can cause your training routine to crash. <strong>Scattering is not always the optimal thing to do</strong>.</li></ul><h3>Submitting Tasks (batching)</h3><p>Suppose there are 4000 training examples. In the above example which calls <em>client.map(single_example_loss, examples, params=…)</em> to compute the loss for a single iteration, we create 4000 Dask tasks/futures. We might instead choose to write a function to compute loss in batches:</p><pre>def batch_loss(example_list, params):<br>    accum_loss, accum_grad = 0, 0<br>    for example in example_list:<br>        loss, grad = single_example_loss(example, params)<br>        accum_loss += loss<br>        accum_grad += grad<br>    return accum_loss, accum_grad</pre><p>Now, we can do all of the computations for a single iteration with:</p><pre>n_workers = len(client.has_what())<br>futures = client.map(<br>    batch_loss, <br>    [examples[i::n_workers] for i in range(n_workers)], <br>    params=params_future<br>    )</pre><p>If we have 40 workers, this reduces the number of Dask tasks/futures created from 4000 to 100. Each Dask task submitted creates some non-trivial amount of overhead, so submitting in batches like this can provide nice speedups.</p><h3>Gathering Results (tree-summation)</h3><p>The standard way one might gather the results to compute the final loss is <em>client.gather()</em>, as used above. To attempt to increase the efficiency of this slightly, we might replace this with:</p><pre>from dask.distributed import as_completed <br>...<br>for _, result in as_completed(futures=mapped, with_results=True):<br>    ...</pre><p>It turns out that neither of these solutions work particularly well in certain situations. Dask has some latency that prevents the client from collecting many large results (remember there might be lots of parameters) from many workers quickly. That is, even if all workers finish quickly, the client might take several additional minutes to collect these results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*l17zlt1lJ6SdHJtQ7Xr7zQ.png" /><figcaption>Gathering results as a single output using tree-summation.</figcaption></figure><p>An alternative (and better!) solution is to let the workers do all necessary post processing by pairing up. We continue iterating like this until only one worker remains with the final result, and then send only this single final result to the client. We also need to add a post-processing helper-function:</p><pre>def accumulate(result1, result2):<br>    return result1[0] + result2[0], result1[1] + result2[1]</pre><p>Then, gather results using tree-summation (letting workers pair up):</p><pre>...<br>mapped = client.map(...)<br><br>while len(mapped) &gt; 1:<br>    new_mapped = []<br>    for i in range(0, len(mapped) - 1, 2):<br>        fut = client.submit(accumulate, mapped[i], mapped[i + 1])<br>        new_mapped.append(fut)<br>    if len(mapped) % 2 == 1:<br>        new_mapped.append(mapped[-1])<br>    mapped = new_mapped<br><br>return mapped[0].result()</pre><p>Using this tree-summation solution will usually provide huge speed-ups over the other two result-gathering solutions.</p><p>One of our time-to-event modeling frameworks currently under development that uses deep learning to model event risk, HazardNet, benefited hugely from the combination of batching and tree summation due to the large number of parameters in the model. We saw estimated speedups of 5–10x when implementing these methods over the standard client.gather() approach.</p><h3>Conclusion</h3><p>We gave a brief overview of three methods for speeding up distributed computations with Dask:</p><ul><li><strong>Scattering:</strong> Transmits data to workers. This is useful when there are large pieces of data that all workers need access to in order to complete the task.</li><li><strong>Batching</strong>: Reduces overhead caused by submitting many tasks to the Dask scheduler. This is useful when the number of tasks is very large.</li><li><strong>Tree-summation</strong>: Accumulates data among workers before sending the accumulated result to the scheduler. Very effective when there are a large number of tasks and each individual piece of data being accumulated is large.</li></ul><p>These approaches could be used for many different types of distributed computations, but are especially useful in the context of optimization. You can learn more about <a href="https://medium.com/utility-machine-learning/a-guide-to-distributed-tensorflow-part-1-549b6b6fb55">setting up efficient data input pipelines</a> and <a href="https://medium.com/utility-machine-learning/a-guide-to-distributed-tensorflow-part-2-b459770e397b">distributed training in the context of deep learning</a> with TensorFlow and much more on <a href="https://medium.com/utility-machine-learning"><em>When Machines Learn</em></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89a43d132690" width="1" height="1" alt=""><hr><p><a href="https://medium.com/utility-machine-learning/dask-performance-boosts-for-model-training-89a43d132690">Dask Performance Boosts for Model Training</a> was originally published in <a href="https://medium.com/utility-machine-learning">When Machines Learn</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Guide to Distributed Tensorflow: Part 2]]></title>
            <link>https://medium.com/utility-machine-learning/a-guide-to-distributed-tensorflow-part-2-b459770e397b?source=rss----8f42171d82---4</link>
            <guid isPermaLink="false">https://medium.com/p/b459770e397b</guid>
            <category><![CDATA[technical-guide]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[distributed-computing]]></category>
            <dc:creator><![CDATA[Roshan Thaikkat]]></dc:creator>
            <pubDate>Fri, 16 Oct 2020 13:02:42 GMT</pubDate>
            <atom:updated>2020-10-17T00:08:58.286Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Guide to Distributed TensorFlow: Part 2</h3><h4>How to set up large scale, distributed training of TensorFlow models using Kubeflow.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VmYdnrlOTK3NanS6" /><figcaption>Photo by<a href="https://unsplash.com/@clintadair?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"> Clint Adair</a> on<a href="https://unsplash.com/s/photos/machine-learning?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"> Unsplash</a></figcaption></figure><h3><strong><em>TL;DR</em></strong></h3><p><em>This is the second post in a two-part series on large-scale, distributed training of TensorFlow models using Kubeflow. In </em><a href="https://medium.com/utility-machine-learning/a-guide-to-distributed-tensorflow-part-1-549b6b6fb55"><em>Part 1</em></a><em>, we saw how to implement an efficient input pipeline for training a recurrent autoencoder using TFRecord and tf.data.Dataset API. In this post, we will continue from where we left off and discuss Kubeflow, the framework we will use for distributing our computational workloads across the cluster nodes. We will also provide the necessary implementation details and an illustrative visualization of how epoch run times scale with the number of GPUs.</em></p><h3><strong>Distributed Training</strong></h3><p><em>This is the second in a two-part series. You can </em><a href="https://medium.com/utility-machine-learning/a-guide-to-distributed-tensorflow-part-1-549b6b6fb55"><em>find Part 1 here</em></a><em>.</em></p><p>TensorFlow<em> </em>takes care of all the painful details of workload distribution with its recommended <em>MultiWorkerMirroredStrategy. </em>At a high level: a replica of the model is created on every worker and then each batch of input data with a global batch size is split and distributed such that each worker gets a single batch with a <em>batch_size_per_worker </em>number of instances. Weight updates happen synchronously after every iteration.</p><p>This data parallelism combined with the ability of GPUs to execute intensive array computations at high speeds and TensorFlow’s<em> </em>efficient communication protocols between the GPUs is what makes this approach scalable. It can’t get any easier to apply this strategy to our model — we can define the model setup and graph operations within the scope of this strategy and TensorFlow takes it from there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/0*DurS3t65h4hoXziw" /><figcaption>Model initialization</figcaption></figure><p>In the above code snippet, <em>assemble(..)</em> is analogous to a method that creates all the layers of the neural network and <em>setup(..)</em> would be a method that creates all the graph operations using those layers. Note that we’re calling these functions within the scope of the distribution strategy to let TensorFlow<em> </em>know that these are the operations that need to be distributed.</p><p>These are the TensorFlow essentials. Now let’s focus on another key component: Kubeflow.</p><h3><strong>Step-by-Step Kubeflow</strong></h3><p><a href="https://www.kubeflow.org/">Kubeflow</a> is a machine learning deployment toolkit that automates a lot of the requirements for making portable and scalable ML deployments. We will use Kubeflow’s<em> tf-operator</em> to create and manage a <em>TFJob, </em>a custom Kubernetes resource. The <em>TFJob </em>custom resource is designed to run distributed training jobs in Kubernetes. In what follows we will outline the steps to install and deploy Kubeflow on an operational cluster with private nodes. We will assume <a href="https://kubernetes.io/docs/tasks/tools/install-kubectl/"><em>kubectl</em></a> is installed and enabled.</p><h4>Creating a StorageClass</h4><p>For this Kubeflow<em> </em>deployment, we need to create a default <em>StorageClass</em> with a dynamic volume provisioner enabled. Within the cluster context a <em>StorageClass</em> manifest needs to be executed; here is a template manifest (a manifest is simply a yaml file for creating a Kubernetes resource).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*wr451zJM4wFVVrMqbxOmEw.png" /><figcaption>Example of a storage class manifest.</figcaption></figure><p>Next, run the following to create a storage class with dynamic provisioning enabled:</p><pre>kubectl create -f &lt;manifest&gt;.yaml </pre><p>Remember to set the cluster context appropriately using kubectl config use-context &lt;cluster&gt; before executing this command.</p><h4>Preparing the Node Pool and Configuring Firewall Rules</h4><p>If the cluster does not meet <a href="https://www.kubeflow.org/docs/started/k8s/overview/">the requirements for Kubeflow</a>, create a new node pool to satisfy these requirements. It is straightforward to create or delete node pools with <a href="https://www.terraform.io/docs/providers/google/r/container_cluster.html"><em>terraform</em></a> but that is beyond the scope of this post.</p><p>If the cluster contains private nodes, as in our case, there will be issues with the installation. Specifically, the installation will crash when <em>webhook </em>related resources are being installed. To prevent this, we need to create an ingress firewall rule from the cluster master’s CIDR to the VMs on ports 6443 and 443. Creating this firewall rule using the Google cloud console is straightforward. For AWS users, the rule should be created under appropriate security group(s).</p><h4>Installing and Deploying Kubeflow</h4><p>Next, follow the instructions in <em>“Prepare your environment”</em> and <em>“Setup and deploy Kubeflow”</em> sections in this <a href="https://www.kubeflow.org/docs/started/k8s/kfctl-k8s-istio/">installation guide</a>. After the installation, if we run</p><pre>kubectl -n kubeflow get pods</pre><p>we should see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/0*iKgj6Lkxb5v8_G1F" /><figcaption>Kubeflow pods up and running</figcaption></figure><p>We can see that our Kubeflow pods are up and running on our cluster. Note that this deployment is a one time process and in the future, these pods will be automatically created and deleted based on node availability.</p><h4><strong>Creating a TFJob</strong></h4><p>Now that we have Kubeflow installed and deployed on our cluster, we can use the <em>tf-operator</em> to create and run a <em>TFJob, </em>follow the steps below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/0*mxM-htBRuVgIXnPh" /><figcaption>Example of a training manifest.</figcaption></figure><ol><li>Assuming the availability of sufficient compute resources to run a training job, we can simply specify the number of cluster workers to create, the docker image every worker needs to pull and the training script that needs to be executed by the workers, all inside a training manifest. See the example manifest above for clarity.</li><li>We can also specify resource limits (such as allowable CPU and memory requests per worker pod) and also include <em>nodeSelector</em> configurations so that the “tensorflow” pods that run the training script always end up getting assigned to a specific node pool (e.g. a pool with GPUs). You must be careful to make sure that the workers have sufficient memory and CPU resources to run the job or you might end up seeing <em>Insufficient cpu</em> and <em>Insufficient memory</em> issues in the pod logs. See <a href="https://www.kubeflow.org/docs/components/training/tftraining/"><em>here</em></a> for more details about the TFJob resource.</li><li>Our <strong>&lt;script_to_be_executed&gt;.py, </strong>referred to in line 19 in the example training manifest above, executes `load_tf_records(..)` (explained in <a href="https://medium.com/p/549b6b6fb55/edit">Part I</a> of this series) and plugs in the returned<em> tf.data.Dataset</em> into the `fit(..)` function of the model whose graph operations are set up within the scope of the <em>MultiWorkerMirroredStrategy.</em></li></ol><p>Here, we have assumed that the reader has some level of familiarity with <a href="https://docs.docker.com/get-started/">Docker</a>.</p><h4><strong>Connecting the Pieces Together</strong></h4><p>So far, we have talked about all the different components of this workflow: data pipelines with <em>TFRecord</em> and <em>tf.data.Dataset</em>, the <em>MultiWorkerMirroredStrategy, </em>Kubernetes’ <em>TFJob </em>and<em> </em>Kubeflow’s<em> tf-operator</em>. But how do our model and the cluster workers interact? How does TensorFlow know the specification of our cluster and the availability of workers? How does everything we’ve seen so far fit together? This interplay between these different components is the last bit of information we need to understand.</p><p>When we initialize a <em>TFJob</em>, Google’s cloud AI platform automatically sets up a <em>TF_CONFIG</em> environment variable on every worker node in the cluster that executes the training job. It contains information such as the number of workers and task index for every worker, and essentially just points to the cluster specification. TensorFlow’s <em>MultiWorkerMirroredStrategy </em>uses this specification to understand worker roles.</p><p>Now, we have a reasonably good understanding of everything we need to run large-scale, distributed training of TensorFlow models. To execute the job, simply run</p><pre>kubectl -n kubeflow create -f &lt;path_to_training_spec&gt;.yaml</pre><p>and the distributed training routine will begin. You can look at the logs by running</p><pre>kubectl -n kubeflow logs &lt;worker-id&gt;</pre><h4><strong>Training Statistics</strong></h4><p>We trained our recurrent autoencoder on a training dataset with 2,235,385 instances where each instance is an array of shape (36, 10); with 36 timesteps and 10 dimensions per timestep. Note that this example is only for demonstration purposes and that the sample dataset is not that large. Our model had an encoder with two layers with [128, 32] GRU units. The decoder had a reversed architecture. Each layer was followed by <em>BatchNormalization</em> and <em>Dropout </em>layers with the exception of the final decoder layer. The final states of every layer in the encoder were merged layer-wise to create input states for the decoder. We set <em>batch_size_per_worker</em> to 1024 and experimented with 2, 4, 6 and 8 GPUs (one GPU per worker). We trained this model on our cluster with <em>n1-highmem-4</em> nodes, each having an NVIDIA-Tesla K-80 GPU. Below we visualize how epoch run times scale with the number of GPUs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*or-44YzEkGz_CBFj" /></figure><h3><strong>Conclusion</strong></h3><p>Running a large-scale, distributed model training involves a lot of moving parts and can be very overwhelming. We hope that this article provides clarity on the essential components of this workflow, and makes it easier to implement efficient input data pipelines for large volumes of data and to effortlessly scale computational workloads involved with model training using data parallelism. Visit <a href="https://medium.com/utility-machine-learning"><em>When Machines Learn</em></a> to find more technical guides for the working data scientist.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b459770e397b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/utility-machine-learning/a-guide-to-distributed-tensorflow-part-2-b459770e397b">A Guide to Distributed Tensorflow: Part 2</a> was originally published in <a href="https://medium.com/utility-machine-learning">When Machines Learn</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Guide to Distributed Tensorflow: Part 1]]></title>
            <link>https://medium.com/utility-machine-learning/a-guide-to-distributed-tensorflow-part-1-549b6b6fb55?source=rss----8f42171d82---4</link>
            <guid isPermaLink="false">https://medium.com/p/549b6b6fb55</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[distributed-computing]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[technical-guide]]></category>
            <dc:creator><![CDATA[Roshan Thaikkat]]></dc:creator>
            <pubDate>Fri, 09 Oct 2020 13:47:42 GMT</pubDate>
            <atom:updated>2020-10-16T13:22:24.875Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Guide to Distributed TensorFlow: Part 1</h3><h4>How to set up efficient input data pipelines for deep learning using TFRecord and tf.data.Dataset API</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ETljmU9scxtrE0kG" /><figcaption><em>Photo by</em><a href="https://unsplash.com/@pietrozj?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"><em> Pietro Jeng</em></a><em> on</em><a href="https://unsplash.com/s/photos/machine-learning?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"><em> Unsplash</em></a></figcaption></figure><h3><strong>TL;DR</strong></h3><p><em>This post is the first in a two-part series on large-scale, distributed training of TensorFlow models using Kubeflow. In this blog series, we will discuss the foundational concepts of a distribution strategy that supports data-parallelism, the tools and technologies involved in setting up the distributed computations and walk you through a concrete example highlighting the overall workflow. This post will provide the implementation details of an input data pipeline using TFRecord and tf.data.Dataset API for distributed model training.</em></p><h3>Deep Learning</h3><p>Deep learning has gained a lot of attention in recent years. The field has seen many exciting research papers coming out to open forums at a tremendous pace, some of which are setting incredible performance benchmarks on problems that were previously considered to be close to impossible. Industry practitioners are rapidly adopting the technology during this <em>age of implementation¹</em> and some even argue that deep learning models have the capabilities to exhibit human-level reasoning. This particular technology, it’s safe to say, is at the forefront of major groundbreaking AI developments.</p><p>If you’re a data scientist, you’ve probably had some exposure to the basics of how neural networks work. However, you might not have the background of an ML or DevOps engineer who typically oversees end-to-end machine learning pipelines and large-scale, cluster-wide computations. If you’re an independent data scientist, you might not have access to that kind of expert advice or resources.</p><blockquote>Wouldn’t it be nice if you could just take your experimental neural network models and scale them up with massive amounts of data, without having to rely on anyone to do it for you?</blockquote><p>This post is intended to save you effort, cost, and development time. We’ll describe a common use case and then, in as much detail as possible, talk about each of the necessary ingredients.</p><h3><strong>Problem setup</strong></h3><p>Let’s say we have raw sensor measurements from a fleet of thousands of machines or <em>assets</em>. Let’s assume that all this data sits in cloud storage and that we have all the necessary credentials for read/write access to this cloud storage. Specifically, we will consider each asset’s data to be a <em>parquet</em> or a <em>csv</em> file of several hundred megabytes. Lastly, let’s also assume that we have access to an operational cluster with private nodes, powered by <a href="https://cloud.google.com/kubernetes-engine">Google Kubernetes Engine</a>.</p><p>Our goal is to train a <em>recurrent</em> <em>autoencoder</em> for unsupervised latent state representation. This is a neural network that takes advantage of the temporal dynamics of our data to engineer useful features that can be used for other complicated learning tasks. For this article, it will be helpful to have some familiarity with <a href="https://dask.org/">Dask</a>, since we will not cover any of the instructions for setting up a Dask scheduler and workers on our on-premise cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*mqWbXAteMox1iX4_ewYK6Q.png" /><figcaption>The workflow we describe here involves training a model on data gathered from cloud storage. Training is distributed using the Google Kubernetes Engine.</figcaption></figure><h4><strong>TensorFlow</strong></h4><p>Google’s open-source Deep Learning library, <a href="https://www.tensorflow.org/">TensorFlow</a><em>,</em> is a go-to for many industry practitioners who want to build and deploy production-grade neural networks. We will use many of the excellent (but experimental) features of this library to scale up our model.</p><p>We assume a sufficient background in developing neural networks, therefore we use the notion of an abstract <em>Model </em>class that encapsulates the necessary functionality of a recurrent autoencoder. This model has an <em>encoder</em> that takes in an input of shape <em>(batch_size, num_timesteps, num_dimensions)</em> and compresses it to a latent state of shape <em>(batch_size, num_latent_state_dimensions) </em>by sequentially processing the data along the time dimension. There’s a <em>decoder</em> that tries to reconstruct the input by processing this latent state. As a result of minimizing the reconstruction error, the encoder is forced to come up with rich representations of our input data which can be used as features for other learning algorithms. We will use a subclassed <a href="https://www.tensorflow.org/api_docs/python/tf/keras/Model"><em>Keras Model</em></a> in this workflow.</p><h4><strong>Input pipeline</strong></h4><p>For distributed training with large amounts of data, we need efficient input pipelines that don’t need to read all of the data into memory. The recommended way to do this is to take advantage of the <em>tf.data</em> API. TensorFlow<em> </em>has the capability to treat the input function itself as a collection of nodes in a computational graph and applies all of the subsequent data transformations to symbolic tensors. The input function is invoked only during the model training iterations to return real-valued tensors.</p><p>Since we have to read and process data for each asset, it would be much faster to do this concurrently. There are some limitations to reading and processing data <em>online </em>that can lead to performance bottlenecks during training — our GPUs that do the actual computations end up suffering downtime if the preprocessing functions are computationally intensive. Also, we won’t be able to fully exploit our resources to parallelize this task. A more efficient alternative that allows for maximum GPU utilization during training is to apply the preprocessing function and save the input data <em>offline.</em> That way, the actual input function during model training would only involve reading in the preprocessed data. There are trade-offs between these two approaches. In this article, we focus on the second approach. We can also use open source scalers like Dask to parallelize this (<em>read -&gt; preprocess -&gt; save</em>) workflow.</p><p>Now there’s one last detail before we can look at code snippets that do this. TensorFlow<em> </em>also has the capability to read data in the <em>TFRecord </em>format very efficiently. A <em>TFRecord</em> file is essentially a collection of binary records wherein each record represents a single <em>serialized</em> instance of our input data.</p><p>Now, the overall pipeline becomes:</p><ol><li>Create batches of asset data records</li><li>For every batch, preprocess and serialize asset data in a distributed fashion using Dask (or other scalers)</li><li>Save each batch that contains serialized binary records to a <em>TFRecord</em> file.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/0*q-8k_hSDGXXZu7mx" /><figcaption>Minimal example of a data preprocessing function.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/0*7jZfa6ozkkYOAiEr" /><figcaption>This function will distribute`fn(..)` across cluster workers. The resulting data instances per asset are serialized in a distributed way. We’re using Dask’s vanilla map and gather strategy.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/0*HwHPWLjZQiIPIov0" /><figcaption>Create batches of assets, distribute the workload via `map_fn(..)` and save results using TFRecordWriter.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/0*t03ykSufmsN8BQ7V" /><figcaption>Array serializing functions.</figcaption></figure><p>In the above (minimal example) code snippets, we can see that the <em>preprocess_fn(..) </em>that accepts a single asset identifier and the cloud storage location, reads the asset-level data and performs some simple data preprocessing steps — standardizing and reformatting. We’re distributing this function at the batch-level using <em>map_fn(..). </em>We will further distribute <em>serialize_fn(..) </em>at the asset level. The <em>distributed_preprocess_fn(..)</em> simply orchestrates the process and repeatedly applies these functions to all batches of assets. The <em>serialize_fn(..) </em>converts arrays to bytes and then to <em>tf.Features</em> in order to serialize. Follow this minimal example workflow to efficiently preprocess and serialize data for training.</p><p>During the actual model training, we need to create a <em>tf.data.Dataset </em>and apply additional (but very simple) transformations to make it ready for training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*kucO9o5QD3a83QJB" /><figcaption>Load previously saved TFRecords</figcaption></figure><p>Here, we’re simply loading and parsing the (previously saved) records from a location that contains multiple <em>TFRecord</em> files. We’re further <em>repeating </em>this for a specified number of training epochs (for data availability throughout the training routine), <em>shuffling </em>the instances and <em>batching</em> them.</p><p>Now, our input data in the <em>tf.data.Dataset</em> format is ready to be passed into our model and we’re all set with our data pipeline to begin model training.</p><h3>The Next Step</h3><p>In this post we’ve explored some basic tools and techniques to prepare data for a distributed computation. In <a href="https://medium.com/utility-machine-learning/a-guide-to-distributed-tensorflow-part-2-b459770e397b">Part 2 of this series</a> we’ll learn how to use Kubeflow to distribute our computational workload across multiple cluster nodes, and we’ll provide concrete examples in a sample implementation. You can find this and more on <a href="https://medium.com/utility-machine-learning"><em>When Machines Learn</em></a><em>.</em></p><p><em>¹ The phrase “age of implementation” was coined by Kai-Fu Lee in his NY Times Bestseller, AI Superpowers. The book emphasizes the broad applications of deep learning to solve many practical problems today.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=549b6b6fb55" width="1" height="1" alt=""><hr><p><a href="https://medium.com/utility-machine-learning/a-guide-to-distributed-tensorflow-part-1-549b6b6fb55">A Guide to Distributed Tensorflow: Part 1</a> was originally published in <a href="https://medium.com/utility-machine-learning">When Machines Learn</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use data visualization to validate imputation tasks]]></title>
            <link>https://medium.com/utility-machine-learning/how-to-use-data-visualization-to-validate-imputation-tasks-b817ce538d53?source=rss----8f42171d82---4</link>
            <guid isPermaLink="false">https://medium.com/p/b817ce538d53</guid>
            <category><![CDATA[technical-guide]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[altair]]></category>
            <category><![CDATA[imputation]]></category>
            <dc:creator><![CDATA[Ben Dexter Cooley]]></dc:creator>
            <pubDate>Fri, 02 Oct 2020 13:01:55 GMT</pubDate>
            <atom:updated>2020-10-02T13:01:54.005Z</atom:updated>
            <content:encoded><![CDATA[<h4>Creating custom charts can help us better understand, validate, and improve imputation tasks in data science and machine learning.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c6nUYPPZYTRC4TymMdOTlQ.jpeg" /></figure><h3>TL;DR</h3><p><em>Imputation is a useful tool for machine learning, but validating results can be difficult. We can improve imputation tuning by applying more advanced data visualization techniques as shown in this article.</em></p><h3>Imputation in Data Science</h3><p>Data imputation is a common practice in machine learning. At a basic level, imputation is the practice of replacing a missing value with an estimated value, usually through mathematical inference. Within machine learning, there are many useful applications for imputation, including:</p><ul><li>Validating an existing model</li><li>Filling in missing values in raw data (data cleaning)</li><li>Using small amounts of data to generate unlimited amounts of data like it</li><li>Smoothing of features in a dataset</li></ul><p>For more details on how to apply imputation, <a href="https://medium.com/p/86edc8ffa82a/edit">check out this post</a>. In this article we’ll be looking at different methods of visualizing imputation in practice. Data visualization can provide a deeper understanding of how accurately your imputation results mirror raw data features.</p><h3>Visualizing missing values</h3><p>While many options exist for visualizing data in Python, we like to use <a href="https://altair-viz.github.io/">Altair</a> for data exploration. We use Altair for a number of reasons: it relies on the simplicity of the <a href="https://vega.github.io/vega-lite/">Vega-Lite</a> visualization grammar, has built-in interactivity, can be shared as HTML files, and uses a modular approach to creating subplots and dashboards.</p><p>The following examples will walk through a few methods to visualize imputation using Altair plots. Let’s take a look at a basic example first: say you have a set of raw data features that you want to use to train a classification model. We will use weather for simplicity. Most features have consistent data, but a few of them have missing or messy values. We can use imputation to fill these in and increase the accuracy of the model.</p><p>But before we can create brand new values, we want to make sure that our imputation can consistently predict values based on input data. To do this, we can redact rows within the dataset and then “fill them in” with imputation. We will compute these values using an HMM (for more applications of using HMM imputation, see <a href="https://medium.com/p/86edc8ffa82a/edit?source=your_stories_page-------------------------------------"><em>Imputation and its Applications</em></a>).</p><p>After imputation, we can use a standard scatter plot to compare what these new imputed values look like against the “true” values that were redacted. Here’s what we get from using Matplotlib to measure imputation results for a set of weather features: temperature, cloud cover, and energy produced.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jNFuToEEw9sysSFH" /></figure><p>This provides a general idea of how your imputed values compare to reality, but it’s difficult to identify any real pattern in the data. Moreover, the results get more difficult to interpret when we apply them to non-quantitative features such as weather summaries like “rainy” or “clear”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*m_hEh3vWFW8wdyq-" /></figure><p>As we can see above, the plot starts to get even more cluttered. The overlapping of “actual” and “imputed” values make it difficult to tell how well the imputation performed.</p><h3>Using Altair to visualize imputation</h3><p>Now let’s try updating our Matplotlib figures with Altair instead. We know that these features are all indexed by time. When visualizing timeseries data, it can help to maintain the continuous nature of the data by using lines instead of points.</p><p>That being said, if we were to connect every point exactly with a line, we will likely generate a lot of visual noise. Instead, we can rely on Altair’s interpolation feature to add a line to the plot that focuses more on the trend of the data, and less on the exact points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4QUIOPR_uBjGdajQh3TNIg.png" /></figure><p>As we can see, our new version gives us a few advantages: the timeseries nature of the data is now apparent and we can focus on the overall “signal” in our data rather than focusing too much on outliers. However, retaining the dots at a reduced opacity allows us to keep the exact data points while emphasizing the line more to the viewer’s eye.</p><p>To construct this plot, we rely on the layering features of the Altair library. Our scatter plot and line plot are effectively two separate charts overlaid onto one another. Here’s the feature dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wk25fv8PSNQgbVIg4NU9xw.png" /></figure><p>Our first step is to format the data in a way that Altair can read. Altair is designed to receive data in long-form format where each row represents a single observation. We will have to reshape our dataframes accordingly, since most machine learning tasks use data in the above wide-form format where each row contains measurements of multiple independent variables (for more on the difference between long-format and wide-format data, see <a href="https://altair-viz.github.io/user_guide/data.html#long-form-vs-wide-form-data">here</a>).</p><p>Using our imputed and redacted datasets, we can use the Pandas method pd.melt() to reshape a wide-format dataset into long-format:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44586809d9e5ba9d809630214368a0ae/href">https://medium.com/media/44586809d9e5ba9d809630214368a0ae/href</a></iframe><p>Now our dataset will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yDwcJSlP8EXrPRMgAtlOEw.png" /></figure><p>We’re ready to start plotting! To create our scatter plot, we start with a simple Altair object using mark_circle(). Crucially, we only want to look at one feature in this plot, so we can use the built in transform_filter() in Altair to grab a single variable like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ceb4436b2f8798f6c186a174088796d/href">https://medium.com/media/2ceb4436b2f8798f6c186a174088796d/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jSXg9xwcXeHmvut10_vXQg.png" /><figcaption>A scatter plot created with Altair.</figcaption></figure><p>Now we need to add the interpolation line in order to better highlight the signal in these patterns.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c656371c291c9176ba3831955dbf26f/href">https://medium.com/media/7c656371c291c9176ba3831955dbf26f/href</a></iframe><p>We now have two separate Altair objects stored in `circles` and `lines`. Because both charts use the same dataset, we can use Altair’s layering feature to simply combine the plots into a new variable by stacking them together.</p><pre>chart = circles + lines</pre><p>By calling your new chart, you should see the layered result. We can also append a title to our chart object with `properties(title=”My Title”)`:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BihSw1fj4-EurEOC30qjfQ.png" /></figure><h3>Visualizing categorical imputation</h3><p>So what happens when a feature contains categorical information instead of quantitative? Our original weather dataset contains a column titled “summary” with strings such as “rain”, “clear”, and “cloudy” to describe the weather at each timestamp.</p><p>Instead of treating this data the same way, we can measure our overall accuracy by aggregating across the time range of the dataset. Again, we care more here about our overall imputation performance, and less about the difference at each timestamp between “actual” and “imputed”.</p><p>First we need to reshape our categorical data. We can do this by:</p><ol><li>isolating our DataFrame to only rows with var == &#39;summary&#39;</li><li>using a Pandas pivot table to count instances of each weather summary for ‘actual’ and ‘imputed’ respectively</li><li>melt this pivot table into a long-format for Altair.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2672fe0f887d150063b9b07a6205a32b/href">https://medium.com/media/2672fe0f887d150063b9b07a6205a32b/href</a></iframe><p>And now we construct the bar chart. This will require using Altair’s row feature to effectively create “mini bar charts”, one for each category, and then stack them on top of each other.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5eae92b0d61c3672a7183c447c8ca40/href">https://medium.com/media/e5eae92b0d61c3672a7183c447c8ca40/href</a></iframe><p>Calling bars will now give you this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yjsXwP85_hQde5Q6dwLafg.png" /></figure><p>As we can see, a clear comparison emerges between our “actual” and “imputed”. Unlike the first type of plot, this method allows us to see, for example, how our imputation might be favoring the “Clear” label more so than others.</p><p>When validating imputation results, it’s useful to generate some metrics to measure success. Above, we are validating based on actual counts of data, but we can also score our imputation using calculated metrics. Our bar plots show us how many times we imputed the correct summary label, but it doesn’t necessarily tell us how<em> accurate</em> (or in this case, at what point in time) we labeled this data.</p><p>At a basic level, we want to ask the question: <em>how well did I impute compared to if I had just done it randomly?</em> We can then compute a ratio of raw accuracy compared to expected accuracy, which compares how well the imputations performed relative to just filling in the most common value into each empty spot.</p><p>When combined with our bar plot, this new metric can give us the context we need to better validate our imputation results. We can also normalize our metric from a score of 0 to 1 for simplicity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QZmxa9JI31TBpPUsKHP7Fg.png" /></figure><p>As we can see, the subplot at the bottom now reveals more information. Our normalized score measures against “random guessing” as a worst-case baseline, so we put this at the zero mark. And since these metrics are all relative, we remove the number labels at the ticks for simplicity. Adding labels for a “minimum acceptable” and “best possible” score also provides a helpful context when sharing this plot with other team members unfamiliar with the data. Our model performed considerably better than filling in these summary labels at random.</p><p>We can apply this same validation plot technique to our numeric variables too. For these features, we can measure success with a metric related to the average z score and another metric related to the average log likelihood.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6UnK-uyti7eTDs4ADa1syA.png" /></figure><p>Again, we see that our model performed considerably better than random in both metrics.</p><p>The dot range plot displaying our metrics is a useful tool to output validations in a more visual format. Adding the labels requires a bit more lifting using Altair, but can be done by layering each element (just like making a chart) of the plot on top of one another using Altair’s mark_text method. Here’s how to create the basic dot range plot using Altair:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a440ff52a933e61a7b386f20c1cd6e9c/href">https://medium.com/media/a440ff52a933e61a7b386f20c1cd6e9c/href</a></iframe><h3>Conclusion</h3><p>Imputation is a valuable technique that can be applied across a wide variety of tasks. Smart visualization of these results can help you better understand and improve your model results. Moreover, when you design plots for others as well as yourself, you can increase collaboration across the team and reinforce confidence in your model among stakeholders.</p><p>For more articles on using imputation, checkout our posts on <a href="https://medium.com/p/86edc8ffa82a/edit?source=your_stories_page-------------------------------------"><em>Imputation and its Applications</em></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b817ce538d53" width="1" height="1" alt=""><hr><p><a href="https://medium.com/utility-machine-learning/how-to-use-data-visualization-to-validate-imputation-tasks-b817ce538d53">How to use data visualization to validate imputation tasks</a> was originally published in <a href="https://medium.com/utility-machine-learning">When Machines Learn</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Imputation and its Applications]]></title>
            <link>https://medium.com/utility-machine-learning/imputation-and-its-applications-86edc8ffa82a?source=rss----8f42171d82---4</link>
            <guid isPermaLink="false">https://medium.com/p/86edc8ffa82a</guid>
            <category><![CDATA[imputation]]></category>
            <category><![CDATA[data-processing]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[introductory]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Anna Haensch]]></dc:creator>
            <pubDate>Fri, 25 Sep 2020 13:03:07 GMT</pubDate>
            <atom:updated>2020-09-25T13:03:03.441Z</atom:updated>
            <content:encoded><![CDATA[<h4>Statistically valid imputation as a tool for data preprocessing, model validation, and generative modeling.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5JK7GOnfNTMAeIxeY_Ig7w.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@jackywatt?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jacky Watt</a> on <a href="https://unsplash.com/s/photos/circles?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>TL;DR</h3><p><em>Imputation is the process of inferring unknown data. It has useful applications in model validation, data preprocessing, and generative modeling. When dealing with sequential data, the hidden Markov model provides one of many possible tools for imputation; it is especially useful in practice because of its generative nature.</em></p><h3>Dealing with missing data</h3><p>In data science, it is very common to encounter incomplete, missing, and insufficient data. In such a case, <a href="https://medium.com/utility-machine-learning/an-introduction-to-imputation-solving-problems-of-missing-and-insufficient-data-1814c90c3545"><em>imputation</em> is the practice of inferring data where it is not explicitly known</a>. Some naive methods for imputation include filling in missing values with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.fillna.html">the previous or next non-missing value</a>. It’s also common to <a href="https://scikit-learn.org/stable/modules/impute.html">fill in missing data with fixed values</a> such as 0 or the mean values of the dataset. These naive techniques may have some utility, depending on the goal of the imputation, but they are sure to introduce bias into the data. For sequential data in particular, these methods ignore important and valuable contextual information. More sophisticated forms of imputation involve fitting the known data to a function — this method is called <a href="https://en.wikipedia.org/wiki/Interpolation">interpolation</a> — or more generally, fitting the known data to a mathematical model, and using statistical inference to determine the missing values. Before we talk about some explicit goals of imputation, let’s consider what might go wrong with naive imputation.</p><h3>Why good imputation matters</h3><p>Any method of imputation carries with it a degree of uncertainty, since supplying data from inference rather than from actual measurement is certain to introduce some amount of error. One limitation comes from the necessary <a href="http://yaroslavvb.com/papers/rubin-imputation.pdf">trade-off between informed statistical inference and simply “guessing correctly” most often</a>.</p><p>This seems like a minor distinction, but consider a scenario where a wind turbine has an alarm sensor that is “off” for 99% of the time. If we impute missing data for the alarm sensor by simply setting missing values to “off” we are guaranteed to have an accuracy of at least 99%, which seems good.</p><p>However, this is a statistically invalid method since the nominal alarm rate is guaranteed to be different from the actual alarm rate, and furthermore, forecasting with this method leads to the assumption that the alarm state will never be triggered, which could be disastrous. Therefore it’s important to impute in a statistically valid way, and in a manner that considers the context of the data and the purpose of the imputation. In what follows, we discuss three possible use cases for imputation.</p><h3>Model validation</h3><p>One preliminary use of imputation is to validate a trained model. By artificially redacting data, then imputing the missing data, it’s possible to get a sense of how well the model understands the data by validating the accuracy of the imputed data against the redacted data. This is a useful tool for understanding the overall fitness of a model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oQ28_7J6VtnwEnK_Q4yGyQ.png" /><figcaption>Diagram showing how imputation is used to validate a trained model.</figcaption></figure><p>A well-trained model will impute values that — in the best case — equal the original value. In a more likely case, imputed values are as statistically valid as the original value, given everything we know.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*dYuLhOfi1o3j-zxvjHp2tA.jpeg" /><figcaption>A sample visualization showing model validation from our companion post, “<em>H</em>ow to use data visualization to validate imputation tasks”.</figcaption></figure><h3>Data preprocessing</h3><p>Imputation is also a useful tool for data preprocessing. It is not uncommon to receive data with incomplete or missing observations. Using statistically informed imputation, these values can be imputed by considering the probability distribution of possible values given the known observations surrounding the missing data points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*laO5MWyCMBfbyencmwKPTQ.png" /><figcaption>Diagram showing how imputation is used to fill missing or incomplete data.</figcaption></figure><p>The tools that allow imputation to be used for data preprocessing can also be used for short-term forecasting, by predicting “next” observations based on the current set of observations.</p><h3>Generative modeling</h3><p>For a model with an underlying <a href="https://en.wikipedia.org/wiki/Generative_model">generative</a> structure, imputation is an important tool for data generation. A model is generative if it models the joint probability distribution of both observations and target data. Because of this property, generative models have been used to great effect in tasks such as <a href="https://github.com/Newmu/dcgan_code#walking-from-one-point-to-another-in-bedroom-latent-space">image</a> and <a href="https://web.stanford.edu/class/archive/cs/cs224n/cs224n.1174/reports/2737434.pdf">text</a> generation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h1uiwCdl1Vrhs38XIsihaQ.png" /><figcaption>Diagram showing how imputation is used to generate a new dataset with similar features and values to the original one.</figcaption></figure><p>Moreover, since generative models give a probability distribution over the complete data — in the case of hidden Markov models this means both observations and hidden states — with just enough data for initial training, a model can be used to generate an unlimited amount of data like it.</p><h3>Better imputation with hidden Markov models</h3><p>The hidden Markov model (HMM) is an important tool for <a href="https://medium.com/utility-machine-learning/using-hidden-markov-modeling-to-detect-seasonality-in-sequential-data-3c059649eb70">modeling sequential data</a>. It works by detecting hidden patterns in multivariate sequential data that arise by considering not only the characteristics of isolated observations, but also the observations in sequence.</p><p>In this way the HMM captures not only correlations between variables but also between observations that are close in time, modeled via underlying “hidden states”. This information is encoded in terms of transition probabilities (i.e. likelihood of transitioning from one hidden state to the next) and emission probabilities (i.e. likelihood of seeing a given observation given a fixed hidden state).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n4xXAwOWDGu7eIB2bbq_-A.png" /><figcaption>Diagram showing how the HMM identifies hidden states through time. For more information on how HMMs work, see our previous post <a href="https://medium.com/utility-machine-learning/using-hidden-markov-modeling-to-detect-seasonality-in-sequential-data-3c059649eb70">“Using Hidden Markov Models to Detect Seasonality in Sequential Data”</a>.</figcaption></figure><p>An HMM is trained using the <a href="https://en.wikipedia.org/wiki/Baum%E2%80%93Welch_algorithm">Baum-Welch expectation-maximization algorithm</a>, and once trained can be a powerful tool for imputation. For any incomplete observation, an HMM can be used to determine not only the most likely hidden state by using transition probabilities, but also the most likely observation for that state using emission probabilities.</p><p>By determining not only the relative likelihood of hidden states, but also the corresponding likelihood of observations, the HMM can be used to fill in missing values and generate data.</p><p>For any imputation method, it is helpful to have a sense of the technical underpinnings of the methodology to get a true understanding of its capabilities and limitations. In an upcoming post on <a href="https://medium.com/utility-machine-learning"><em>When Machines Learn</em></a> we’ll dive deeper into the technical methodology of imputation using hidden Markov models.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86edc8ffa82a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/utility-machine-learning/imputation-and-its-applications-86edc8ffa82a">Imputation and its Applications</a> was originally published in <a href="https://medium.com/utility-machine-learning">When Machines Learn</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Jax to streamline machine learning optimization]]></title>
            <link>https://medium.com/utility-machine-learning/using-jax-to-streamline-machine-learning-optimization-d0da2f53a9fb?source=rss----8f42171d82---4</link>
            <guid isPermaLink="false">https://medium.com/p/d0da2f53a9fb</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Sam McCormick]]></dc:creator>
            <pubDate>Fri, 11 Sep 2020 19:01:43 GMT</pubDate>
            <atom:updated>2020-09-11T19:36:44.469Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to use Jax to streamline machine learning optimization</h3><h4>Speed up your optimization processes and reduce development time with this open source Python library.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6fWVDcia6t6e5-yKbZQgkw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@traf?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Traf</a> on <a href="https://unsplash.com/s/photos/speed?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><strong>TL; DR:<em> </em></strong><em>Without reliable optimization methods, training ML models is infeasible or too slow to be practically useful. Many of the most powerful optimization methods require calculating loss function derivatives in order to efficiently search the space of possible parameter values. However, computing derivatives of complicated functions is tedious, time-consuming, and prone to human error. Jax is an open-source Python library that provides an automated method for computing derivatives, reducing development cycle time and improving the readability of code.</em></p><h3>Optimization for ML: an overview</h3><p>Many machine learning problems can be boiled down to the following steps:</p><ul><li>Specify a model with parameters θ that takes in input data and returns a predicted value or set of values.</li><li>Specify a loss function that captures how dissimilar the predictions of a model are compared to observed “ground truth” data (of course, this is highly problem-dependent).</li><li>Find the set of parameters θ that minimize the loss function using an optimization routine.</li></ul><p>Consider the case of linear regression with two independent variables <em>x1</em> and <em>x2</em>. The model specification is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*FsG0SZUXLt4ehsI9pvguCQ.png" /></figure><p>Here, the β values represent the parameters that need to be optimized (taking the place of θ in our more general description above) , ε is an error term that represents uncertainty, and <em>y</em> is the “true” value that we’re trying to predict. The canonical loss function for linear regression is the sum of squared errors:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*5LoKHvFylwpPmTBmnqYXLQ.png" /></figure><p>This applies across all of our <em>n</em> data points. Therefore, we’d like to pick the β values such that this value is minimized. In the specific case of linear regression, we can actually solve for the β values analytically using linear algebra. However, in most cases, finding an analytic solution in this way is not possible. Therefore, we turn to optimization methods which allow us to iteratively search for the best parameter values that minimize the loss function for whatever problem we’re trying to solve.</p><h3>Why do we need derivatives?</h3><p>The space of possible parameter values is usually infinite, so we need a clever way to search for the optimal parameters. Consider the analogy of a blind person lost in the hills who wants to get back to the valley where they parked their car. (Imagine the hills are completely smooth and there are no obstacles to contend with). At each point, they can sense the slope of the hill, and so they proceed by walking downhill, re-calibrating every so often to figure out the direction of the steepest downwards descent and then walking in that direction.</p><p>In this analogy, the person’s elevation corresponds to the loss function they want to minimize, and the x and y coordinates of the direction they walk in represent the two parameters of this “model”. This is the essence of many iterative derivative-based optimization methods: by understanding the topography of the region in parameter space, one can determine the direction that most quickly decreases the loss function and hopefully reach the global minimum most quickly.</p><h3>How can Jax help?</h3><p>For many machine learning models, calculating derivatives of loss functions by hand is downright painful. Online tools such Wolfram Alpha can help accelerate this process, but they still require the user to write Python code to encode the derivative correctly. This isn’t so hard for scalar data inputs, but in practice many machine learning models take vectors or matrices as input, and one incorrectly applied dot product or summation can lead to an incorrect derivative that will crash the optimization routine. If only there was a way to get the computer to do all of this hard work for you….</p><p>Enter Jax, an open-source library created by Google that can automatically compute derivatives of native Python and NumPy¹ functions. This means that as a user, you can write numerical functions in Python and use Jax to automatically compute derivatives (including higher-order derivatives!) and use them as input to optimization routines.</p><p>Under the hood, Jax makes use of the technique of autodifferentation, a topic that falls squarely outside the scope of this post (<a href="https://towardsdatascience.com/automatic-differentiation-explained-b4ba8e60c2ad">this blog post</a> gives a helpful introduction, though). The good news is, you don’t have to understand anything about how autodiff works² in practice to use Jax — you just need to know the basics of how to set up an optimization problem!</p><p>Let’s walk through a real-life example of how Jax can be used to simplify the implementation of a machine learning model.</p><h3>Using Jax for fitting Weibull mixture models to data</h3><p>One of Tagup’s main algorithmic approaches for improving the decision making of asset managers is our time-to-event (TTE) modeling capabilities. Our TTE models use the unified data history of an asset to predict time until certain events occur such as machine failures, preemptive removals, or maintenance actions (for the remainder of this post, we will discuss the specific case of predicting time until failure, commonly known as <em>survival modeling</em>).</p><p>Our convex latent variable (CLV) model works by first fitting a parametric distribution to observed asset lifetimes and then using other available data (nameplate data, sensor readings, weather, etc.) to scale that distribution which we refer to as our <em>base hazard</em>. In future posts, we will discuss our approach to time-to-event modeling in detail (this also involves interesting optimization techniques!), but for the purpose of this post, we will focus on the simpler sub-problem of fitting a distribution to observed machine lifetimes.</p><p>One of the most common distributions used for modeling machine lifetimes is the <a href="https://en.wikipedia.org/wiki/Weibull_distribution"><em>Weibull distribution</em></a>, which is a very flexible distribution that is governed by only two parameters. (See our <a href="https://www.tagup.io/blog/ai/survival-analysis-part-1-the-weibull-model">previous post</a> for a brief introduction to survival modeling and an explanation of fitting a Weibull model to data.)</p><p>However, consider a fleet of assets that contains two distinct sub-populations with different means and variances of lifetimes. A simple Weibull model won’t be able to fit this data very well, because the data is really a <a href="https://en.wikipedia.org/wiki/Mixture_model#:~:text=In%20statistics%2C%20a%20mixture%20model,which%20an%20individual%20observation%20belongs."><strong>mixture</strong></a> of multiple distributions. This inspired us to create a tool for fitting <em>Weibull mixture models </em>to data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b6L3GitRB2hsqIsTbvDjaw.gif" /><figcaption>A Jax-powered optimization routine learning the optimal Weibull mixture model parameters from synthetically generated asset lifetimes. By looping through the predicted distribution at each iteration, we can see how the routine “learns” the true distribution from which the data was generated.</figcaption></figure><p>A quick literature review turned up<a href="https://www.sciencedirect.com/science/article/pii/S0307904X12002545"> this research paper</a> for doing just that. However, the optimization routine outlined in the paper didn’t look appealing to implement in Python:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*uy79oQw_Kz1bYpr4X7HwNQ.png" /></figure><p>How could we avoid the painful process of turning the derivatives into code? The answer, of course, is to use Jax:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PiKOC97JTW0TH5pNpj8raw.png" /><figcaption>An example of computing derivatives of an arbitrary function using Jax.</figcaption></figure><p>Let’s briefly run through what’s going on in this function, the purpose of which is to compute the hazard³ as a function of model parameters and time since install as well as derivatives of this function if requested.</p><ol><li>Since <em>compute_hazard</em> is a function of multiple parameters, the derivatives required for optimization are matrices known as the <a href="https://en.wikipedia.org/wiki/Jacobian_matrix_and_determinant">Jacobian</a> (first derivative) and <a href="https://en.wikipedia.org/wiki/Hessian_matrix">Hessian</a> (second derivative), hence the variable names.</li><li>The Jax function <em>grad</em> is used to compute the first derivative of the hazard function, while <em>vmap </em>automatically<em> </em>vectorizes the gradient computation across the inputs (see docs and examples <a href="https://jax.readthedocs.io/en/latest/notebooks/autodiff_cookbook.html">here</a>).</li><li>Lastly, <em>jacfwd</em> and <em>jacrev </em>are used in succession to compute the Hessian matrix if requested by the user.</li></ol><p>Wow. In a few simple lines of code, we were able to compute the first and second derivative of the hazard function. Now, all we have to do is pass functions for computing loss and its derivatives to an optimization routine (the specifics of which will be detailed in a future post), and voila, we’re able to find the optimal parameters!</p><h3>Conclusion</h3><p>Optimization is an essential part of making any machine learning problem feasible. Derivative-based optimization methods are by far the most common and reliable approaches used, but require that derivatives be worked out by hand which is often quite tedious and prone to error.</p><p>Jax is an open-source library that seamlessly integrates with Python and uses autodifferentiation to efficiently compute derivatives of complex functions, obviating the need to calculate them manually. It generalizes to many classes of problems common in machine learning and is a very useful tool for data scientists who write custom optimization routines.</p><p>In a future post, we’ll talk more about some considerations and limitations of Jax which will hopefully help you avoid some of the pitfalls we ran into when getting familiar with the library.</p><p><em>¹ NumPy is a widely used Python package that provides efficient implementations for numerical computations of the type often required by machine learning models.</em></p><p><em>² Jax does have some important limitations that users have to be aware of, though — these will be described in a future post.</em></p><p><em>³ In the context of survival modeling, the </em><a href="https://en.wikipedia.org/wiki/Survival_analysis#Hazard_function_and_cumulative_hazard_function"><em>hazard function</em></a><em> represents the probability that an asset fails in period t+1 given that it has lived up until time t. Hazard is convenient to work with for two reasons: the likelihood function that we seek to optimize is a function of hazard; and all statistics of interest (failure probability, expected RUL) can be derived from hazard.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0da2f53a9fb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/utility-machine-learning/using-jax-to-streamline-machine-learning-optimization-d0da2f53a9fb">Using Jax to streamline machine learning optimization</a> was originally published in <a href="https://medium.com/utility-machine-learning">When Machines Learn</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Introduction to Imputation: Solving problems of missing and insufficient data]]></title>
            <link>https://medium.com/utility-machine-learning/an-introduction-to-imputation-solving-problems-of-missing-and-insufficient-data-1814c90c3545?source=rss----8f42171d82---4</link>
            <guid isPermaLink="false">https://medium.com/p/1814c90c3545</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[engineering]]></category>
            <dc:creator><![CDATA[Ben Dexter Cooley]]></dc:creator>
            <pubDate>Thu, 30 Jul 2020 15:44:57 GMT</pubDate>
            <atom:updated>2020-07-30T15:52:32.888Z</atom:updated>
            <content:encoded><![CDATA[<h4>Missing data is a common problem. Here’s how imputation can help.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TuT4uLOT8PT_Zct9qwn5yw.png" /><figcaption><em>Photo with modifications by</em><a href="https://unsplash.com/@jeisblack?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"><em> Jason Blackeye</em></a><em> on</em><a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"><em> Unsplash</em></a></figcaption></figure><p>For many data scientists, analysts, or engineers, dealing with missing or bad data is an everyday experience. A dataset could have missing values for a key period of time, or perhaps the dataset contains outlier values that need to be corrected.</p><p>Often, you may look for new data or work with small subsets of the dataset. However, the complete data set, after correcting for its limitations, can hold real insights. What can you do to preserve the integrity of the data while still mining it for useful signal?</p><p>Imputation can help solve this problem. Over the coming weeks, the <a href="https://www.tagup.io/">Tagup</a> team will publish several articles in a series on imputation, its applications, and how to apply it on a practical level.</p><p>In this article, we’ll briefly discuss what imputation is, how it can be useful, and how imputation using machine learning models differs from other standard methods of dealing with missing or insufficient data.</p><h3>The process of imputation</h3><p>Imputation can be thought of as the process of looking at a row of missing data and then “inferring”, or making a reasonable guess, as to what value should be in its place. In fact, you may have been doing imputation for a long time without knowing the name. You can replace missing data in many ways such as taking a running average or using interpolation between values. A common and simple form of model-based imputation is called “mean imputation”: when you see a missing value in a dataset, you simply take the average value for the entire column of data and insert it for all missing data points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XqiH9qnRofO3Luzu" /><figcaption><em>Diagram showing the process of applying mean imputation to a column of data.</em></figcaption></figure><p>All methods of imputation have different sets of pros and cons (discussed later in the article). Basically, you can think of imputation as a set of rules: if a dataset contains missing values, apply a certain calculation to create a “best guess” replacement.</p><h3>Why imputation is useful</h3><p>Data that is ideal for imputation comes in many different forms — NaN values, infrequent timestamp records, and improperly formatted numbers, to name a few. But even with these flaws, there still could be significant insight in the existing dataset. With imputation, new signals can be found in datasets with missing data (among other data quality limitations).</p><blockquote>Imputation is a tool to recoup and preserve valuable data.</blockquote><p>Imputation allows you to:</p><ul><li>Troubleshoot what may be happening in periods of missing data by simulating possible values</li><li>Synchronize time scales for machine learning/modeling</li><li>Smooth extremely noisy data</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fnt8Q9obXk4BqUwa" /><figcaption><em>A sample measurement from the Tagup application, showing a period of missing data at the gray shaded regions of the chart. This data should be considered pre-imputation; for raw data in this chart, we are only applying interpolation (for predicting values at unsampled locations) between two data points instead of model-based imputation (to fill in missing values with new values).</em></figcaption></figure><p>For example, imputation can be used to fill in missing sensor measurements if you lose data communication for a day. By identifying the time range (one day) and frequency of expected measurements, you can use imputation to simulate what “normal” operating conditions would look like for this time.</p><h3>Imputation with machine learning</h3><p>There are a variety of imputation methods to consider. Machine learning provides more advanced methods of dealing with missing and insufficient data compared with traditional methods. We will be covering some of these advantages in detail throughout our upcoming series on data imputation. A few existing methods include:</p><ul><li>Mean or median imputation</li><li>Imputation using most frequent values</li><li>Linear regression imputation</li><li>Multivariate imputation by chained equation (MICE)</li><li>k-nearest neighbors algorithm (k-NN)</li><li><a href="https://medium.com/utility-machine-learning/using-hidden-markov-modeling-to-detect-seasonality-in-sequential-data-3c059649eb70">Hidden Markov Model</a> (HMM)</li></ul><p>For now, it’s useful to consider the following example: say you are monitoring a fleet of assets for a critical threshold alarm and you lose data communications for one of many sensor measurements. The missing data totals to about 5% of the total time range. A traditional method of imputation, such as using the mean or perhaps the most frequent value, would fill in this 5% of missing data based on the values of the other 95%.</p><p>But this traditional approach has an inherent risk: alarms and thresholds are infrequent and often short. Certain “spikes” or “anomalies” in data, by their very nature, cannot be predicted based on what is considered an average value in the dataset.</p><p>Machine learning methods such as the k-nearest neighbors algorithm (k-NN) or Hidden Markov Model (HMM) provide a more complex set of calculations for imputation. Unlike traditional methods, it also gives you more imputing abilities such as:</p><ul><li>Accounting for correlation between different features, rather than treating them separately</li><li>Accounting for uncertainty bounds</li><li>Imputing categorical values as well as numerical</li></ul><p>In future posts within this series, we’ll break down in more detail the various applications of imputation using machine learning. We will also look at how to best visualize imputation results, and how to create and tune an imputation model.</p><p>Stay tuned for more articles on imputation methods by following <a href="https://medium.com/utility-machine-learning">When Machines Learn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1814c90c3545" width="1" height="1" alt=""><hr><p><a href="https://medium.com/utility-machine-learning/an-introduction-to-imputation-solving-problems-of-missing-and-insufficient-data-1814c90c3545">An Introduction to Imputation: Solving problems of missing and insufficient data</a> was originally published in <a href="https://medium.com/utility-machine-learning">When Machines Learn</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Hidden Markov Models to Detect Seasonality in Sequential Data]]></title>
            <link>https://medium.com/utility-machine-learning/using-hidden-markov-modeling-to-detect-seasonality-in-sequential-data-3c059649eb70?source=rss----8f42171d82---4</link>
            <guid isPermaLink="false">https://medium.com/p/3c059649eb70</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[hidden-markov-models]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[clustering-algorithm]]></category>
            <dc:creator><![CDATA[Anna Haensch]]></dc:creator>
            <pubDate>Fri, 19 Jun 2020 14:14:47 GMT</pubDate>
            <atom:updated>2020-07-20T13:28:49.948Z</atom:updated>
            <content:encoded><![CDATA[<h4>Comparing techniques for finding and interpreting cyclic trends in sequential data with HMMs.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FzLcYtRtbaTTcxj2TWfvhw.jpeg" /><figcaption>One tree in four seasons. Image via Wikimedia Commons courtesy of<a href="https://en.wikipedia.org/wiki/Season#/media/File:B%C3%A4ume_Jahreszeit_2013.jpg"> J. Hagelüken</a></figcaption></figure><h4><em>TL;DR</em></h4><p><em>In this post we will discuss the advantages of performing seasonal clustering on time series data with a hidden Markov model as compared to a traditional spatial clustering algorithm. We further explore how applying this clustering improves possible applications to important machine learning tasks such as operating mode classification.</em></p><h3>Understanding the Seasons</h3><p>The seasons winter, spring, summer, and fall, are a mechanism that we use for both classifying weather conditions and describing the time of year. Humans have long been aware of the cadence of the seasons, and have a reasonably consistent way of interpreting them in terms of local weather patterns; we know that there are four of them, we know they occur annually in a predictable, sequential way, and we know some general characteristics of the weather for each of the seasons.</p><p>In the northeastern United States, summer is usually warm, while winter is usually cold; trees tend to bud in the spring and turn brown in the fall.</p><p>What’s not obvious is whether the definition of seasons is something inherent to the weather itself, or something that requires some presupposed knowledge of the cyclic nature of seasons.</p><blockquote>If we didn’t know that seasons were cyclic, could we still detect the seasons from the weather?</blockquote><p>In this post, we will explore whether it’s possible to reclaim the definition of seasons, directly from raw data through machine learning.</p><h3>Finding the Seasons in Data</h3><p>Using weather data from <a href="https://darksky.net/forecast/40.7127,-74.0059/us12/en">DarkSky</a>, gathered every 12 hours from January 1, 2019 through December 31, 2019 for Cambridge, MA, as well as data from an array of nine 300 Watt Solar panels located in Cambridge, we will consider different types of models that have the potential to learn and identify seasons. We will also consider models that can solve the slightly more complicated problem of correctly identifying the season on seasonably uncharacteristic days.</p><figure><img alt="Raw data variables used as features in training our Machine Learning model." src="https://cdn-images-1.medium.com/max/1024/1*NJr6IgU_WSa6ahBMTdFu0Q.png" /><figcaption>The uppermost plot above gives the difference in 7-day rolling mean temperature over 30 days. In addition the five continuous measurements above, we also have a categorical measurement giving one of 18 narrative summaries of the weather for each 12-hour block, such as, “heavy rain” or “humid and partly cloudy.”</figcaption></figure><p>From the plots above, we can see that raw weather data exhibits a clear seasonality. If we were to cluster dates together by some measure of similarity, it would be reasonable to expect, for example, the warm, sunny, high UV index days of June, July and August to belong to the same cluster.</p><h3>Spatial Clustering Techniques</h3><p>One simple method of clustering is <a href="https://en.wikipedia.org/wiki/K-means_clustering">K-means clustering</a>, which partitions data into groupings by assigning each observation to a cluster with the closest mean value. We refer to such an algorithm as a <em>spatial clustering technique</em>, since the observed values are considered as points in some high dimensional space — 6 dimensions, in this case — and the clusters are related to their position in this space. In the plot below we perform K-means clustering on the data and specify four clusters to reflect the four seasons we hope to discover.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ze7aVHdcwdfzOPmfMXkpzQ.png" /><figcaption>Clustered states identified in the data with the K-means clustering algorithm.</figcaption></figure><p>At first glance, the plot above doesn’t immediately demonstrate seasonal clustering. However, looking closely, we see that in certain date ranges there are dominant clusters which are likely groupings of days which are most typical to the season. For example, cluster 2 is dominant in the summer. A weakness of this algorithm is that it’s not sensitive to outliers. The algorithm has no way of understanding that a cold day in August is different from a cold day in February.</p><p>To counter this, we can turn to a more advanced spatial clustering algorithm, such as <a href="https://hdbscan.readthedocs.io/en/latest/how_hdbscan_works.html">HDBSCAN</a>, which draws a distinction between core points and outliers. For the purposes of weather classification, the outliers can be thought of as anomalies in the data. Performing HDBSCAN clustering on our data leads to the labeling of seasons below, which we can see comes fairly close to our conception of the seasons, particularly in the clustering of summer days.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HALysFUrx4gjNt6ZVLSpcQ.png" /><figcaption>Clustered states identified in the data with the HDBSCAN clustering algorithm.</figcaption></figure><p>However, this still leaves us with the problem of assigning seasons to the anomalous days. Spatial clustering algorithms do not take into account the sequential nature of the data, in which there is still a great deal of signal to be found. For example, an unusually hot day can often be classified as such by comparing it to the most recent typical day. For this task, we will introduce hidden Markov modeling.</p><h3>Hidden Markov Modeling</h3><p>A <em>Markov chain</em> is a series of events (also called <em>states</em>) in which the probability of the next event depends only on the current state. If we loosely categorize all possible weather scenarios into four different types, we can consider the series of weather types for each 12 hour period over one year as a Markov chain.</p><p>In this way, we can give some measure to the likelihood of the weather type tomorrow given the weather type today by considering the various transition probabilities.</p><p>Modeling the changing weather in this way gives a minimal backbone from which we can describe the changing of the seasons. In particular, we can tune it to be sensitive to the fact that day after day, the season tends to stay the same, and the seasons must follow one after the other in an ordered way.</p><p>In our example, we pretend not to know the seasons for each day, but rather, we hope to infer them solely from the observed data measurements. Therefore, in this example the Markov chain is a sequence of <em>hidden states</em>. In general, a system where a series of hidden states satisfying the Markov rule have a corresponding series of observations is called a <a href="https://www.ece.ucsb.edu/Faculty/Rabiner/ece259/Reprints/tutorial%20on%20hmm%20and%20applications.pdf">hidden Markov model</a> (HMM). In its most generic rendering, an HMM can be visualized as in the diagram below, where at each time <em>t</em> we have observed data,<em> X(t)</em>, and a hidden state, <em>Z(t)</em>.</p><figure><img alt="Graphical representation of a hidden Markov model." src="https://cdn-images-1.medium.com/max/1024/0*8T1XguoIrb8tG8mK" /><figcaption>Graphical representation of a hidden Markov model.</figcaption></figure><p>An HMM has three important parameters associated with it:</p><ul><li>The <em>initial state probability</em>, which gives the probability of each of the hidden states at the first recorded timestamp.</li><li>The <em>emission probability</em> which gives the probability of the observed data (e.g. the weather), given each of the hidden states.</li><li>The <em>transition probability matrix</em> which gives the probability of transitioning from one hidden state to another at any given time.</li></ul><p>Using the celebrated <a href="https://en.wikipedia.org/wiki/Baum%E2%80%93Welch_algorithm">Baum-Welch expectation-maximization (EM) algorithm</a>, we can use the observed raw weather data to train an HMM to learn optimal initial state, emission, and transition parameters. The EM algorithm is an iterative process of optimizing model parameters by incrementally optimizing the likelihood of the observed data. For somewhat technical reasons, the algorithm is guaranteed to terminate, but will only terminate at locally optimal model parameters.</p><p>In practice, this means that the outcome of EM is dependent on the choice of initializing model parameters. It’s important to <a href="https://cran.r-project.org/web/packages/seqHMM/vignettes/seqHMM_estimation.pdf">seed the algorithm carefully</a> both for outcome and run-time considerations. We will soon see how this choice of initial model parameters can impact the performance of the HMM.</p><p>In both of the following examples, the initial state probability and emission probabilities are seeded randomly and in both we set the number of hidden states to be equal to four. In the first example, the transition probability matrix is also seeded randomly. This means that the probability of changing from any season to another from one day to the next is totally random.</p><p>As we see below, even after training to a locally optimal set of parameters, this model performs quite poorly at the task of detecting seasons.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TMInpZgxmj4iqjNSuF1fZw.png" /><figcaption>Detecting four hidden states with a non-cyclic hidden Markov model.</figcaption></figure><p>In fact, even though the model knows about four hidden states, only three of them actually occur. This is typical in a poorly seeded HMM, since it’s easy to converge to a locally optimal solution which is far from globally optimal. On the other hand, suppose we seed the EM algorithm with the following more informed transition probability matrix:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/143/0*DB4BEliBwd2E8GIg" /></figure><p>The above matrix captures two important features of seasonality. The entry in row <em>i</em> and columns <em>j</em> of this matrix represents the probability of transitioning from hidden state <em>i</em> to hidden state <em>j</em>. In the matrix above, the largest values occur along the main diagonal. This reflects the fact that the probability of remaining in the same season from one day to the next is very high.</p><p>In addition, we notice that each row has only one additional non-zero value off the main diagonal. This is a reasonable choice for our transition matrix since we know that each season has only one other season which follows it. The probability of transitioning into any season other than the current one or the season immediately following it must be zero.</p><p>With these values set to zero, the cyclic nature of the HMM will be preserved by training with EM since transition probabilities seeded with zero won’t change. Once trained, we can use the <a href="https://en.wikipedia.org/wiki/Viterbi_algorithm">Viterbi algorithm</a> with our model to label our data with the most likely sequence of states.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XTjclCio__1IFbvd8cQrzA.png" /><figcaption>Detecting four hidden states with a cyclic hidden Markov model.</figcaption></figure><p>The plot above incorporates the sequential nature of the data as well as the cyclic nature of seasons to detect the seasons of the year with reasonable accuracy.¹ Notice how this differs from the labeling produced by the spatial clustering models which also detected seasonal trends, but were not able to correctly label days that exhibited seasonally uncharacteristic weather patterns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9l4qMSsCE4_8eWxakRv2Wg.png" /><figcaption>A visual summary of season detection in weather and solar data.</figcaption></figure><h3>Conclusion</h3><p>Clustering is very effective in enhancing the interpretability of data, but the power of hidden Markov modeling is in its ability to contextualize sequential raw data. Consequently, this type of modeling can be used to great effect in decision making processes and this framework has broad applicability to industrial settings including:</p><ul><li>Operating mode detection and analysis.</li><li>Time-to-event forecasting for industrial assets and machinery.</li><li>Imputation of missing data to fill in otherwise degraded or incomplete data.</li><li>Generative modeling for the training of robust models even when only a very limited amount of initial training data is available.</li></ul><p>Stay tuned for more posts about these topics and more on <a href="https://medium.com/utility-machine-learning"><em>When Machines Learn</em></a>.</p><p><em>¹ You might notice that the dominant hidden states for the cyclic HMM plot appear to cycle 0, 1, 3, 2, 0. In fact, if you look closely, you see small colored bands between the dominant cycles, so the cyclic nature of the HMM is still preserved but in an unexpected way.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c059649eb70" width="1" height="1" alt=""><hr><p><a href="https://medium.com/utility-machine-learning/using-hidden-markov-modeling-to-detect-seasonality-in-sequential-data-3c059649eb70">Using Hidden Markov Models to Detect Seasonality in Sequential Data</a> was originally published in <a href="https://medium.com/utility-machine-learning">When Machines Learn</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>