<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Shad Griffin on Medium]]></title>
        <description><![CDATA[Stories by Shad Griffin on Medium]]></description>
        <link>https://medium.com/@jshadgriffin?source=rss-b2cb0fe3df91------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*JPUnq5_vYGYYhpvU</url>
            <title>Stories by Shad Griffin on Medium</title>
            <link>https://medium.com/@jshadgriffin?source=rss-b2cb0fe3df91------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 14:39:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jshadgriffin/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Build Trustworthy AI]]></title>
            <link>https://jshadgriffin.medium.com/how-to-build-trustworthy-ai-2876ddc2db6a?source=rss-b2cb0fe3df91------2</link>
            <guid isPermaLink="false">https://medium.com/p/2876ddc2db6a</guid>
            <dc:creator><![CDATA[Shad Griffin]]></dc:creator>
            <pubDate>Mon, 03 Feb 2025 15:57:17 GMT</pubDate>
            <atom:updated>2026-06-03T17:19:19.550Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hgwW8j4XQQsBe61XTsVJMQ.jpeg" /></figure><h4>A comprehensive AI Governance System is the Key</h4><p><strong>Introduction</strong></p><p>AI Governance is a trendy term these days. It can mean different things to different people. IBM (my employer and I agree with them) maintains that a comprehensive AI Governance system provides the following:</p><ol><li>Lifecycle Governance.</li><li>Risk Management.</li><li>Regulatory Compliance.</li></ol><p>In practical terms, an AI Governance system must facilitate all documentation related to AI development and deployment, ensure all deployed AI performs as expected, and ensure compliance with all legal and regulatory requirements.</p><p>An effective AI governance system will keep the Feds from banging on your door with a search warrant, prevent a customer-facing chatbot from cussing like a sailor, and provide a “breadcrumb trail” of documentation so you can re-trace your steps if you ever need to understand why your AI does what it does.</p><p>In this article, I will focus on risk management or ensuring your AI is doing what it should. Risk management is about keeping your AI from being inaccurate. If your AI is designed to speak like your average American high schooler but suddenly starts speaking in Latin, your AI governance system should recognize the issue and take corrective action. If you need 85% accuracy in a predictive model and the accuracy over the last two days is 75%, your AI governance system should recognize that and take action.</p><p><strong>What is AI?</strong></p><p>Before we get into AI governance, it is helpful to define AI clearly. There are many different opinions regarding the definition of AI. If you ask 10 data scientists, you will get at least 15 different answers.</p><p>From a simple statistical model to the most complex neural network, AI is a self-learning model that produces output based on inputs. The self-learning component is the key, that’s what makes it AI.</p><p>In traditional statistical modeling or machine learning, the inputs are data, typically in rows and columns. For generative AI, the input is question or some other kind of text.</p><p>The output for a traditional statistical model is a number or a category. The output for generative AI is a category or text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*Ls6D5ZkOa-HsKz-QG6ujuw.png" /></figure><p><strong>How does AI Governance monitor AI Models?</strong></p><p>AI models generates output from inputs. You ensure trust in AI by ensuring the model output and input are accurate and consistent with the original design. An AI governance platform allows you to monitor the input and output, ensuring accuracy and consistency, which, in turn, will enable you to trust the AI.</p><p>Trust in AI means it won’t start dropping F-Bombs or revealing corporate secrets. You know this if the input and output of the AI are accurate and consistent with the purpose of the AI.</p><p>So, to summarize, an AI governance platform monitors AI and ensures trust by:</p><ol><li>Ensuring the model output is accurate.</li><li>Ensuring the model output and input do not vary dramatically over time.</li></ol><p><strong>How do you know if the model output is accurate?</strong></p><p>The answer to the question depends on the type of output coming from your model. Let’s start with a machine learning or statistical model. These types of models typically generate a number or a classification.</p><p>Let’s say, for example, you build a model that predicts who will and will not cancel their subscription next month. So, the model output will be a column of data for every customer that predicts “YES” or “NO.” “Yes” means the customer will cancel, and “NO” means they will not.</p><p>If we predict that a customer will cancel next month, at the end of next month, we will know with certainty if the model was accurate. Once this information is available in a database, we can compare the predicted to the actual, add up the wins and losses, and determine if the model performs as intended. A sound AI governance system will do this automatically. If the AI is not performing as intended, the system will automatically rebuild the model or notify the proper people to take action.</p><p>Let’s think about a model that generates words or natural language. This is what many generative AI models do. If I ask an AI model to write an email, there is not a concrete source of ground truth like there is for our customer cancellation example above, right? There will not be an email sitting in a database a month from now that we can use as a reference like there was for the customer cancellation example.</p><p>With natural language, it is standard to use human-generated responses to the AI prompt as the “truth.” In practice, what this means is there must be a “human in the loop” to provide ground truth regularly. Suppose you have an AI process that generates 1,000 automatic daily emails. To ensure the emails are accurate, you can select ten emails randomly and have a human respond to them. Then, compare the ten human-generated emails to the 10 AI-generated emails. This comparison will give a good idea of whether or not the AI is doing what it is supposed to do.</p><p>An AI governance system facilitates having a human in the loop. An AI governance system will respond appropriately once noticing the differences between human and AI responses. An appropriate response could mean shutting everything down until a data scientist fixes the issue or rebuilding the model automatically. The proper action depends on the use case.</p><figure><img alt="Model output is directly compared the actual data. From this you can gauge whether the model is accurate." src="https://cdn-images-1.medium.com/max/1024/1*N28M9K__gmKrIoALirAZqA.png" /><figcaption>Model output compared to ground truth indicates if the model is performing as it should.</figcaption></figure><p><strong>How do you know if output and input vary dramatically over time?</strong></p><p>Let’s say you build a model to predict height based on weight. The input in this simple model would be height, and the output is weight. While building your model, you note that the average height of your input data is 70 inches, and the average predicted weight or model output is 175 pounds. You do your due diligence and convince yourself that the model is ready for prime time, so you put it into operational mode.</p><p>A year later, you notice that the average input value or average height has changed dramatically. When we built the model, the average height was 70 inches, but now it is 85 inches.</p><p>Should you be alarmed? Yeah, you definitely should because the underlying data used to build the model fundamentally differs from the current data, and there is a significant risk that the model predictions could be wrong.</p><p>Likewise, what if, after a few months, the average predicted output or weight is 225 pounds? The current output is dramatically different from the original output. We built the model to predict an average value of 175 pounds, and now it predicts an average of 225 pounds. A change in the output indicates that the problem you are trying to solve or the population you’re trying to predict has dramatically changed.</p><p>Ensuring consistency for natural language models is similar. You compare the linguistic output and input of the current model to the original model. If we created the model to output English and it outputs Korean, you should be able to tell.</p><p>Most people refer to changes in the original model state to the current model state as “drift,” but the definitions beyond that can be murky.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SbIepMgIWtkT7CTahwNq5Q.png" /></figure><p><strong>So, what does all this mean?</strong></p><p>Building trust in your AI means that you know what it is doing and how that compares to the original state of the AI. If you designed your AI to predict customer churn and it isn’t, that is bad, and you need to fix it. If you create AI to write banking customer emails and it gives predictions of a zombie apocalypse, that is bad, and you need to fix it.</p><p>An AI governance system is critically important because it will monitor your AI and ensure it does what it should. AI Governance facilitates trustworthy AI.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2876ddc2db6a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying AI Model Fairness]]></title>
            <link>https://jshadgriffin.medium.com/demystifying-ai-model-fairness-10837881be1f?source=rss-b2cb0fe3df91------2</link>
            <guid isPermaLink="false">https://medium.com/p/10837881be1f</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai-ethics]]></category>
            <category><![CDATA[ai-bias]]></category>
            <dc:creator><![CDATA[Shad Griffin]]></dc:creator>
            <pubDate>Mon, 03 Feb 2025 15:56:06 GMT</pubDate>
            <atom:updated>2026-06-03T17:17:53.162Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hgwW8j4XQQsBe61XTsVJMQ.jpeg" /></figure><h4>It’s all about the data, dude.</h4><p><strong>Introduction</strong></p><p>In this article, I will discuss what generally causes a model application to mistreat or discriminate against certain groups. I can’t guarantee this is always the root cause, but it is more than likely. To be clear, if a model fails to act fairly in giving loans to people of color or discriminates against women in hiring, it is mistreating or discriminating against those groups.</p><p>The problem underlying the mistreatment of minority groups regarding loan approvals stems from an issue with the underlying data. To explain how this can happen, I will examine a completely different use case, market expansion. The impact of the issue is acute when certain vunerable groups are effective, but the problem is something you should consider for a data science activities.</p><p><strong>A Market Expansion Use Case</strong></p><p>Bob owns a carpet cleaning business in Dallas County, Texas. He’s been in business for 25 years, and 98% of his business is in Dallas County. Bob focuses his marketing and advertising in Dallas County; this is why most of his business is there. Occasionally, Bob ventures into the County next door to Dallas County (Tarrant), but this business comes from referrals and people who moved to Tarrant County from Dallas County. Again, Bob does nothing to promote his business in Tarrant County. All of his Tarrant County business comes from people who move and word of mouth.</p><p>After 25 years, Bob is looking to expand big time into Tarrant County. He purchases a list of households in both Dallas and Tarrant County. His idea is to build a predictive model to identify the best 10% of prospects across both counties and send a solicitation and coupon to these customers through traditional mail.</p><p>Will this work?</p><p><strong>What Models do</strong></p><p>Before determining if Bob’s approach to market expansion will work, there are a few things to understand about predictive models.</p><p>Let’s say we have a model that predicts the likely height for a sample of people based on their weight and a few other lifestyle variables. Assume we built the model on a sample of 1,000 people, and the average actual height of these people is 66 inches.<br>After we build a model and predict the height of the 1,000 people in our sample, the average predicted height should be about 66 inches. If it’s not, it would not be a very good model. If the model predicts the average height to be 56 inches, for example, the model kind of sucks, right?</p><p>In our use case, Bob, the carpet cleaner, uses a predictive model to predict prospects who will become customers. The output of this model will be a number between 0 and 1 that represents the probability of being a customer. Let’s assume that Bob currently has a 1% market penetration in Dallas County. That is, for every 100 households in Dallas County, Bob has one customer.</p><p>After Bob Builds his model, the average probability generated by the model of someone being a customer should be about 1%. If it is different from 1%, it wouldn’t be a very good model.</p><p>On average, the probability of being a customer is 1%, but the model will also identify a subset of the population that is more likely to buy Bob’s services. The group with a higher probability is where Bob will focus his efforts. The higher the likelihood of converting, the more effective a solicitation will be and the higher the ROI on the marketing effort. Using the model strategically, Bob can spend his scarce marketing dollars and focus them only on those likely to buy. So, if he randomly sends a solicitation to 10% percent of the prospects, 1% will buy. If he sends to the 10% most likely to become a customer, a much higher percentage will purchase his product, and Bob’s ROI is also much higher.</p><p><strong>Understanding Model Discrimination.</strong></p><p>Let’s take a look at the fundamentals of Bob’s data set.</p><p>Total households</p><p>Dallas County Households: 950,000</p><p>Bob’s Dallas County Customers: 10,000</p><p>Dallas County Penetration: 1.05%</p><p>Tarrant County Households: 750,000</p><p>Bob’s Tarrant County Customers: 200</p><p>Tarrant County Penetration: 0.03%</p><p>If Bob builds a model based on the metrics above to identify the 10% of households most likely to be a new customer for both counties, he will locate about 170,000 households. How many of these will be in Tarrant County?</p><p>It is hard to know for sure, but probably zero. So much for Bob’s market expansion, huh?</p><p>There will be very few model-generated prospects for Tarrant County because Bob used biased data. The model looks at the underlying nature of the data and assumes that the lack of sales in Tarrant County occurs for a reason. It is not smart enough to understand that Tarrant County has no sales because Bob has never really tried to do business there. It assumes that the relationship between County and conversion is causal when, in reality, it is not.</p><p>Bias occurs when the historical data presents a reality inconsistent with your current goals. For example, if Bob wanted to continue doing 98% of his business in Dallas County, the data set would work just fine. The fact that he wants to do a higher percentage in Tarrant County is why there is an issue.</p><p><strong>Mitigating The Problem</strong></p><p>If you’re Bob and realize this, there isn’t a clear-cut way to solve this problem. There are, however, ways you can minimize it.</p><p>One, you could establish a quota. For example, Bob could take the top 5% of the best prospects from each County, knowing that the model-generated probability of becoming a customer in Dallas County will be much higher than in Tarrant County.</p><p>Two, he could remove the County as a predictor in the model. Sometimes this works, but usually it doesn’t. It doesn’t work because real-world data is always correlated. An economist would say that real-world data is multi-collinear. In lay terms, this means that even if you remove the County as a predictor, other variables related to the County will still reflect the bias. For example, it could be that Dallas and Tarrant County have different household income and wealth levels. If you remove the county variable, the bias appears in these other related variables. There is a more extensive discussion here as to why this is true, but hopefully, it is clear why this would occur.</p><p>Third, you could build the model using the County as a predictor but then score all the Tarrant County data as if it were Dallas County. So, estimate the effect of the County on the modeling process but remove it from the deployment. Again, a lot of detail is left unsaid here, but if you need more clarification, please check out this other article, where I go into great detail on this topic.</p><p>Fourth, you could sample the data in a non-random or weighted way. For example, you could take 100% of the Tarrant County customers and 2% of the Dallas County customers. The resulting sample would change the Dallas/Tarrant County ratio from 98/2 to 50/50.</p><p>I’m sure there are other ways to address a problem with bias as well. There is no perfect way to deal with biased data, but there are ways to mitigate it. The best mitigation technique will depend on the specifics of the problem you are trying to solve.</p><p>In this article, I showed how biased data can affect market expansion for a carpet cleaner, but hopefully, it is clear how the same problem exists in discrimination. If a tech firm historically hires one woman for every five men, the predictive model will reflect this ratio in its predictions. It’s not that AI is prejudiced or against anyone. The data it is working with reflects an underrepresentation of a specific group.</p><p><a href="https://medium.com/geekculture/understanding-bias-in-modern-machine-learning-8795403ea1c7"><em>For a deeper dive into the topic, check out my other article.</em></a></p><p><a href="https://medium.com/geekculture/understanding-bias-in-modern-machine-learning-8795403ea1c7">Machine Learning with Biased Data</a></p><p>Thanks so much for your time. I hope this was useful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10837881be1f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying a Watson Machine Learning Model with Python]]></title>
            <link>https://medium.com/geekculture/deploying-a-watson-machine-learning-model-with-python-98a690699180?source=rss-b2cb0fe3df91------2</link>
            <guid isPermaLink="false">https://medium.com/p/98a690699180</guid>
            <dc:creator><![CDATA[Shad Griffin]]></dc:creator>
            <pubDate>Fri, 24 Feb 2023 16:09:48 GMT</pubDate>
            <atom:updated>2026-06-03T17:18:56.476Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IUy_ROrpW4VZlTHLAXsdjQ.jpeg" /></figure><p><a href="https://github.com/shadgriffin/deploywmlwpython/blob/main/Deploying%20an%20Machine%20Learning%20Model%20in%20WML-Final.ipynb">deploywmlwpython/Deploying an Machine Learning Model in WML-Final.ipynb at main · shadgriffin/deploywmlwpython</a></p><p>In this article, I build a machine learning model in a jupyter notebook inside Watson Studio, then deploy the model programmatically using python code to Watson Machine Learning (WML). Doing so allows you to incorporate the machine learning model into applications via an API.</p><p>I designed this tutorial for those with some knowledge of python, machine learning, Watson Studio, cloud object storage, and IBM Cloud. Also, this tutorial is specific to IBM Public cloud environments (Software as a Service (SaaS)). Versions of Watson Studio running on a Kubernetes cluster or locally on your desktop will require different WML model deployment procedures.</p><h3>1.0 Getting Setup</h3><p>Establish Libraries</p><pre><br>import os, types<br>import pandas as pd<br>from botocore.client import Config<br>import ibm_boto3<br>import numpy as np<br>import pandas as pd</pre><p>Ensure WML is up to date.</p><pre>!pip install -U ibm-watson-machine-learning</pre><h3>2.0 Prerequisites</h3><p>This tutorial assumes that you have some knowledge of Watson Studio and Cloud Pak for Data on IBM Cloud. Specifically, it assumes that you can do the following.</p><ol><li>Create an IBMid. <a href="https://www.ibm.com/account/reg/us-en/signup?formid=urx-19776">https://www.ibm.com/account/reg/us-en/signup?formid=urx-19776</a></li><li>Provision an instance of Watson Studio. <a href="https://dataplatform.cloud.ibm.com/docs/content/svc-welcome/wsl.html?audience=wdp">https://dataplatform.cloud.ibm.com/docs/content/svc-welcome/wsl.html?audience=wdp</a></li><li>Provision an instance of Watson Machine Learning. <a href="https://dataplatform.cloud.ibm.com/docs/content/DO/WML_Deployment/WMLServiceInstance.html">https://dataplatform.cloud.ibm.com/docs/content/DO/WML_Deployment/WMLServiceInstance.html</a></li><li>Set up a deployment space inside cloud pak for data. <a href="https://dataplatform.cloud.ibm.com/docs/content/wsj/analyze-data/ml-space-create.html">https://dataplatform.cloud.ibm.com/docs/content/wsj/analyze-data/ml-space-create.html</a></li></ol><p>If you do not know how to do these things, don’t worry. There is plenty of good documentation on how to do so. Please follow the links provided. If you know how to do these things but still need to, please do so now.</p><h3>3.0 Research and set WML parameters</h3><p>Before starting, there are five parameters to locate for successful model deployment. These include the following.</p><ol><li>The supported Watson Studio Runtime and Python version.</li><li>The supported version of your model.</li><li>An API Key.</li><li>The end point of your Watson Machine Learning service.</li><li>The name of your model.</li></ol><h4>3.1 Find the supported Watson Studio Runtime and python version.</h4><p>Based on your machine learning model, there is one and only one appropriate Watson Studio Runtime version and Python version.</p><p>The following link details these versions in detail.<br><a href="https://www.ibm.com/docs/en/cloud-paks/cp-data/4.0?topic=specifications-software-hardware-deployments">https://www.ibm.com/docs/en/cloud-paks/cp-data/4.0?topic=specifications-software-hardware-deployments</a></p><p><strong>When navigating this page, please ENSURE YOU HAVE THE RIGHT VERSION of Cloud Pak for Data.</strong> A pull-down menu in the top left corner of the web page alters the documentation based on the Cloud Pak for Data version.</p><p>In this example, I use an xgboost model. Based on the documentation, xgboost is currently only supported for python version 3.9 (3.10 is the most current version as I am writing this). The supported runtime for this model is 22.1. Please copy the text stating the correct runtime and python version and paste it below as a python object. The text must be precisely the same as on the website.</p><pre>runtime_version=&#39;runtime-22.1-py3.9&#39;</pre><h4>3.2 Find the supported version of your model.</h4><p>This link also details the supported version of your model.</p><p><a href="https://www.ibm.com/docs/en/cloud-paks/cp-data/4.0?topic=specifications-software-hardware-deployments">https://www.ibm.com/docs/en/cloud-paks/cp-data/4.0?topic=specifications-software-hardware-deployments</a></p><p>Find the appropriate model_type, and copy and paste the model_type from the web page above into a python object. For me, the model type is ‘xgboost_1.5.’</p><pre>model_type=&#39;xgboost_1.5&#39;</pre><p><strong>After identifying the model_type, runtime, and python version, Ensure that the runtime and python version for your Jupyter notebook is what it needs to be.</strong></p><p>You can check your notebook’s runtime and python versions by clicking on the information icon (an i with a circle around it) in the top right corner. You can also change the environment here is as well. I have to ensure that the python software version is 3.9 and the runtime is 22.1.</p><h4>3.3 Generate an API Key.</h4><p>How to Generate an API key is well documented. Please see the following link.</p><p><a href="https://www.ibm.com/docs/en/app-connect/containers_cd?topic=servers-creating-cloud-api-key">https://www.ibm.com/docs/en/app-connect/containers_cd?topic=servers-creating-cloud-api-key</a></p><p>When you get the API, paste it as a python object in the cell below.</p><pre>api_key=’xxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxx-xxxxxxxx&#39;</pre><h4>3.4 Find the endpoint of your Watson Machine learning service. <a href="https://dataplatform.cloud.ibm.com/data/jupyter2/runtimeenv2/v1/wdpx/service/notebook/conda4rt22199967126e3f84974b9e2c1184f39a31c/dsxjpy/aI1AF8O22yfYVFd4I8dBew:b-x8T0cKw0R53R_Wcy7bMbwNTjP3UDtzS9RIgGUtcfYlHhbY5H-kptkODRqvqy4pxqFlqT4/container/notebooks/a90ec385-8a78-476d-8a7b-ff8e65c6afec?api=v2&amp;project=99967126-e3f8-4974-b9e2-c1184f39a31c#3.4-Find-the-endpoint-of-your-Watson-Machine-learning-service.-">¶</a></h4><p>When creating a Watson Machine Learning service, you choose where to create it. You can choose Dallas, London, Frankfurt, or Tokyo. If you don’t remember, click on the hamburger menu in the top left corner, then go to “Services Instances .”Under “Services Instances,” find the WML service you want to use, which details the location. Make a note of the following endpoint based on the site of your service.</p><p>Dallas: <a href="https://us-south.ml.cloud.ibm.com/">https://us-south.ml.cloud.ibm.com</a></p><p>London — <a href="https://eu-gb.ml.cloud.ibm.com/">https://eu-gb.ml.cloud.ibm.com</a></p><p>Frankfurt — <a href="https://eu-de.ml.cloud.ibm.com/">https://eu-de.ml.cloud.ibm.com</a></p><p>Tokyo — <a href="https://jp-tok.ml.cloud.ibm.com/">https://jp-tok.ml.cloud.ibm.com</a></p><p>You can find these URLs on the web here.</p><p><a href="https://cloud.ibm.com/apidocs/machine-learning">https://cloud.ibm.com/apidocs/machine-learning</a></p><p>Create a python object that defines the correct WML end point. For me, it is Dallas.</p><pre>endpoint=’https://us-south.ml.cloud.ibm.com&#39;</pre><h4>3.5 Name you model</h4><p>The model name is how identifies the model systematically inside the IBM cloud. It can be anything, but ideally, it describes the model. I will use “High/Low Midi-chlorians Classifier V1.”</p><pre>name=&#39;High/Low Midi-chlorians Classifier V1&#39;</pre><h3>4.0 Build a machine learning model</h3><p>Import data from google drive</p><pre>!wget --load-cookies /tmp/cookies.txt &quot;https://docs.google.com/uc?export=download&amp;confirm=$(wget --quiet --save-cookies /tmp/cookies.txt\<br>    \--keep-session-cookies --no-check-certificate &#39;https://docs.google.com/uc?export=download&amp;id=FILEID&#39;\<br>    \-O- | sed -rn &#39;s/.*confirm=([0-9A-Za-z_]+).*/\1\n/p&#39;)&amp;id=1dNDmrhlocDog23mXntpS0OdMMAPC5848&quot; -O balanced.csv &amp;&amp; rm -rf /tmp/cookies.txt<br><br><br><br>df_balanced = pd.read_csv(&quot;balanced.csv&quot;, sep=&quot;,&quot;, header=0)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5KUeVZ1Yof1xqqrACO3XJQ.png" /></figure><p>Examine the rows and column of the data</p><pre>df_balanced.shape</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*qYvdw5kVnndsE3WRNcRvKA.png" /></figure><p>The data we use in the following steps is fictitious and not the point of the exercise, so I will not worry about describing it in much detail. We don’t need the complete data set to show how to deploy a model to WML. Thus, I will take a .5% random sample and reduce the number of columns.</p><pre>df_balanced=df_balanced[[&#39;FAILURE_TARGET&#39;, &#39;AGE_OF_EQUIPMENT&#39;, &#39;S15&#39;, &#39;S17&#39;, &#39;S13&#39;, &#39;S5&#39;, &#39;S16&#39;,<br>       &#39;S19&#39;, &#39;S18&#39;, &#39;S8&#39;]].copy()<br><br>np.random.seed(33)<br>df_balanced[&#39;wookie&#39;] = (np.random.randint(0, 10000, df_balanced.shape[0]))/10000<br><br><br>df_balanced=df_balanced[df_balanced[&#39;wookie&#39;]&lt;.005]</pre><p>Define the features, dependent variable, and independent variables.</p><pre>features = [x for x in df_balanced.columns if x not in [&#39;FAILURE_TARGET&#39;]]  <br>dependent=pd.DataFrame(df_balanced[&#39;FAILURE_TARGET&#39;])<br><br>independent=df_balanced.drop(columns=[&#39;FAILURE_TARGET&#39;])</pre><p>Specify the algorithm.</p><pre>from xgboost.sklearn import XGBClassifier<br><br>xgb0 = XGBClassifier(objective = &#39;binary:logistic&#39;,use_label_encoder=False);</pre><p>Build the model.</p><pre>xgb0.fit(independent, dependent, eval_metric=&#39;error&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0e1vc0begc7zJycdNyPjcw.png" /></figure><h3>5.0 Deploy the model</h3><p>Build credentials for the WML service using the API Key and endpoint.</p><pre><br>wml_credentials = {<br>                  &quot;apikey&quot;:api_key,<br>                  &quot;url&quot;:endpoint<br>}</pre><p>Next, import the API client from the WML python library and submit your WML credentials.</p><pre>from ibm_watson_machine_learning import APIClient<br><br>client = APIClient(wml_credentials)</pre><p>Next, examine the deployment spaces available. Again, this tutorial does not cover how to create a deployment space. Fortunately, this is well documented.</p><p>Select the deployment space you want to use by copying the ID for the deployment space and pasting it into a python object. I only have one, Dagobah, so I will use it.</p><pre>client.spaces.list(limit=10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-FY49uDorotssZkMSx5odQ.png" /></figure><pre>space_id = ‘3axxxxxxxxxxxxxxxxxxxxxxxxxxfe’</pre><p>Set the default space in the WML client. It should say ‘SUCCESS’ if you do it right.</p><pre>client.set.default_space(space_id)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*Jf3DoZ3CnJdzgn0spgXBVw.png" /></figure><p>Set the software specifications to the appropriate runtime and versions we established in section 3.</p><pre>sofware_spec_uid = client.software_specifications.get_id_by_name(runtime_version)</pre><p>Define the metadata of the model.</p><pre>metadata = {<br> client.repository.ModelMetaNames.NAME: name,<br> client.repository.ModelMetaNames.TYPE: model_type,<br> client.repository.ModelMetaNames.SOFTWARE_SPEC_UID: sofware_spec_uid<br>}</pre><p>Below, make sure you specify the name of the machine learning model. I named the machine learning model xgb0.</p><p>From a previous line, “xgb0 = XGBClassifier(objective = ‘binary:logistic’,use_label_encoder=False);”</p><p>Write the model to a WML repository with the appropriate metadata.</p><pre>published_model = client.repository.store_model(<br> model=xgb0,<br> meta_props=metadata,<br> training_data=independent,<br> training_target=dependent)</pre><p>View the model details in a JSON.</p><pre>import json<br><br>published_model_uid = client.repository.get_model_id(published_model)<br>model_details = client.repository.get_details(published_model_uid)<br>print(json.dumps(model_details, indent=2))</pre><p>List all of the models saved to the repository. We should see the model we created and saved at the top.</p><pre>models_details = client.repository.list_models()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V4pdKy9723BAfWer6TYtqg.png" /></figure><p>Deploy the model to the Watson Machine Learning service so other applications can use it.</p><pre>metadata = {<br>    client.deployments.ConfigurationMetaNames.NAME: name,<br>    client.deployments.ConfigurationMetaNames.ONLINE: {}<br>}<br><br>created_deployment = client.deployments.create(published_model_uid, meta_props=metadata)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_eZAz_zhCkQfk2eT5ABlYA.png" /></figure><h3>Author</h3><p><strong>Shad Griffin</strong>, is a Distinguished Data Scientist at IBM</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98a690699180" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/deploying-a-watson-machine-learning-model-with-python-98a690699180">Deploying a Watson Machine Learning Model with Python</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Complete Solution to the BackBaze.com Kaggle Problem]]></title>
            <link>https://medium.com/geekculture/a-complete-solution-to-the-backbaze-com-kaggle-problem-9d5cb45a88db?source=rss-b2cb0fe3df91------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d5cb45a88db</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[predictive-maintenance]]></category>
            <category><![CDATA[equipment-failure]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[false-positive]]></category>
            <dc:creator><![CDATA[Shad Griffin]]></dc:creator>
            <pubDate>Wed, 28 Dec 2022 01:35:36 GMT</pubDate>
            <atom:updated>2026-06-03T17:19:37.399Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Complete Solution to the Backblaze Machine Failure Kaggle Problem , VI</h3><h3>Part Six, Evaluating the Model</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s4fwIhjYir1hfWb3pJNvSA.jpeg" /></figure><ul><li><a href="https://www.kaggle.com/datasets/backblaze/hard-drive-test-data">Hard Drive Test Data</a></li><li><a href="https://github.com/shadgriffin/backblazedata/blob/master/Backblaze.com%20--Step%20Six--%20Evaluate%20Model.ipynb">backblazedata/Backblaze.com --Step Six-- Evaluate Model.ipynb at master · shadgriffin/backblazedata</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FGJewNI72VTE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DGJewNI72VTE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FGJewNI72VTE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce6fcde0251c03f1e41e42e1eefd4955/href">https://medium.com/media/ce6fcde0251c03f1e41e42e1eefd4955/href</a></iframe><ul><li><a href="https://jshadgriffin.medium.com/a-complete-solution-to-the-backbaze-com-kaggle-problem-3a9558cd8929">A Complete Solution to the BackBaze.com Kaggle Problem</a></li><li><a href="https://jshadgriffin.medium.com/a-complete-solution-to-the-backbaze-com-kaggle-problem-7c0f51429908">A Complete Solution to the BackBaze.com Kaggle Problem</a></li><li><a href="https://jshadgriffin.medium.com/a-complete-solution-to-the-backbaze-com-kaggle-problem-cd51259787b7">A Complete Solution to the BackBaze.com Kaggle Problem</a></li><li><a href="https://jshadgriffin.medium.com/a-complete-solution-to-the-backbaze-com-kaggle-problem-1f53235bdb4e">A Complete Solution to the BackBaze.com Kaggle Problem</a></li><li><a href="https://jshadgriffin.medium.com/a-complete-solution-to-the-backbaze-com-kaggle-problem-cf1fab1af529">A Complete Solution to the BackBaze.com Kaggle Problem</a></li></ul><h3>1.0 Introduction</h3><p>Note this is part six of a six-part solution.</p><p>Backblaze, you are the “GOAT.” You are the “cat’s meow.” You “Rock the House.” In case you don’t know why Backblaze is so totally “kick-ass,” they open-sourced a vast set of hard drive information a few years ago and continue updating it each quarter. What a treasure trove of superb data. Backblaze, thank you from the bottom of my heart.</p><p>The Backblaze data includes operational metrics from hard drives with an indicator of a hard-drive failure. It is an excellent source for teaching techniques related to machine failure. Again, thank you for making this available to the open-source community. Here is a link to the data.</p><p><a href="https://www.backblaze.com/b2/hard-drive-test-data.html">Backblaze Hard Drive Stats</a></p><p>My goal in this series of articles is not to give the best solution with the highest AUC. My goal is to show you how to approach equipment failure problems and build solutions that reflect realistic accuracy, and provide an easy transition from the lab to the real world.</p><p>I will use a Spark/Python Jupyter notebook inside IBM’s Watson Studio on the cloud as a tool in this discussion.</p><p><a href="https://www.ibm.com/cloud/watson-studio">IBM Watson Studio - Overview</a></p><p>I will also be using cloud object storage on the IBM cloud.</p><p><a href="https://cloud.ibm.com/docs/cloud-object-storage">IBM Cloud Docs</a></p><p>To be fully transparent, I know very little about the operation and management of disk drives. I am not a subject matter expert in disk drives. My lack of expertise is critical to note because developing data science solutions usually requires some knowledge of the subject matter. Because of this lack of knowledge, I am sure this solution is lacking in some areas. Despite this, I have made assumptions when necessary, documented gaps in my understanding, and plowed through the problem from beginning to end. Consider this work a template to solve the problem, not a solution specifically built for Backblaze to operationalize immediately. Undoubtedly, I would need to consult with disk drive experts before finalizing the solution.</p><p>In the sixth article of the series, I evaluate the model built in step 5.</p><p>Based on what I read and hear, it is common for people to evaluate a model with a confusion matrix, an AUC curve, or an accuracy metric. While these are valid and worth exploring, they do not incorporate time. Predictive Maintenance is time-dependent, and these methods fail to account for the timeliness of signals. In another article, I write about this in great detail (section 7).</p><p><a href="https://medium.com/swlh/machine-learning-for-equipment-failure-prediction-and-predictive-maintenance-pm-e72b1ce42da1">https://medium.com/swlh/machine-learning-for-equipment-failure-prediction-and-predictive-maintenance-pm-e72b1ce42da1</a></p><p>Because equipment failure problems are time-dependent, “when” a prediction occurs is as important as “if” a prediction occurs. Time is critical when evaluating a predictive model for equipment failure problems. For example, if a model predicts failure on Monday and does not fail on Monday, is it a false positive signal?</p><p>It depends. How long does Monday’s signal last?</p><p>For example, in our data, if the signal occurs on Monday and the machine fails on Tuesday, it is probably not a false positive. It is likely a true positive. If a signal occurs on Monday and the device fails six months later, it is likely a false positive. In other words, you must have an acceptable time frame between a signal and a failure to assign a signal as either a false positive or a true positive. If a failure follows the signal in a time shorter or equal to this time frame, it is a true positive. Otherwise, it is a false positive.</p><p>Another issue that occurs when evaluating equipment failure models is repetitive signals. For example, in our data, if there are signals on Monday and Tuesday, do we have two different signals or one signal spanning two days? For our use case, it is one signal. Getting a valid measure of accuracy means combining repetitive signals into a single signal.</p><p>Again, I recommend working through this article if you have not previously done so. It will provide further details on the techniques used to understand the data from Backblaze.</p><p><a href="https://medium.com/swlh/machine-learning-for-equipment-failure-prediction-and-predictive-maintenance-pm-e72b1ce42da1">Machine Learning for Equipment Failure Prediction and Predictive Maintenance (PM)</a></p><h3>2.0 Establish environment and Parameters</h3><p>Install, import and establish Libraries</p><pre>!pip install plotly --upgrade<br>!pip install chart_studio  --upgrade<br><br>import chart_studio.plotly as py<br>import plotly.graph_objs as go<br>import plotly as plotly<br>import pandas as pd<br>import numpy as np<br><br><br>from sklearn import metrics<br><br>from sklearn.preprocessing import LabelEncoder<br><br>import xgboost as xgb<br>from xgboost.sklearn import XGBClassifier<br><br>import types<br>import pandas as pd<br><br>pd.options.display.float_format = &#39;{:.8f}&#39;.format</pre><p>Define Cloud Object Storage Credentials.</p><pre>def __iter__(self): return 0<br># @hidden_cell<br># The following code contains the credentials for a file in your IBM Cloud Object Storage.<br># You might want to remove those credentials before you share your notebook.<br>credentials = {<br>    &#39;IAM_SERVICE_ID&#39;: &#39;XXXXX&#39;,<br>    &#39;IBM_API_KEY_ID&#39;: &#39;XXXXX&#39;,<br>    &#39;ENDPOINT&#39;: &#39;XXXXX&#39;,<br>    &#39;IBM_AUTH_ENDPOINT&#39;: &#39;XXXXX&#39;,<br>    &#39;BUCKET&#39;: &#39;XXXXX&#39;,<br>    &#39;FILE&#39;: &#39;XXXXX&#39;<br>}</pre><pre>from ibm_botocore.client import Config<br>import ibm_boto3<br>cos = ibm_boto3.client(service_name=&#39;s3&#39;,<br>    ibm_api_key_id=credentials[&#39;IBM_API_KEY_ID&#39;],<br>    ibm_service_instance_id=credentials[&#39;IAM_SERVICE_ID&#39;],<br>    ibm_auth_endpoint=credentials[&#39;IBM_AUTH_ENDPOINT&#39;],<br>    config=Config(signature_version=&#39;oauth&#39;),<br>    endpoint_url=credentials[&#39;ENDPOINT&#39;])</pre><p>Read in Data</p><pre># @hidden_cell<br># The following code accesses a file in your IBM Cloud Object Storage. It includes your credentials.<br># You might want to remove those credentials before you share the notebook.<br><br><br>bucket = &#39;XXXXX&#39;<br>object_key = &#39;pred.csv&#39;<br><br>body = cos.get_object(Bucket=bucket,Key=object_key)[&#39;Body&#39;]<br># add missing __iter__ method, so pandas accepts body as file-like object<br>if not hasattr(body, &quot;__iter__&quot;): body.__iter__ = types.MethodType( __iter__, body )<br><br>df = pd.read_csv(body)<br>df.head()</pre><h3>3.0 Identifying disks with a failure.</h3><p>In step 3, we had to sample the data, so it was small enough to run in my environment. As a reminder, we randomly selected 1000 disks with a failure and 1000 disks without a failure. As we evaluate the model, we will weight the data to approximate the original unsampled data (about 42M records).</p><p>The first step in weighting the data is creating a flag that identifies each disk as having a failure or not.</p><pre> #identify disks with a failure<br>df_failure=df[df[&#39;FAILURE&#39;]==1]<br>#keep relevant columns<br>df_failure=df_failure[[&#39;SERIAL_NUMBER&#39;]]<br>#dedup the data <br>df_failure_list=df_failure.drop_duplicates()<br>#create a flag that it is a Serial number with a failure<br>df_failure_list[&#39;FAILURE_SN&#39;]=1</pre><p>Join the list of Serial Numbers with a failure to the original file.</p><pre>#conduct an inner join to the original data — result set will be all records from a SN with a failure<br>df_failure = pd.merge(df, df_failure_list, on =’SERIAL_NUMBER’, how =”inner”)</pre><p>Create a file with Serial Numbers that did not fail.</p><pre>#merge the list of SNs with a failure to the whole list with a left join<br>df_nonfailure=pd.merge(df, df_failure_list, on =&#39;SERIAL_NUMBER&#39;, how =&quot;left&quot;)<br>#if the SN failure flag is null make it 0<br>df_nonfailure[&#39;FAILURE_SN&#39;] = df_nonfailure[&#39;FAILURE_SN&#39;].replace(np.nan, 0)<br>#include only the records with a FAILURE_SN of 0.  This includes the records with from SNs without a failure<br>df_nonfailure=df_nonfailure[df_nonfailure[&#39;FAILURE_SN&#39;]==0]<br>#drop dups to have a list of SNs without a failure<br>df_nonfailure_list=df_nonfailure[&#39;SERIAL_NUMBER&#39;].drop_duplicates()<br>#count the records and fields<br>df_nonfailure_list.shape</pre><p>Append failures and non-failures</p><pre>#append the failure and non-failure groups together<br>dfx = pd.concat([df_failure, df_nonfailure], axis=0)</pre><h3>4.0 Evaluate the Model</h3><h4>4.1 Evaluation of the AUC and confusion matrix</h4><p>As I mentioned earlier, the most confusing element of predictive maintenance problems is building a realistic model assessment. Because of timing and the small number of failures, understanding how the model will work once deployed in production is challenging.</p><p>There are standard metrics for evaluating models like accuracy, AUC, and a confusion matrix. In the sections below, I will show how, given the transformations we used to build our model and the complexity of the problem, we need a more realistic view of model performance when deployed into production. These standard metrics are helpful but do not capture the time-dependent nature of the problem.</p><p>Rename the variable names so they match an existing template.</p><pre>df = df.rename(columns={&quot;GROUP&quot;: &quot;MODELING_GROUP&quot;, &quot;P_1&quot;: &quot;P_FAIL&quot;, &quot;TARGET&quot;:&quot;FAILURE_TARGET&quot;,&quot;FAILURE&quot;:&quot;EQUIPMENT_FAILURE&quot;,&quot;SERIAL_NUMBER&quot;:&quot;ID&quot;})</pre><p>Split the data frame into separate data frames by MODELING_GROUP.</p><pre>df_testing=df[df[&#39;MODELING_GROUP&#39;] == &#39;TESTING&#39;].copy()<br>df_training=df[df[&#39;MODELING_GROUP&#39;] == &#39;TRAINING&#39;].copy()<br>df_validation=df[df[&#39;MODELING_GROUP&#39;] == &#39;VALIDATION&#39;].copy()</pre><pre><br>df_training[‘Y_FAIL’] = np.where(((df_training.P_FAIL &lt;= .250)), 0, 1)<br>#Print model report:<br>print(“Accuracy : %.4g” % metrics.accuracy_score(df_training[‘FAILURE_TARGET’].values, df_training[‘Y_FAIL’]))<br>print(“AUC Score (Train): %f” % metrics.roc_auc_score(df_training[‘FAILURE_TARGET’], df_training[‘P_FAIL’]))<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*TdYr2BKQWwe0gjRa6wjRdw.png" /></figure><pre>df_testing[‘Y_FAIL’] = np.where(((df_testing.P_FAIL &lt;= .250)), 0, 1)<br>#Print model report:<br>print(“Accuracy : %.4g” % metrics.accuracy_score(df_testing[‘FAILURE_TARGET’].values, df_testing[‘Y_FAIL’]))<br>print(“AUC Score (Train): %f” % metrics.roc_auc_score(df_testing[‘FAILURE_TARGET’], df_testing[‘P_FAIL’]))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*m5jURcPqSrQDm74mIm2g0w.png" /></figure><p>With a cut-off of .25, the testing set has an accuracy of .9751 and and AUC of .785501. The testing set has an accuracy of .9732 and an AUC of .771920</p><p>Let’s examine a confusion matrix for the testing data set.</p><pre>print(pd.crosstab(df_testing.Y_FAIL, df_testing.EQUIPMENT_FAILURE, dropna=False))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*dBXQ7h5F9zO8jSv3_hih5A.png" /></figure><p>According to a simple confusion matrix, we have 176,582 True Negatives, 106 True Positives, 199 False Negatives, and 4459 False Positives in the testing data set. These stats, however, do not incorporate the element of time. For example, some false positives preceded the failures by an acceptable time increment. Thus, they would be True Positives, not False Positives. ​ Several signals of failure can also be combined. For example, if there is a signal Monday, Tuesday and Wednesday, is that three signals or one signal occurring over three separate days? More than likely, it is one signal.<br>​ In the next section, I will incorporate the element of time and derive more realistic measures of model accuracy.</p><h4>4.2 Using Heuristics to Define a False Positive, True Positive, False Negative, and True Negative.</h4><p>We first need to define a few parameters to accurately evaluate our machine learning model. I usually fine-tune these parameters with the testing and training data sets, then confirm the accuracy with the validation data set.</p><p>The first parameter is the Forecast Window.</p><p>The Forecast Window is the time a failure signal projects into the future.</p><p>For example, if there is a failure signal on June 1st, how long is that signal last?</p><p>Does it mean the machine will break in the next second, minute, hour, day, or month?</p><p>Note that the forecast window length depends on the problem’s context. If a machine runs to failure in 10 years, the forecast window will be relatively long, perhaps as long as six or nine months. If a machine runs to failure in 1 day, the forecast window will be much shorter, maybe an hour or a few minutes. The length of the forecast window must be helpful to the problem. For example, a twenty-eight-day forecast window for a machine that runs to failure in thirty days is of little value.</p><p>As I mentioned earlier, I am not an expert in the operation and maintenance of disk drives. Based on what I know, however, a 15-day forecast window is reasonable.</p><p>We also need to define a cut-off value. In this first example, we will use a cut-off value of .25. The cut-off value determines if a prediction is a failure or a non-failure. In the current example, if the probability of failure is less than .25, it is a predicted non-failure. If the likelihood of failure is greater than .30, it is an expected failure.</p><pre>forecast_window=15<br>cutoff=0.25</pre><p>Reformat the date field to Datetime.\</p><pre>df[&#39;DATE&#39;]=pd.to_datetime(df[&#39;DATE&#39;])</pre><p>Define a prediction of Failure.</p><pre>df[&#39;Y_FAIL&#39;] = np.where(((df.P_FAIL &lt;= cutoff)), 0, 1)</pre><p>To effectively evaluate the model, we must do three things. One, we need to remove redundant failure signals. That is, ensure at least 15 days (the forecast window) exist between each failure signal in the data. Two, we must ensure failure signals from a specific disk align with failures from the same disk. We don’t want a signal from disk x predicting a failure in disk y. Three, we must understand the time between signals and failures.</p><p>Note there are many ways to do what I am doing in the next few steps. It is straightforward data processing. I’m not saying this is the best way. I am saying it works.</p><p>4.21 Eliminate redundant failure signals</p><p>There can only be one failure every 15 days. If multiple failure signals occur in a fifteen-day window, these signals will be aggregated and associated with the first signal.</p><p>For example, assume you have a signal on Monday, Tuesday, Wednesday, and Thursday. Here, we have a single failure signal measured over four days, not four different signals measured over four days. The latter situation doesn’t make sense. The problem on Tuesday, Wednesday, and Thursday are not independent of the issue on Monday. The four are connected. They have to be; even if they are not, you should have checked and repaired the disk after the first signal.</p><p>Given this, to get an accurate model assessment, we must consolidate the four signals and associate them with the first day in the series of signals (Monday). In other words, Tuesday, Wednesday, and Thursday signals are redundant and subject to removal. Again, a signal of failure is good for 15 days (forecast window), so a signal that occurs inside the 15-day window of an earlier signal is not, by definition, NOT a separate signal of failure.</p><p>Let’s take a step back and look at this pragmatically. If you get a failure signal today, you will take action and check the machine immediately, right? Isn’t the whole point here? We only have consecutive signals in the historical data because the model does not exist yet. In a real-world situation, successive failure signals should not occur. A signal will prompt the business to check the machine. At that point, the signal becomes either a false positive or a true positive, end of the story.</p><p>Sort the data by id and date.</p><pre><br>xx=df<br>xx=xx.sort_values(by=[&#39;ID&#39;,&#39;DATE&#39;], ascending=[True, True])</pre><p>Create a unique list of machines.</p><pre>aa=xx<br><br>pd_id=aa.drop_duplicates(subset=&#39;ID&#39;)<br>pd_id=pd_id[[&#39;ID&#39;]]<br>pd_id.shape</pre><p>Label each machine with a sequential number. We need the id to be sequential for use in a later step.</p><pre>pd_id=pd_id.reset_index(drop=True)<br>pd_id=pd_id.reset_index(drop=False)<br>pd_id=pd_id.rename(columns={&quot;index&quot;: &quot;SCOOBYDOO&quot;})<br>pd_id[&#39;SCOOBYDOO&#39;]=pd_id[&#39;SCOOBYDOO&#39;]+1<br></pre><p>Grab the max number of machines. We will use this in a loop in a later step.</p><pre>column = pd_id[&quot;SCOOBYDOO&quot;]<br>max_value = column.max()+1<br></pre><p>Append the sequencial number to the main file. Now each machine a sequencial id.</p><pre>xx=xx.sort_values(by=[&#39;ID&#39;], ascending=[True])<br>pd_id=pd_id.sort_values(by=[&#39;ID&#39;], ascending=[True])<br>xx =xx.merge(pd_id, on=[&#39;ID&#39;], how=&#39;inner&#39;)<br></pre><p>Sort the data by ID and Date and reset the index of the dataframe so it matches the sort.</p><pre><br>xx=xx.sort_values(by=[&#39;ID&#39;,&#39;DATE&#39;], ascending=[True,True])<br><br>#reset index<br>xx=xx.reset_index(drop=True)</pre><p>The next few steps assign a new failure indicator that incorporates the forecast window. Note that this calculation occurs at a machine level. Doing this keeps a signal from one machine affecting another machine.</p><p>This loop takes a while to run.</p><p>The output is a new failure indicator called “Y_FAILZ.” This failure signal incorporates the forecast window and will not occur more than once every 15 days.</p><pre>#create a null dataframe for the next step<br>df_fred=xx<br>df_fred[&#39;Y_FAIL_sumxx&#39;]=0<br>df_fred=df_fred[df_fred[&#39;SCOOBYDOO&#39;] == max_value+1]<br>df_fred.shape<br><br><br><br>#sum the number of signals occuring over the last 90 days for each machine individually<br><br>for x in range(max_value):<br>        dffx=xx[xx[&#39;SCOOBYDOO&#39;] ==x]<br>        dff=dffx.copy()<br>        dff[&#39;Y_FAIL_sumxx&#39;] =(dff[&#39;Y_FAIL&#39;].rolling(min_periods=1, window=(forecast_window)).sum())<br>        df_fred= pd.concat([df_fred,dff])<br>        <br>xx=df_fred<br><br># if a signal has occured in the last 15 days, the signal is 0.<br>xx[&#39;Y_FAILZ&#39;]=np.where((xx.Y_FAIL_sumxx&gt;1), 0, xx.Y_FAIL)<br><br><br>df=xx</pre><p>4.22 Identify the machine id for each signal. Identify the date of the failure signal.</p><p>To determine if a signal is accurate, we need to collect two more pieces of information.</p><p>The first is the date of the failure signal. We’ll need to compare the failure date to the failure signal date to ensure that the signal is within the forecast window.</p><p>Remember that we are working with a panel data set. We have multiple machines measured over time. We have to align the signals and failures by machine. In other words, we don’t want a signal from machine 1 associated with a failure in machine 2. The signals from machine 1 are meant to predict failures in machine 1, not machine 2. If we have a machine id for each failure signal, we can ensure that it aligns with the machine id of the failure.</p><p>Sort the data by id and date.</p><pre><br>xx=df<br>xx=xx.sort_values(by=[&#39;ID&#39;,&#39;DATE&#39;], ascending=[True, True])</pre><p>Create signal id with the cumsum function.</p><pre>xx[&#39;SIGNAL_ID&#39;] = xx[&#39;Y_FAILZ&#39;].cumsum()</pre><p>Now we will pull the records with a signal into a different data frame.</p><p>Here we will create a new field that identifies the date of each signal (SIGNAL_DATE).</p><p>Also, we will identify the machine ID Associated with each signal (ID_OF_SIGNAL)</p><pre>df_signals=xx[xx[&#39;Y_FAILZ&#39;] == 1]<br>df_signal_date=df_signals[[&#39;SIGNAL_ID&#39;,&#39;DATE&#39;,&#39;ID&#39;]]<br>df_signal_date=df_signal_date.rename(index=str, columns={&quot;DATE&quot;: &quot;SIGNAL_DATE&quot;})<br>df_signal_date=df_signal_date.rename(index=str, columns={&quot;ID&quot;: &quot;ID_OF_SIGNAL&quot;})</pre><p>Append ID_OF_SIGNAL and SIGNAL_DATE to the original Dataframe base on the SIGNAL_ID.</p><pre>xx =xx.merge(df_signal_date, on=[&#39;SIGNAL_ID&#39;], how=&#39;outer&#39;) <br>df=xx.copy()</pre><p>Simplify by only keeping the fields we need going forward.</p><pre>df=df[[&#39;DATE&#39;, &#39;ID&#39;, &#39;EQUIPMENT_FAILURE&#39;, &#39;FAILURE_TARGET&#39;,&#39;FAILURE_DATE&#39;,<br>       &#39;P_FAIL&#39;, &#39;Y_FAILZ&#39;,&#39;SIGNAL_ID&#39;,<br>       &#39;SIGNAL_DATE&#39;,&#39;ID_OF_SIGNAL&#39;,&#39;MODELING_GROUP&#39;,&#39;FAILURE_SN&#39;]]</pre><p>Create a field called “Warning” that indicates the time from signal to failure.</p><pre>df[‘FAILURE_DATE’]=pd.to_datetime(df[‘FAILURE_DATE’])<br>df[‘SIGNAL_DATE’]=pd.to_datetime(df[‘SIGNAL_DATE’])<br>df[‘C’] = df[‘FAILURE_DATE’] — df[‘SIGNAL_DATE’].copy()<br>df[‘WARNING’] = df[‘C’] / np.timedelta64(1, ‘D’).copy()</pre><p>4.23 Create a realistic confusion matrix on unweighted data.</p><p>Finally, we have enough information to define a false positive, false negative, true positive, and true negative.</p><p>A true positive occurs if the machine fails and there is a signal within the last 15 days. Also, we have to ensure that the signal id belongs to the machine (ID). Note that this prohibits a signal from another machine from being applied to the machine in question.</p><p>A false negative occurs if and only if the machine fails and it is not a true positive.</p><p>A False Positive occurs if there is a failure signal and a failure does not happen in the next 15 days. Also, if a signal occurs after the failure, this is a false positive. We also must ensure that the signal ID belongs to the machine ID.</p><p>If an observation is not a False Positive, a False Negative, or a True Positive, it is a True Negative.</p><pre># define a true positive<br>df[&#39;TRUE_POSITIVE&#39;] = np.where(((df.EQUIPMENT_FAILURE == 1) &amp; (df.WARNING&lt;=forecast_window) &amp;(df.WARNING&gt;=0) &amp; (df.ID_OF_SIGNAL==df.ID)), 1, 0)</pre><pre># define a false negative<br>df[&#39;FALSE_NEGATIVE&#39;] = np.where((df.TRUE_POSITIVE==0) &amp; (df.EQUIPMENT_FAILURE==1), 1, 0)</pre><pre># define a false positive<br>df[&#39;BAD_S&#39;]=np.where((df.WARNING&lt;0) | (df.WARNING&gt;=forecast_window | df.WARNING.isnull().values.any()), 1, 0)<br><br><br>df[&#39;FALSE_POSITIVE&#39;] = np.where(((df.Y_FAILZ == 1) &amp; (df.BAD_S==1) &amp; (df.ID_OF_SIGNAL==xx.ID)), 1, 0)</pre><pre>df[&#39;TRUE_NEGATIVE&#39;] = np.where(((df.FALSE_POSITIVE == 0) &amp; (df.TRUE_POSITIVE==0) &amp; (df.FALSE_NEGATIVE==0)), 1, 0)</pre><pre>df[‘CATEGORY’]=np.where((df.FALSE_POSITIVE==1),’FALSE_POSITIVE’,<br> (np.where((df.FALSE_NEGATIVE==1),’FALSE_NEGATIVE’,<br> (np.where((df.TRUE_POSITIVE==1),’TRUE_POSITIVE’,’TRUE_NEGATIVE’)))))</pre><pre>#Get unweighted failures, non-failures and observations per group<br>tipsy = df.groupby([&#39;MODELING_GROUP&#39;]).aggregate(<br>    {&#39;FALSE_POSITIVE&#39;: &#39;sum&#39;, &#39;TRUE_POSITIVE&#39;:&#39;sum&#39;, &#39;FALSE_NEGATIVE&#39;:&#39;sum&#39;,&#39;TRUE_NEGATIVE&#39;:&#39;sum&#39;})<br>tipsy</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Mi4L4rGvovfkrwY0z2-GA.png" /></figure><p>4.24 Create a realistic confusion matrix on weighted data.</p><p>Separate disks with a failure and those without.</p><pre>df_f=df[df[&#39;FAILURE_SN&#39;]==1].copy()<br>df_n=df[df[&#39;FAILURE_SN&#39;]==0].copy()</pre><p>Set the weights. This is the total in the original file, divided by 1000.</p><pre>#failure weight<br>f_weight=1.084<br>#non-failure weight<br>n_weight=119.41</pre><p>Keep relevant fields.</p><pre>df_n=df_n[[‘DATE’,’ID’,’CATEGORY’,’FAILURE_SN’,’MODELING_GROUP’]].copy()<br>df_f=df_f[[‘DATE’,’ID’,’CATEGORY’,’FAILURE_SN’,’MODELING_GROUP’]].copy()</pre><p>Set weight values and define dis-aggregated false positive, false negative, true positive and true negative values.</p><pre>df_n[‘FALSE_NEGATIVE’] = np.where((df_n.CATEGORY==’FALSE_NEGATIVE’), n_weight, 0)<br>df_f[‘FALSE_NEGATIVE’] = np.where((df_f.CATEGORY==’FALSE_NEGATIVE’), f_weight, 0)<br><br>df_n[&#39;FALSE_POSITIVE&#39;] = np.where((df_n.CATEGORY==&#39;FALSE_POSITIVE&#39;), n_weight, 0)<br>df_f[&#39;FALSE_POSITIVE&#39;] = np.where((df_f.CATEGORY==&#39;FALSE_POSITIVE&#39;), f_weight, 0)<br><br>df_n[&#39;TRUE_POSITIVE&#39;] = np.where((df_n.CATEGORY==&#39;TRUE_POSITIVE&#39;), n_weight, 0)<br>df_f[&#39;TRUE_POSITIVE&#39;] = np.where((df_f.CATEGORY==&#39;TRUE_POSITIVE&#39;), f_weight, 0)<br><br>df_n[&#39;TRUE_NEGATIVE&#39;] = np.where((df_n.CATEGORY==&#39;TRUE_NEGATIVE&#39;), n_weight, 0)<br>df_f[&#39;TRUE_NEGATIVE&#39;] = np.where((df_f.CATEGORY==&#39;TRUE_NEGATIVE&#39;), f_weight, 0)</pre><p>Concatenate the failures and non-failures.</p><pre>dfx = pd.concat([df_f, df_n], axis=0)</pre><p>Create the weighted confusion matrix.</p><pre>#Get weighted failures, non-failures and observations per group<br>tipsy = dfx.groupby([&#39;MODELING_GROUP&#39;]).aggregate(<br>    {&#39;FALSE_POSITIVE&#39;: &#39;sum&#39;, &#39;TRUE_POSITIVE&#39;:&#39;sum&#39;, &#39;FALSE_NEGATIVE&#39;:&#39;sum&#39;,&#39;TRUE_NEGATIVE&#39;:&#39;sum&#39;})<br><br>tipsy</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y-NPYWBdyZwmIKxkJ696WA.png" /></figure><pre>tipsy.sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*B-GHSt5A0S2Nl68baIqF6g.png" /></figure><p>Note that the weighted total is about 42.8M. This is very close to the number of records we started with before sampling.</p><p>We cut the false negatives in the Validation set by about 25% (98/(284+98)) based on the assumptions and model. I would need to learn more about the economics of the problem to extrapolate the impact on BackBlaze’s bottom line but think of it this way.</p><p>There are 1,084 failures in the 2020 data. If we decreased this by 25%, we would eliminate 271 unpredicted failures.</p><p>Suppose a false positive costs $25,000; implementing the model would save the company 271*25,000, or about 6.775M dollars. On the other hand, if a false positive costs $500, the solution would only yield a savings of 271*500 or about 135K dollars. The economics of the problem is critically important to understand before you can gauge the accuracy of the solution. The economics will also determine the cut-off and forecast window parameters.</p><p>We have roughly six false positives for every true positive. That’s not ideal, but given that we only have a failure signal about once every 18,000 hours, I don’t think it is an issue. Again, that’s an assumption on my part. If it is an issue, we can tweak things to lower the number at the cost of more false negatives.</p><p>In the next section, I will outline the potential impact of varying the failure window and cut-off assumptions.</p><h3>5.0 Examine the False Negatives with a continuum of Forecast Windows.</h3><p>As I’ve said before, I am not a subject matter expert regarding disk drives. My guess, however, is that the most expensive type of failure is one that you don’t see coming. In other words, a false negative is more costly than a false positive. Since false negatives are likely more expensive, we will look at how they vary as you change the forecast window. For example, how many fewer false negatives will you experience if the forecast window is 30 days instead of 15.</p><p>The numbers in the chart below come from re-running the code above, using different values for the forecast window. The number of false negatives reflects those in the training data set.</p><p>Note a longer forecast window means fewer false negatives.</p><pre>trace = go.Scatter(<br>    x = [5,10,15,20,25,30,45,60,75,90,105,120,135,150,165,180],<br>    y = [283,272,261,258,253,250,242,235,229,224,224,219,216,216,214,212],<br>    mode = &#39;lines&#39;<br>)<br>layout = go.Layout(<br>    title=&#39;False Negatives with a 0.25 Cut-Off and varying Forecast Windows&#39;,<br>    xaxis=dict(<br>        title=&#39;Forecast Window in Days&#39;,<br>        titlefont=dict(<br>            family=&#39;Courier New, monospace&#39;,<br>            size=18,<br>            color=&#39;#7f7f7f&#39;<br>        )<br>    ),<br>    yaxis=dict(<br>        title=&#39;False Negatives in Training Set&#39;,<br>        titlefont=dict(<br>            family=&#39;Courier New, monospace&#39;,<br>            size=18,<br>            color=&#39;#7f7f7f&#39;<br>        )<br>    )<br>)<br>    <br>data=[trace]  <br>fig = go.Figure(data=data, layout=layout)<br>plotly.offline.iplot(fig, filename=&#39;shapes-lines&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dgjybFbrAIb87nIXT3nrew.png" /></figure><h3>6.0 Examine the False Negatives with a continuum of Cut-Off Values.</h3><p>Now, let’s take a look when we keep a constant window, but change the cut-off.</p><pre>trace = go.Scatter(<br>    x = [0.05,0.1,0.15,0.2,0.25,0.3,0.35,0.4,0.45],<br>    y = [298,249,251,251,261,266,269,272,279],<br>    mode = &#39;lines&#39;<br>)<br><br>layout = go.Layout(<br>    title=&#39;False Negatives by Cut-Off with a Fifteen Day Prediction Window&#39;,<br>    xaxis=dict(<br>        title=&#39;Cut-Off&#39;,<br>        titlefont=dict(<br>            family=&#39;Courier New, monospace&#39;,<br>            size=18,<br>            color=&#39;#7f7f7f&#39;<br>        )<br>    ),<br>    yaxis=dict(<br>        title=&#39;False Negatives&#39;,<br>        titlefont=dict(<br>            family=&#39;Courier New, monospace&#39;,<br>            size=18,<br>            color=&#39;#7f7f7f&#39;<br>        )<br>    )<br>)<br>    <br>data=[trace]  <br>fig = go.Figure(data=data, layout=layout)<br>plotly.offline.iplot(fig, filename=&#39;shapes-lines&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G6J_PICu8KAR7eyioSRJXg.png" /></figure><h3>7.0 Conclusion and Summary</h3><p>I want to reiterate that this series of articles is not the “Final Answer” for Backblaze. My intent is to provide a guidebook for solving machine failure problems. Someone with better knowledge of hard drives can use these articles to find that “Final Answer”, if it exists.</p><p>A data scientist must set a few parameters to evaluate an equipment failure solution. Setting these parameters is context specific and requires knowledge of the business problem. As I have mentioned, I am not an expert on disk drives or maintaining a data center.</p><p>Here are the parameters necessary to evaluate a machine learning model for equipment failure.</p><ol><li>Feature window. The amount of history to use when predicting the current period. In the current solution, I assumed that the previous seven days are relevant when predicting a failure today.</li><li>Forecast window. The time a prediction of failure lasts. I assumed that a failure signal lasts 15 days in the current solution. This means a signal today implies that the machine will fail in the next 15 days. If a signal occurs on the 1st and a failure occurs before the 15th, the signal is a true positive. If a failure does not occur before the 15th, the signal is a false positive. Likewise, if a machine fails and there is no signal in the previous 15 days, it is a false negative; generally, the longer the forecast window, the fewer false positives, and negatives.</li><li>The cut-off value. A machine learning model yields a probability of failure. A data scientist must determine at what cut-off the model predicts a failure. For example, a cut-off of .1 means that if the likelihood of failing is greater than .1, we expect the machine to fail. If the probability is less than .1, we expect the machine not to fail. If a data scientist changes the cut-off from .1 to .2, there will be fewer failure signals. Because there are fewer signals, there will likely be fewer false positives, fewer true positives, and more false negatives. Likewise, if a data scientist lowers the cut-off from .2 to .1, there will be more failure signals. More failure signals mean more true positives, more false positives, and fewer true negatives.</li></ol><p>In the current solution, we decreased the number of unforeseen failures by 21%. Also, note that we have roughly six false positives for every true positive. That’s not ideal, but given that we only have a failure signal about once every 18,000 hours, I don’t think it is an issue. Again, that’s an assumption on my part.</p><p>This solution is based on assumptions and changing these assumptions will, undoubtedly, change the results.</p><p>Remember, the point here is not to find the ultimate answer. It is to demonstrate how to find it when combined with subject matter expertise.</p><p>Hopefully, you have found these six articles useful. Please let me know if you have any questions.</p><p>Thanks so much for your time.</p><h3>Author</h3><p><strong>Shad Griffin</strong>, is a Certified Thought Leader and Data Scientist at IBM</p><p>All data used in this notebook is the property of Backblaze.com.</p><p>For questions regarding use of data please see the following website.</p><ul><li><a href="https://www.backblaze.com/b2/hard-drive-test-data.html">Backblaze Hard Drive Stats</a></li><li><a href="https://www.kaggle.com/datasets/backblaze/hard-drive-test-data">Hard Drive Test Data</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d5cb45a88db" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/a-complete-solution-to-the-backbaze-com-kaggle-problem-9d5cb45a88db">A Complete Solution to the BackBaze.com Kaggle Problem</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Complete Solution to the BackBaze.com Kaggle Problem]]></title>
            <link>https://medium.com/geekculture/a-complete-solution-to-the-backbaze-com-kaggle-problem-3a9558cd8929?source=rss-b2cb0fe3df91------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a9558cd8929</guid>
            <category><![CDATA[predictive-maintenance]]></category>
            <category><![CDATA[equipment-failure]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[spark]]></category>
            <dc:creator><![CDATA[Shad Griffin]]></dc:creator>
            <pubDate>Wed, 28 Dec 2022 01:34:32 GMT</pubDate>
            <atom:updated>2026-06-03T17:26:19.540Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Complete Solution to the Backblaze Machine Failure Kaggle Problem, V</h3><h3>Step Five, Modeling the Data</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s4fwIhjYir1hfWb3pJNvSA.jpeg" /></figure><p><a href="https://github.com/shadgriffin/backblazedata/blob/master/Backblaze.com%20--Step%20Five--%20Build%20model.ipynb">backblazedata/Backblaze.com --Step Five-- Build model.ipynb at master · shadgriffin/backblazedata</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FGJewNI72VTE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DGJewNI72VTE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FGJewNI72VTE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce6fcde0251c03f1e41e42e1eefd4955/href">https://medium.com/media/ce6fcde0251c03f1e41e42e1eefd4955/href</a></iframe><ul><li><a href="https://jshadgriffin.medium.com/a-complete-solution-to-the-backbaze-com-kaggle-problem-9d5cb45a88db">A Complete Solution to the BackBaze.com Kaggle Problem</a></li><li><a href="https://jshadgriffin.medium.com/a-complete-solution-to-the-backbaze-com-kaggle-problem-7c0f51429908">A Complete Solution to the BackBaze.com Kaggle Problem</a></li><li><a href="https://jshadgriffin.medium.com/a-complete-solution-to-the-backbaze-com-kaggle-problem-cd51259787b7">A Complete Solution to the BackBaze.com Kaggle Problem</a></li><li><a href="https://jshadgriffin.medium.com/a-complete-solution-to-the-backbaze-com-kaggle-problem-1f53235bdb4e">A Complete Solution to the BackBaze.com Kaggle Problem</a></li><li><a href="https://jshadgriffin.medium.com/a-complete-solution-to-the-backbaze-com-kaggle-problem-cf1fab1af529">A Complete Solution to the BackBaze.com Kaggle Problem</a></li></ul><h3>1.0 Introduction</h3><p>Note this is part five of a six-part solution.</p><p>Backblaze, you are the “GOAT.” You are the “cat’s meow.” You “Rock the House.” In case you don’t know why Backblaze is so totally “kick-ass,” they open-sourced a vast set of hard drive information a few years ago and continue updating it each quarter. What a treasure trove of superb data. Backblaze, thank you from the bottom of my heart.</p><p>The Backblaze data includes operational metrics from hard drives with an indicator of a hard-drive failure. It is an excellent source for teaching techniques related to machine failure. Again, thank you for making this available to the open-source community. Here is a link to the data.</p><p><a href="https://www.backblaze.com/b2/hard-drive-test-data.html">Backblaze Hard Drive Stats</a></p><p>My goal in this series of articles is not to give the best solution with the highest AUC. My goal is to show you how to approach equipment failure problems and build solutions that reflect realistic accuracy, and provide an easy transition from the lab to the real world.</p><p>I will use a Spark/Python Jupyter notebook inside IBM’s Watson Studio on the cloud as a tool in this discussion.</p><p><a href="https://www.ibm.com/cloud/watson-studio">IBM Watson Studio - Overview</a></p><p>I will also be using cloud object storage on the IBM cloud.</p><p><a href="https://cloud.ibm.com/docs/cloud-object-storage">https://cloud.ibm.com/docs/cloud-object-storage</a></p><p>To be fully transparent, I know very little about the operation and management of disk drives. I am not a subject matter expert in disk drives. My lack of expertise is critical to note because developing data science solutions usually requires some knowledge of the subject matter. Because of this lack of knowledge, I am sure this solution is lacking in some areas. Despite this, I have made assumptions when necessary, documented gaps in my understanding, and plowed through the problem from beginning to end. Consider this work a template to solve the problem, not a solution specifically built for Backblaze to operationalize immediately. Undoubtedly, I would need to consult with disk drive experts before finalizing the solution.</p><p>In the fifth article of the series, I build a model.</p><p>I created these notebooks with a runtime useing 1 driver with 1 vCPU and 4 GB RAM, and 2 executors each with 1 vCPU and 4 GB RAM. This is available for free on the IBM Cloud. Some of the notebooks take a few hours to run. You’ll need to schedule your notebooks to run as jobs.</p><p>I recommend working through this article if you have not previously done so. It will provide further details on the techniques used to understand the data from Backblaze.</p><p><a href="https://medium.com/swlh/machine-learning-for-equipment-failure-prediction-and-predictive-maintenance-pm-e72b1ce42da1">Machine Learning for Equipment Failure Prediction and Predictive Maintenance (PM)</a></p><h3>2.0 Establish environment and Parameters</h3><p>Establish Libraries</p><pre>from functools import reduce<br>from pyspark.sql import DataFrame<br><br>import pyspark.sql.functions as F<br>from pyspark.sql.functions import *<br><br>import pandas as pd<br><br>from pyspark.ml.feature import StringIndexer, VectorAssembler<br>from pyspark.ml.evaluation import MulticlassClassificationEvaluator<br>from sklearn.metrics import confusion_matrix<br>from pyspark.ml.classification import GBTClassifier<br>import numpy as np<br><br>spark.conf.set(&quot;spark.sql.broadcastTimeout&quot;,  7200000)<br>spark.conf.set(&quot;spark.sql.parquet.compression.codec&quot;, &quot;gzip&quot;)</pre><p>Define Cloud Object Storage Credentials</p><pre>import ibmos2spark, os<br># @hidden_cell<br><br>if os.environ.get(&#39;RUNTIME_ENV_LOCATION_TYPE&#39;) == &#39;external&#39;:<br>    endpoint_ae0ee98cbce04bcbb3163be1d0955096 = &#39;https://s3-api.us-geo.objectstorage.softlayer.net&#39;<br>else:<br>    endpoint_ae0ee98cbce04bcbb3163be1d0955096 = &#39;https://s3-api.us-geo.objectstorage.service.networklayer.com&#39;<br><br>credentials = {<br>    &#39;endpoint&#39;: XXXXXX,<br>    &#39;service_id&#39;: &#39;XXXXX&#39;,<br>    &#39;iam_service_endpoint&#39;: &#39;XXXXX&#39;,<br>    &#39;api_key&#39;: &#39;XXXXX&#39;<br>}<br><br>configuration_name = &#39;XXXXX&#39;<br>cos = ibmos2spark.CloudObjectStorage(sc, credentials, configuration_name, &#39;bluemix_cos&#39;)</pre><p>Read in Data</p><pre>df = spark.read.parquet(cos.url(https://medium.com/&#39;data_2020_model.parquet&#39;,%20&#39;xxxxxcccc&#39;))<br>print((df.count(), len(df.columns)))</pre><h3>3.0 Create a target window.</h3><p>Typically, industrial machines fail infrequently. Manufacturers design and build them to last and perform reliably over time. Reliable machines mean we have few incidences of failure to study and model. One standard way of dealing with a small number of failures is to expand the failure window. Instead of predicting the specific day of failure in our current use case, predict the days leading up to failure. Expanding the failure window makes sense. When a machine fails, it rarely just happens. It is rare for a machine to be perfect on Monday, terrible on Tuesday, and then perfect on Wednesday without some intervention. Machines, like humans, wear down over time. Because of this, we can incorporate the days before a failure as part of the dependent variable.</p><p>There is no magic in determining the length of the failure window. The only hard rule is that it needs to fit the context of the problem. For example, if a machine lasts 20 years, a 5-second failure window is a little short. If it fails every twenty years, a window of three, six, or nine months is likely more reasonable. Likewise, a six-day failure window does not make much sense if a machine fails twice a day.</p><p>In the current use case, I used an eleven-day failure window. Again, there is nothing magical about that. I chose it because it makes sense.</p><p>Again, there is a lot about disk drives that I don’t know. I am not a subject matter expert regarding disk drives and storage. Someone with more expertise in the space may argue for a larger or smaller window. Also, the target window is a parameter that you can tune. We may get better results with a larger or smaller window. I did not attempt to adjust the window size but may do some time in the future.</p><p>Create a data frame with only records of failure.</p><pre>df_failure=df.filter(df.FAILURE ==1)</pre><p>Limit the fields</p><pre>df_failure=df_failure[[‘DATE’,’SERIAL_NUMBER’,’FAILURE’]]</pre><p>Drop the failure field and rename the date field as the failure date.</p><pre>df_failure = df_failure.drop(&quot;FAILURE&quot;)<br>df_failure=df_failure.withColumnRenamed(&quot;DATE&quot;,&quot;FAILURE_DATE&quot;)<br>df_failure=df_failure.withColumnRenamed(&quot;SERIAL_NUMBER&quot;,&quot;SERIAL_NUMBERX&quot;)</pre><p>Ensure you only have one failure per serial number.</p><pre>from pyspark.sql import Window<br>from pyspark.sql.functions import rank<br>window = Window.partitionBy(&quot;SERIAL_NUMBERX&quot;).orderBy(&quot;FAILURE_DATE&quot;)<br>df_failure=(df_failure.withColumn(&#39;rank&#39;, rank().over(window))<br>.filter(col(&#39;rank&#39;) == 1)<br>.drop(&#39;rank&#39;))</pre><p>Keep a list of disks with a failure. We will use this later on.</p><pre>df_failure_list=df_failure[[&#39;SERIAL_NUMBERX&#39;]]<br>df_failure_list = df_failure_list.withColumn(&quot;wookie&quot;, lit(1))</pre><p>Inner join the list of failures to the original data frame. The result is a complete list of disks with a failure.</p><pre>df_failure=df.join(df_failure,(((df.SERIAL_NUMBER) ==  (df_failure.SERIAL_NUMBERX)) ),&quot;inner&quot;)<br>df_failure = df_failure.drop(&quot;SERIAL_NUMBERX&quot;)</pre><p>Select relevant fields and calculate the difference between the current date and the failure date.</p><pre>from pyspark.sql.functions import *<br>dater=df_failure.select(<br>      col(&quot;SERIAL_NUMBER&quot;),<br>      col(&quot;DATE&quot;),<br>      col(&quot;FAILURE_DATE&quot;),<br>      datediff(col(&quot;FAILURE_DATE&quot;),col(&quot;DATE&quot;)).alias(&quot;datediff&quot;))</pre><p>Create a field called “TARGET” that is 1 if the date is with 11 days of a failure.</p><pre>from pyspark.sql.functions import when<br><br>dater=dater.withColumn(&quot;TARGET&quot;, when(dater[&#39;datediff&#39;] &lt;=10, 1).otherwise(0))<br><br></pre><p>Rename columns in the data frame and append to the data frame of failures.</p><pre>dater=dater.withColumnRenamed(&quot;SERIAL_NUMBER&quot;,&quot;SERIAL_NUMBERX&quot;)<br>dater=dater.withColumnRenamed(&quot;DATE&quot;,&quot;DATEX&quot;)<br>dater=dater.withColumnRenamed(&quot;FAILURE_DATE&quot;,&quot;FAILURE_DATEX&quot;)</pre><pre>df_failure=df_failure.join(dater,(((df_failure.SERIAL_NUMBER) ==  (dater.SERIAL_NUMBERX)) &amp; ((df_failure.DATE)==(dater.DATEX)) &amp; ((df_failure.FAILURE_DATE)==(dater.FAILURE_DATEX))),&quot;inner&quot;)<br>#drop dummy keys<br>df_failure = df_failure.drop(&quot;SERIAL_NUMBERX&quot;)<br>df_failure = df_failure.drop(&quot;DATEX&quot;)<br>df_failure = df_failure.drop(&quot;FAILURE_DATEX&quot;)<br>df_failure = df_failure.drop(&quot;datediff&quot;)</pre><p>Join the list of failure disks to the original data frame, keep only disks that do not have a failure.</p><pre>#join the list of failure directories to the original data frame with a left join<br>df_nonfailure=df.join(df_failure_list,(((df.SERIAL_NUMBER) ==  (df_failure_list.SERIAL_NUMBERX)) ),&quot;left&quot;)<br>#drop dummy key<br>df_nonfailure = df_nonfailure.drop(&quot;SERIAL_NUMBERX&quot;)<br>#assign dummy variable to indicate disk did not fail in 2020<br>df_nonfailure=df_nonfailure.na.fill(0,[&quot;wookie&quot;]) <br>#select only disks that failed<br>df_nonfailure=df_nonfailure.filter(df_nonfailure.wookie ==0)<br>#assign the predicted variable of 0<br>df_nonfailure = df_nonfailure.withColumn(&quot;TARGET&quot;, lit(0))<br>#clean things up<br>df_nonfailure = df_nonfailure.drop(&quot;wookie&quot;)</pre><p>Create a failure date way in the future for the nonfailure data.</p><pre>df_nonfailure = df_nonfailure.withColumn(&quot;FAILURE_DATE&quot;, expr(&quot;make_date(2099, 12, 12)&quot;))</pre><p>Append failures and non-failures.</p><pre>df = df_failure.unionByName(df_nonfailure)</pre><h3>4.0 Create training, testing and validation groups</h3><p>Next, we will need to create a Training, Testing and Validation group for our modeling process. In this use case and in most equipment failure problems, we can not randomly assign records to each group. Because the data is a cross-sectional time-series, we must define the Training, Testing and Validation groups based on serial number. I wrote about the reasons for this extensively in another article. For more information, please the following:</p><p><a href="https://medium.com/towards-data-science/assigning-panel-data-to-training-testing-and-validation-groups-for-machine-learning-models-7017350ab86e">https://medium.com/towards-data-science/assigning-panel-data-to-training-testing-and-validation-groups-for-machine-learning-models-7017350ab86e</a></p><p>Create a unique list of serial numbers.</p><pre>df_sample=df.select([c for c in df.columns if c in [&#39;SERIAL_NUMBER&#39;]])<br>df_sample=df_sample.dropDuplicates([&#39;SERIAL_NUMBER&#39;])<br>df_sample=df_sample.withColumn(&#39;wookie&#39;, rand())</pre><p>Randomly assign the serial numbers to either the Training, Testing or Validation group.</p><pre>df_sample = df_sample.withColumn(&quot;GROUP&quot;, when(df_sample.wookie &lt;= 0.33333333,&quot;TRAINING&quot;)<br>                                 .when(df_sample.wookie &gt;=0.6666666667,&quot;TESTING&quot;)<br>                                 .otherwise(&quot;VALIDATION&quot;))</pre><p>Append the group to the original data frame.</p><pre>df_sample = df_sample.withColumnRenamed(&quot;SERIAL_NUMBER&quot;,&quot;DOODEE&quot;)<br>df_sample = df_sample.drop(&quot;wookie&quot;)<br><br><br>df=df.join(df_sample,(((df_sample.DOODEE) ==  (df.SERIAL_NUMBER))),&quot;inner&quot;)<br>df = df.drop(&quot;DOODEE&quot;)</pre><h3>5.0 Prepare the data for the model</h3><p>Reformat features</p><pre>from pyspark.sql.types import *<br>df = df.withColumn(&quot;MODEL_FAIL_CNT&quot;, df[&quot;MODEL_FAIL_CNT&quot;].cast(DecimalType(12,6)))<br>df = df.withColumn(&quot;MODEL_FAIL_RATE&quot;, df[&quot;MODEL_FAIL_RATE&quot;].cast(DecimalType(12,6)))<br>df = df.withColumn(&quot;MODEL_FAIL_TOTAL&quot;, df[&quot;MODEL_FAIL_TOTAL&quot;].cast(DecimalType(12,6)))<br>df = df.withColumn(&quot;MANU_FAIL_RATE&quot;, df[&quot;MANU_FAIL_RATE&quot;].cast(DecimalType(12,6)))<br>df = df.withColumn(&quot;MANU_FAIL_CNT&quot;, df[&quot;MANU_FAIL_CNT&quot;].cast(DecimalType(12,6)))<br>df = df.withColumn(&quot;MANU_FAIL_TOTAL&quot;, df[&quot;MANU_FAIL_TOTAL&quot;].cast(DecimalType(12,6)))<br>df = df.withColumn(&quot;REALLOCATED_SECTOR_COUNT_N_MOD&quot;, df[&quot;REALLOCATED_SECTOR_COUNT_N_MOD&quot;].cast(DecimalType(12,6)))<br>df = df.withColumn(&quot;REPORTED_UNCORRECTABLE_ERRORS_N_MOD&quot;, df[&quot;REPORTED_UNCORRECTABLE_ERRORS_N_MOD&quot;].cast(DecimalType(12,6)))<br>df = df.withColumn(&quot;COMMAND_TIMEOUT_N_MOD&quot;, df[&quot;COMMAND_TIMEOUT_N_MOD&quot;].cast(DecimalType(12,6)))<br>df = df.withColumn(&quot;CURRENT_PENDING_SECTOR_COUNT_N_MOD&quot;, df[&quot;CURRENT_PENDING_SECTOR_COUNT_N_MOD&quot;].cast(DecimalType(12,6)))<br>df = df.withColumn(&quot;POWER_ON_HOURS_N_MOD&quot;, df[&quot;POWER_ON_HOURS_N_MOD&quot;].cast(DecimalType(12,6)))<br>df = df.withColumn(&quot;REALLOCATED_SECTOR_COUNT_R_MOD&quot;, df[&quot;REALLOCATED_SECTOR_COUNT_R_MOD&quot;].cast(DecimalType(12,6)))<br>df = df.withColumn(&quot;REPORTED_UNCORRECTABLE_ERRORS_R_MOD&quot;, df[&quot;REPORTED_UNCORRECTABLE_ERRORS_R_MOD&quot;].cast(DecimalType(12,6)))<br>df = df.withColumn(&quot;COMMAND_TIMEOUT_R_MOD&quot;, df[&quot;COMMAND_TIMEOUT_R_MOD&quot;].cast(DecimalType(12,6)))<br>df = df.withColumn(&quot;CURRENT_PENDING_SECTOR_COUNT_R_MOD&quot;, df[&quot;CURRENT_PENDING_SECTOR_COUNT_R_MOD&quot;].cast(DecimalType(12,6)))<br>df = df.withColumn(&quot;POWER_ON_HOURS_R_MOD&quot;, df[&quot;POWER_ON_HOURS_R_MOD&quot;].cast(DecimalType(12,6)))<br>df = df.withColumn(&quot;REALLOCATED_SECTOR_COUNT_N_MAN&quot;, df[&quot;REALLOCATED_SECTOR_COUNT_N_MAN&quot;].cast(DecimalType(12,6)))<br>df = df.withColumn(&quot;REPORTED_UNCORRECTABLE_ERRORS_N_MAN&quot;, df[&quot;REPORTED_UNCORRECTABLE_ERRORS_N_MAN&quot;].cast(DecimalType(12,6)))<br>df = df.withColumn(&quot;COMMAND_TIMEOUT_N_MAN&quot;, df[&quot;COMMAND_TIMEOUT_N_MAN&quot;].cast(DecimalType(12,6)))<br>df = df.withColumn(&quot;CURRENT_PENDING_SECTOR_COUNT_N_MAN&quot;, df[&quot;CURRENT_PENDING_SECTOR_COUNT_N_MAN&quot;].cast(DecimalType(12,6)))<br>df = df.withColumn(&quot;POWER_ON_HOURS_N_MAN&quot;, df[&quot;POWER_ON_HOURS_N_MAN&quot;].cast(DecimalType(12,6)))<br>df = df.withColumn(&quot;REALLOCATED_SECTOR_COUNT_R_MAN&quot;, df[&quot;REALLOCATED_SECTOR_COUNT_R_MAN&quot;].cast(DecimalType(12,6)))<br>df = df.withColumn(&quot;REPORTED_UNCORRECTABLE_ERRORS_R_MAN&quot;, df[&quot;REPORTED_UNCORRECTABLE_ERRORS_R_MAN&quot;].cast(DecimalType(12,6)))<br>df = df.withColumn(&quot;COMMAND_TIMEOUT_R_MAN&quot;, df[&quot;COMMAND_TIMEOUT_R_MAN&quot;].cast(DecimalType(12,6)))<br>df = df.withColumn(&quot;CURRENT_PENDING_SECTOR_COUNT_R_MAN&quot;, df[&quot;CURRENT_PENDING_SECTOR_COUNT_R_MAN&quot;].cast(DecimalType(12,6)))<br>df = df.withColumn(&quot;POWER_ON_HOURS_R_MAN&quot;, df[&quot;POWER_ON_HOURS_R_MAN&quot;].cast(DecimalType(12,6)))</pre><p>Fill missings with -99. Note this will work because we are using a non-parametric model.</p><pre>df=df.na.fill(value=-99)</pre><p>Define three data sets based on allocation to Training, Testing or Validation group.</p><pre>df_training=df.filter(df.GROUP ==&#39;TRAINING&#39;)<br>df_testing=df.filter(df.GROUP ==&#39;TESTING&#39;)<br>df_validation=df.filter(df.GROUP ==&#39;VALIDATION&#39;)</pre><p>Drop features that are non-predictive, text, or deriviatives of the predicted variable.</p><pre>builder=df_training<br>builder = builder.drop(‘DATE’,’SERIAL_NUMBER’,’MODEL’,’FAILURE’,’ROW’,’MANUFACTURER’,’GROUP’,’FAILURE_DATE’,’MODELM’)</pre><p>Define the feature names.</p><pre>feature_names = builder.drop(&#39;TARGET&#39;)</pre><p>Prep the data for modeling and scoring on the validation and testing data sets.</p><pre>features = feature_names.columns<br>va_train = VectorAssembler(inputCols = features, outputCol=’features’)<br><br>va_test=VectorAssembler(inputCols = features, outputCol=&#39;features&#39;)<br><br>va_valid=VectorAssembler(inputCols = features, outputCol=&#39;features&#39;)<br><br>df_training = va_train.transform(df_training)<br>df_validation=va_valid.transform(df_validation)<br>df_testing=va_test.transform(df_testing)<br>builder = va_train.transform(builder)<br><br>builder = builder.select([&#39;features&#39;, &#39;TARGET&#39;])</pre><h3>6.0 Build the model</h3><pre>gbtc = GBTClassifier(labelCol=&quot;TARGET&quot;, maxIter=20)<br>gbtc = gbtc.fit(builder)</pre><h3>7.0 Evaluate model</h3><p>Evaluate the model with non-time-dependent stats like accuracy and F1</p><pre>pred_tr = gbtc.transform(df_training)<br>pred_v = gbtc.transform(df_validation)<br>pred_te = gbtc.transform(df_testing)</pre><pre># Select (prediction, true label) and compute test error<br>evaluator = MulticlassClassificationEvaluator(labelCol=”TARGET”,predictionCol=”prediction”, metricName=(“accuracy”))<br>accuracy = evaluator.evaluate(pred_tr)<br>print(“Training Accuracy = %g” % (accuracy))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*hFQ7hDJL7ua4coUe8znSIQ.png" /></figure><pre># Select (prediction, true label) and compute test error<br>evaluator = MulticlassClassificationEvaluator(labelCol=&quot;TARGET&quot;,predictionCol=&quot;prediction&quot;, metricName=(&quot;accuracy&quot;))<br>accuracy = evaluator.evaluate(pred_te)<br>print(&quot;Testing Accuracy = %g&quot; % (accuracy))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*--Ayn-c-JV62cNR5j3XAJg.png" /></figure><pre># Select (prediction, true label) and compute test error<br>evaluator = MulticlassClassificationEvaluator(labelCol=&quot;TARGET&quot;,predictionCol=&quot;prediction&quot;, metricName=(&quot;accuracy&quot;))<br>accuracy = evaluator.evaluate(pred_v)<br>print(&quot;Validation Accuracy = %g&quot; % (accuracy))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*29oUjOz0y-e4NqApLEeLtg.png" /></figure><pre># Select (prediction, true label) and compute test error<br>evaluator = MulticlassClassificationEvaluator(labelCol=&quot;TARGET&quot;,predictionCol=&quot;prediction&quot;, metricName=(&quot;f1&quot;))<br>f1v = evaluator.evaluate(pred_v)<br><br># Select (prediction, true label) and compute test error<br>evaluator = MulticlassClassificationEvaluator(labelCol=&quot;TARGET&quot;,predictionCol=&quot;prediction&quot;, metricName=(&quot;f1&quot;))<br>f1te = evaluator.evaluate(pred_te)<br><br><br><br># Select (prediction, true label) and compute test error<br>evaluator = MulticlassClassificationEvaluator(labelCol=&quot;TARGET&quot;,predictionCol=&quot;prediction&quot;, metricName=(&quot;f1&quot;))<br>f1tr = evaluator.evaluate(pred_tr)<br><br><br>print( &quot;Training F1 = %g&quot; % (f1tr))<br>print( &quot;Testing F1 = %g&quot; % (f1te))<br>print( &quot;Validation F1 = %g&quot; % (f1v))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*oiA4PLPytvLoiDfC0sQ_KA.png" /></figure><p>The results look very promising, but we definitely have more evaluation to do.</p><h3>8.0 Format the scored data for further evaluation</h3><p>Append the scored data into one dataframe</p><pre>pred = pred_tr.union(pred_v)<br>pred =pred.union(pred_te)</pre><p>Select relevant fields.</p><pre>pred=pred.select(&quot;DATE&quot;,&quot;FAILURE&quot;,&quot;SERIAL_NUMBER&quot;,&quot;TARGET&quot;,&quot;GROUP&quot;,&quot;probability&quot;,&quot;FAILURE_DATE&quot;)</pre><p>Convert probablity so that it is usable.</p><pre>pred = pred.withColumn(&quot;probability&quot;,col(&quot;probability&quot;).cast((&quot;string&quot;)))<br>predy = pred.withColumn(&quot;left&quot;, substring_index(pred.probability, &#39;,&#39;, 1))<br>charReplace = udf(lambda x: x.replace(u&#39;[&#39;,&#39;&#39;))<br>predy=predy.withColumn(&#39;left&#39;,charReplace(&#39;left&#39;))<br><br>predy = predy.withColumn(&quot;P_0&quot;,col(&quot;left&quot;).cast((&quot;decimal(38,37)&quot;)))<br>predy = predy.withColumn(&quot;P_1&quot;,1-predy.P_0)</pre><h3>9.0 Export the data for use in Step 6</h3><p>Select Relevant fields</p><pre>predy=predy.select(&quot;DATE&quot;,&quot;SERIAL_NUMBER&quot;,&quot;FAILURE&quot;,&quot;TARGET&quot;,&quot;GROUP&quot;,&quot;P_0&quot;,&quot;P_1&quot;,&quot;FAILURE_DATE&quot;)</pre><p>Convert to Pandas.</p><pre>df_pred = predy.toPandas()</pre><p>Convert to csv.</p><pre>df_pred=df_pred.to_csv(&#39;pred.csv&#39;,index=False)</pre><p>Define Object storage credentials.</p><pre>import os, types<br>import pandas as pd<br>from botocore.client import Config<br>import ibm_boto3<br><br>def __iter__(self): return 0<br># @hidden_cell<br># The following code contains the credentials for a file in your IBM Cloud Object Storage.<br># You might want to remove those credentials before you share your notebook.<br>credentials = {<br>    &#39;IAM_SERVICE_ID&#39;: &#39;XXXXX&#39;,<br>    &#39;IBM_API_KEY_ID&#39;: &#39;XXXXX&#39;,<br>    &#39;ENDPOINT&#39;: &#39;XXXXX&#39;,<br>    &#39;IBM_AUTH_ENDPOINT&#39;: &#39;XXXXX&#39;,<br>    &#39;BUCKET&#39;: &#39;XXXXX&#39;,<br>    &#39;FILE&#39;: &#39;XXXXX&#39;<br>}</pre><pre>from ibm_botocore.client import Config<br>import ibm_boto3<br>cos = ibm_boto3.client(service_name=&#39;s3&#39;,<br>    ibm_api_key_id=credentials[&#39;IBM_API_KEY_ID&#39;],<br>    ibm_service_instance_id=credentials[&#39;IAM_SERVICE_ID&#39;],<br>    ibm_auth_endpoint=credentials[&#39;IBM_AUTH_ENDPOINT&#39;],<br>    config=Config(signature_version=&#39;oauth&#39;),<br>    endpoint_url=credentials[&#39;ENDPOINT&#39;])</pre><p>Export csv to object storage.</p><pre>cos.upload_file(Filename=&#39;pred.csv&#39;,Bucket=credentials[&#39;BUCKET&#39;],Key=&#39;pred.csv&#39;)</pre><p>All data used in this notebook is the property of BackBlaze.</p><p>For questions regarding use of data please see the following website.</p><ul><li><a href="https://www.backblaze.com/b2/hard-drive-test-data.html">Backblaze Hard Drive Stats</a></li><li><a href="https://www.kaggle.com/datasets/backblaze/hard-drive-test-data">Hard Drive Test Data</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a9558cd8929" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/a-complete-solution-to-the-backbaze-com-kaggle-problem-3a9558cd8929">A Complete Solution to the BackBaze.com Kaggle Problem</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Complete Solution to the BackBaze.com Kaggle Problem]]></title>
            <link>https://medium.com/geekculture/a-complete-solution-to-the-backbaze-com-kaggle-problem-7c0f51429908?source=rss-b2cb0fe3df91------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c0f51429908</guid>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[feature-engineering]]></category>
            <category><![CDATA[equipment-failure]]></category>
            <category><![CDATA[predictive-maintenance]]></category>
            <category><![CDATA[kaggle]]></category>
            <dc:creator><![CDATA[Shad Griffin]]></dc:creator>
            <pubDate>Wed, 28 Dec 2022 01:33:54 GMT</pubDate>
            <atom:updated>2026-06-03T17:26:36.181Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Complete Solution to the Backblaze Machine Failure Kaggle Problem, IV</h3><h3>Step Four, Adding Features</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s4fwIhjYir1hfWb3pJNvSA.jpeg" /></figure><p><a href="https://github.com/shadgriffin/backblazedata/blob/master/Backblaze.com%20--Step%20Four--%20Adding%20Features.ipynb">backblazedata/Backblaze.com --Step Four-- Adding Features.ipynb at master · shadgriffin/backblazedata</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FGJewNI72VTE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DGJewNI72VTE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FGJewNI72VTE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce6fcde0251c03f1e41e42e1eefd4955/href">https://medium.com/media/ce6fcde0251c03f1e41e42e1eefd4955/href</a></iframe><ul><li><a href="https://jshadgriffin.medium.com/a-complete-solution-to-the-backbaze-com-kaggle-problem-9d5cb45a88db">A Complete Solution to the BackBaze.com Kaggle Problem</a></li><li><a href="https://jshadgriffin.medium.com/a-complete-solution-to-the-backbaze-com-kaggle-problem-3a9558cd8929">A Complete Solution to the BackBaze.com Kaggle Problem</a></li><li><a href="https://jshadgriffin.medium.com/a-complete-solution-to-the-backbaze-com-kaggle-problem-cd51259787b7">A Complete Solution to the BackBaze.com Kaggle Problem</a></li><li><a href="https://jshadgriffin.medium.com/a-complete-solution-to-the-backbaze-com-kaggle-problem-1f53235bdb4e">A Complete Solution to the BackBaze.com Kaggle Problem</a></li><li><a href="https://jshadgriffin.medium.com/a-complete-solution-to-the-backbaze-com-kaggle-problem-cf1fab1af529">A Complete Solution to the BackBaze.com Kaggle Problem</a></li></ul><h3>1.0 Introduction</h3><p>Note this is part four of a six-part solution.</p><p>Backblaze, you are the “GOAT.” You are the “cat’s meow.” You “Rock the House.” In case you don’t know why Backblaze is so totally “kick-ass,” they open-sourced a vast set of hard drive information a few years ago and continue updating it each quarter. What a treasure trove of superb data. Backblaze, thank you from the bottom of my heart.</p><p>The Backblaze data includes operational metrics from hard drives with an indicator of a hard-drive failure. It is an excellent source for teaching techniques related to machine failure. Again, thank you for making this available to the open-source community. Here is a link to the data.</p><p><a href="https://www.backblaze.com/b2/hard-drive-test-data.html">Backblaze Hard Drive Stats</a></p><p>My goal in this series of articles is not to give the best solution with the highest AUC. My goal is to show you how to approach equipment failure problems and build solutions that reflect realistic accuracy, and provide an easy transition from the lab to the real world.</p><p>I will use a Spark/Python Jupyter notebook inside IBM’s Watson Studio on the cloud as a tool in this discussion.</p><p><a href="https://www.ibm.com/cloud/watson-studio">IBM Watson Studio - Overview</a></p><p>I will also be using cloud object storage on the IBM cloud.</p><p><a href="https://cloud.ibm.com/docs/cloud-object-storage">IBM Cloud Docs</a></p><p>The fourth article in this series we will create featues and append them to the data. We will also append the features we created in Step Two.</p><p>I created these notebooks with a runtime useing 1 driver with 1 vCPU and 4 GB RAM, and 2 executors each with 1 vCPU and 4 GB RAM. This is available for free on the IBM Cloud. Some of the notebooks take a few hours to run. You’ll need to schedule your notebooks to run as jobs.</p><p><a href="https://dataplatform.cloud.ibm.com/docs/content/wsj/analyze-data/schedule-task.html">Scheduling a notebook</a></p><p>I recommend working through this article if you have not previously done so. It will provide further details on the techniques used to understand the data from Backblaze.</p><p><a href="https://medium.com/swlh/machine-learning-for-equipment-failure-prediction-and-predictive-maintenance-pm-e72b1ce42da1">Machine Learning for Equipment Failure Prediction and Predictive Maintenance (PM)</a></p><h3>2.0 Establish environment and parameters</h3><p>Import the Relevant Libraries, connect to object storage and import data from previous step.</p><pre>from functools import reduce<br>from pyspark.sql import DataFrame<br><br>import pyspark.sql.functions as F<br>from pyspark.sql.functions import *<br><br>from pyspark.sql.functions import when<br><br>from pyspark.sql.functions import rand<br>from pyspark.sql.functions import lit<br><br>from pyspark.sql.types import DoubleType<br>from pyspark.sql.functions import col, round<br><br>from pyspark.sql.window import Window<br>from pyspark.sql.functions import row_number<br><br><br>import pandas as pd<br><br><br>spark.conf.set(&quot;spark.sql.broadcastTimeout&quot;,  7200000)<br>spark.conf.set(&quot;spark.sql.parquet.compression.codec&quot;, &quot;gzip&quot;)</pre><pre>import ibmos2spark, os<br># @hidden_cell<br><br>if os.environ.get(&#39;RUNTIME_ENV_LOCATION_TYPE&#39;) == &#39;external&#39;:<br>    endpoint_ae0ee98cbce04bcbb3163be1d0955096 = &#39;https://s3-api.us-geo.objectstorage.softlayer.net&#39;<br>else:<br>    endpoint_ae0ee98cbce04bcbb3163be1d0955096 = &#39;https://s3-api.us-geo.objectstorage.service.networklayer.com&#39;<br><br>credentials = {<br>    &#39;endpoint&#39;: XXXXX,<br>    &#39;service_id&#39;: &#39;XXXXX&#39;,<br>    &#39;iam_service_endpoint&#39;: &#39;XXXXX&#39;,<br>    &#39;api_key&#39;: &#39;XXXXX&#39;<br>}<br><br>configuration_name = &#39;XXXXX&#39;<br>cos = ibmos2spark.CloudObjectStorage(sc, credentials, configuration_name, &#39;bluemix_cos&#39;)</pre><pre>df = spark.read.parquet(cos.url(https://medium.com/&#39;data_2020_final.parquet&#39;,%20&#39;bucketname&#39;))</pre><p>Reformat numeric values to double.</p><pre>for c in [ &#39;REALLOCATED_SECTOR_COUNT_N&#39;,<br> &#39;REPORTED_UNCORRECTABLE_ERRORS_N&#39;,<br> &#39;COMMAND_TIMEOUT_N&#39;,<br> &#39;CURRENT_PENDING_SECTOR_COUNT_N&#39;,<br> &#39;POWER_ON_HOURS_N&#39;,<br> &#39;REALLOCATED_SECTOR_COUNT_R&#39;,<br> &#39;REPORTED_UNCORRECTABLE_ERRORS_R&#39;,<br> &#39;COMMAND_TIMEOUT_R&#39;,<br> &#39;CURRENT_PENDING_SECTOR_COUNT_R&#39;,<br> &#39;POWER_ON_HOURS_R&#39;,&#39;FAILURE&#39;,&#39;CAPACITY_BYTES&#39;]:<br>    # add condition for the cols to be type cast<br>    df=df.withColumn(c, df[c].cast(&#39;double&#39;))</pre><h3>3.0 Create lagged features</h3><p>Create a consecutive row number for each record and serial number.</p><pre><br>df=df.sort(&quot;SERIAL_NUMBER&quot;, &quot;DATE&quot;)<br>windowSpec  = Window.partitionBy(&quot;SERIAL_NUMBER&quot;).orderBy(&quot;DATE&quot;)<br><br>df=df.withColumn(&quot;ROW&quot;,row_number().over(windowSpec))</pre><p>Create lagged by 7 features</p><pre>dfx=df<br><br>df_7 = dfx.withColumn(&#39;ROW_7&#39;, ( dfx[&#39;ROW&#39;] + 7 ) )<br>df_7 = df_7.drop(&quot;ROW&quot;)<br>df_7 = df_7.drop(&quot;DATE&quot;)<br>df_7 = df_7.drop(&quot;MODEL&quot;)<br>df_7 = df_7.drop(&quot;MANUFACTURER&quot;)<br>df_7 = df_7.drop(&quot;CAPACITY_BYTES&quot;)<br>df_7 = df_7.drop(&quot;FAILURE&quot;)<br><br>df_7=df_7.withColumnRenamed(&quot;REALLOCATED_SECTOR_COUNT_R&quot;,&quot;REALLOCATED_SECTOR_COUNT_R_7&quot;)<br>df_7=df_7.withColumnRenamed(&quot;SERIAL_NUMBER&quot;,&quot;SERIAL_NUMBER_7&quot;)<br>df_7=df_7.withColumnRenamed(&quot;REALLOCATED_SECTOR_COUNT_N&quot;,&quot;REALLOCATED_SECTOR_COUNT_N_7&quot;)<br>df_7=df_7.withColumnRenamed(&quot;REPORTED_UNCORRECTABLE_ERRORS_N&quot;,&quot;REPORTED_UNCORRECTABLE_ERRORS_N_7&quot;)<br>df_7=df_7.withColumnRenamed(&quot;COMMAND_TIMEOUT_N&quot;,&quot;COMMAND_TIMEOUT_N_7&quot;)<br>df_7=df_7.withColumnRenamed(&quot;CURRENT_PENDING_SECTOR_COUNT_N&quot;,&quot;CURRENT_PENDING_SECTOR_COUNT_N_7&quot;)<br>df_7=df_7.withColumnRenamed(&quot;POWER_ON_HOURS_N&quot;,&quot;POWER_ON_HOURS_N_7&quot;)<br>df_7=df_7.withColumnRenamed(&quot;REPORTED_UNCORRECTABLE_ERRORS_R&quot;,&quot;REPORTED_UNCORRECTABLE_ERRORS_R_7&quot;)<br>df_7=df_7.withColumnRenamed(&quot;COMMAND_TIMEOUT_R&quot;,&quot;COMMAND_TIMEOUT_R_7&quot;)<br>df_7=df_7.withColumnRenamed(&quot;CURRENT_PENDING_SECTOR_COUNT_R&quot;,&quot;CURRENT_PENDING_SECTOR_COUNT_R_7&quot;)<br>df_7=df_7.withColumnRenamed(&quot;POWER_ON_HOURS_R&quot;,&quot;POWER_ON_HOURS_R_7&quot;)<br><br><br><br>df=df.join(df_7,(((df.ROW) ==  (df_7.ROW_7)) &amp; ((df.SERIAL_NUMBER) ==  (df_7.SERIAL_NUMBER_7))),&quot;left&quot;)<br>df = df.drop(&quot;SERIAL_NUMBER_7&quot;)<br>df = df.drop(&quot;ROW_7&quot;)</pre><p>Create lagged by 6 features</p><pre><br>df_6 = dfx.withColumn(&#39;ROW_6&#39;, ( dfx[&#39;ROW&#39;] + 6 ) )<br>df_6 = df_6.drop(&quot;ROW&quot;)<br>df_6 = df_6.drop(&quot;DATE&quot;)<br>df_6 = df_6.drop(&quot;MODEL&quot;)<br>df_6 = df_6.drop(&quot;MANUFACTURER&quot;)<br><br>df_6 = df_6.drop(&quot;CAPACITY_BYTES&quot;)<br>df_6 = df_6.drop(&quot;FAILURE&quot;)<br><br><br>df_6=df_6.withColumnRenamed(&quot;REALLOCATED_SECTOR_COUNT_R&quot;,&quot;REALLOCATED_SECTOR_COUNT_R_6&quot;)<br>df_6=df_6.withColumnRenamed(&quot;SERIAL_NUMBER&quot;,&quot;SERIAL_NUMBER_6&quot;)<br>df_6=df_6.withColumnRenamed(&quot;REALLOCATED_SECTOR_COUNT_N&quot;,&quot;REALLOCATED_SECTOR_COUNT_N_6&quot;)<br>df_6=df_6.withColumnRenamed(&quot;REPORTED_UNCORRECTABLE_ERRORS_N&quot;,&quot;REPORTED_UNCORRECTABLE_ERRORS_N_6&quot;)<br>df_6=df_6.withColumnRenamed(&quot;COMMAND_TIMEOUT_N&quot;,&quot;COMMAND_TIMEOUT_N_6&quot;)<br>df_6=df_6.withColumnRenamed(&quot;CURRENT_PENDING_SECTOR_COUNT_N&quot;,&quot;CURRENT_PENDING_SECTOR_COUNT_N_6&quot;)<br>df_6=df_6.withColumnRenamed(&quot;POWER_ON_HOURS_N&quot;,&quot;POWER_ON_HOURS_N_6&quot;)<br>df_6=df_6.withColumnRenamed(&quot;REPORTED_UNCORRECTABLE_ERRORS_R&quot;,&quot;REPORTED_UNCORRECTABLE_ERRORS_R_6&quot;)<br>df_6=df_6.withColumnRenamed(&quot;COMMAND_TIMEOUT_R&quot;,&quot;COMMAND_TIMEOUT_R_6&quot;)<br>df_6=df_6.withColumnRenamed(&quot;CURRENT_PENDING_SECTOR_COUNT_R&quot;,&quot;CURRENT_PENDING_SECTOR_COUNT_R_6&quot;)<br>df_6=df_6.withColumnRenamed(&quot;POWER_ON_HOURS_R&quot;,&quot;POWER_ON_HOURS_R_6&quot;)<br><br>df=df.join(df_6,(((df.ROW) ==  (df_6.ROW_6)) &amp; ((df.SERIAL_NUMBER) ==  (df_6.SERIAL_NUMBER_6))),&quot;left&quot;)<br>df = df.drop(&quot;SERIAL_NUMBER_6&quot;)<br>df = df.drop(&quot;ROW_6&quot;)</pre><p>Create lagged by 5 features</p><pre><br>df_5 = dfx.withColumn(&#39;ROW_5&#39;, ( dfx[&#39;ROW&#39;] + 5 ) )<br>df_5 = df_5.drop(&quot;ROW&quot;)<br>df_5 = df_5.drop(&quot;DATE&quot;)<br>df_5 = df_5.drop(&quot;MODEL&quot;)<br>df_5 = df_5.drop(&quot;MANUFACTURER&quot;)<br><br>df_5 = df_5.drop(&quot;CAPACITY_BYTES&quot;)<br>df_5 = df_5.drop(&quot;FAILURE&quot;)<br>df_5=df_5.withColumnRenamed(&quot;REALLOCATED_SECTOR_COUNT_R&quot;,&quot;REALLOCATED_SECTOR_COUNT_R_5&quot;)<br>df_5=df_5.withColumnRenamed(&quot;SERIAL_NUMBER&quot;,&quot;SERIAL_NUMBER_5&quot;)<br>df_5=df_5.withColumnRenamed(&quot;REALLOCATED_SECTOR_COUNT_N&quot;,&quot;REALLOCATED_SECTOR_COUNT_N_5&quot;)<br>df_5=df_5.withColumnRenamed(&quot;REPORTED_UNCORRECTABLE_ERRORS_N&quot;,&quot;REPORTED_UNCORRECTABLE_ERRORS_N_5&quot;)<br>df_5=df_5.withColumnRenamed(&quot;COMMAND_TIMEOUT_N&quot;,&quot;COMMAND_TIMEOUT_N_5&quot;)<br>df_5=df_5.withColumnRenamed(&quot;CURRENT_PENDING_SECTOR_COUNT_N&quot;,&quot;CURRENT_PENDING_SECTOR_COUNT_N_5&quot;)<br>df_5=df_5.withColumnRenamed(&quot;POWER_ON_HOURS_N&quot;,&quot;POWER_ON_HOURS_N_5&quot;)<br>df_5=df_5.withColumnRenamed(&quot;REPORTED_UNCORRECTABLE_ERRORS_R&quot;,&quot;REPORTED_UNCORRECTABLE_ERRORS_R_5&quot;)<br>df_5=df_5.withColumnRenamed(&quot;COMMAND_TIMEOUT_R&quot;,&quot;COMMAND_TIMEOUT_R_5&quot;)<br>df_5=df_5.withColumnRenamed(&quot;CURRENT_PENDING_SECTOR_COUNT_R&quot;,&quot;CURRENT_PENDING_SECTOR_COUNT_R_5&quot;)<br>df_5=df_5.withColumnRenamed(&quot;POWER_ON_HOURS_R&quot;,&quot;POWER_ON_HOURS_R_5&quot;)<br><br>df=df.join(df_5,(((df.ROW) ==  (df_5.ROW_5)) &amp; ((df.SERIAL_NUMBER) ==  (df_5.SERIAL_NUMBER_5))),&quot;left&quot;)<br>df = df.drop(&quot;SERIAL_NUMBER_5&quot;)<br>df = df.drop(&quot;ROW_5&quot;)</pre><p>Create lagged by 4 features.</p><pre><br>df_4 = dfx.withColumn(&#39;ROW_4&#39;, ( dfx[&#39;ROW&#39;] + 4 ) )<br>df_4 = df_4.drop(&quot;ROW&quot;)<br>df_4 = df_4.drop(&quot;DATE&quot;)<br>df_4 = df_4.drop(&quot;MODEL&quot;)<br>df_4 = df_4.drop(&quot;MANUFACTURER&quot;)<br><br>df_4 = df_4.drop(&quot;CAPACITY_BYTES&quot;)<br>df_4 = df_4.drop(&quot;FAILURE&quot;)<br>df_4=df_4.withColumnRenamed(&quot;REALLOCATED_SECTOR_COUNT_R&quot;,&quot;REALLOCATED_SECTOR_COUNT_R_4&quot;)<br>df_4=df_4.withColumnRenamed(&quot;SERIAL_NUMBER&quot;,&quot;SERIAL_NUMBER_4&quot;)<br>df_4=df_4.withColumnRenamed(&quot;REALLOCATED_SECTOR_COUNT_N&quot;,&quot;REALLOCATED_SECTOR_COUNT_N_4&quot;)<br>df_4=df_4.withColumnRenamed(&quot;REPORTED_UNCORRECTABLE_ERRORS_N&quot;,&quot;REPORTED_UNCORRECTABLE_ERRORS_N_4&quot;)<br>df_4=df_4.withColumnRenamed(&quot;COMMAND_TIMEOUT_N&quot;,&quot;COMMAND_TIMEOUT_N_4&quot;)<br>df_4=df_4.withColumnRenamed(&quot;CURRENT_PENDING_SECTOR_COUNT_N&quot;,&quot;CURRENT_PENDING_SECTOR_COUNT_N_4&quot;)<br>df_4=df_4.withColumnRenamed(&quot;POWER_ON_HOURS_N&quot;,&quot;POWER_ON_HOURS_N_4&quot;)<br>df_4=df_4.withColumnRenamed(&quot;REPORTED_UNCORRECTABLE_ERRORS_R&quot;,&quot;REPORTED_UNCORRECTABLE_ERRORS_R_4&quot;)<br>df_4=df_4.withColumnRenamed(&quot;COMMAND_TIMEOUT_R&quot;,&quot;COMMAND_TIMEOUT_R_4&quot;)<br>df_4=df_4.withColumnRenamed(&quot;CURRENT_PENDING_SECTOR_COUNT_R&quot;,&quot;CURRENT_PENDING_SECTOR_COUNT_R_4&quot;)<br>df_4=df_4.withColumnRenamed(&quot;POWER_ON_HOURS_R&quot;,&quot;POWER_ON_HOURS_R_4&quot;)<br><br>df=df.join(df_4,(((df.ROW) ==  (df_4.ROW_4)) &amp; ((df.SERIAL_NUMBER) ==  (df_4.SERIAL_NUMBER_4))),&quot;left&quot;)<br>df = df.drop(&quot;SERIAL_NUMBER_4&quot;)<br>df = df.drop(&quot;ROW_4&quot;)</pre><p>Create lagged by 3 features.</p><pre>df_3 = dfx.withColumn(&#39;ROW_3&#39;, ( dfx[&#39;ROW&#39;] + 3 ) )<br>df_3 = df_3.drop(&quot;ROW&quot;)<br>df_3 = df_3.drop(&quot;DATE&quot;)<br>df_3 = df_3.drop(&quot;MODEL&quot;)<br>df_3 = df_3.drop(&quot;MANUFACTURER&quot;)<br>df_3 = df_3.drop(&quot;CAPACITY_BYTES&quot;)<br>df_3 = df_3.drop(&quot;FAILURE&quot;)<br><br>df_3=df_3.withColumnRenamed(&quot;REALLOCATED_SECTOR_COUNT_R&quot;,&quot;REALLOCATED_SECTOR_COUNT_R_3&quot;)<br>df_3=df_3.withColumnRenamed(&quot;SERIAL_NUMBER&quot;,&quot;SERIAL_NUMBER_3&quot;)<br>df_3=df_3.withColumnRenamed(&quot;REALLOCATED_SECTOR_COUNT_N&quot;,&quot;REALLOCATED_SECTOR_COUNT_N_3&quot;)<br>df_3=df_3.withColumnRenamed(&quot;REPORTED_UNCORRECTABLE_ERRORS_N&quot;,&quot;REPORTED_UNCORRECTABLE_ERRORS_N_3&quot;)<br>df_3=df_3.withColumnRenamed(&quot;COMMAND_TIMEOUT_N&quot;,&quot;COMMAND_TIMEOUT_N_3&quot;)<br>df_3=df_3.withColumnRenamed(&quot;CURRENT_PENDING_SECTOR_COUNT_N&quot;,&quot;CURRENT_PENDING_SECTOR_COUNT_N_3&quot;)<br>df_3=df_3.withColumnRenamed(&quot;POWER_ON_HOURS_N&quot;,&quot;POWER_ON_HOURS_N_3&quot;)<br>df_3=df_3.withColumnRenamed(&quot;REPORTED_UNCORRECTABLE_ERRORS_R&quot;,&quot;REPORTED_UNCORRECTABLE_ERRORS_R_3&quot;)<br>df_3=df_3.withColumnRenamed(&quot;COMMAND_TIMEOUT_R&quot;,&quot;COMMAND_TIMEOUT_R_3&quot;)<br>df_3=df_3.withColumnRenamed(&quot;CURRENT_PENDING_SECTOR_COUNT_R&quot;,&quot;CURRENT_PENDING_SECTOR_COUNT_R_3&quot;)<br>df_3=df_3.withColumnRenamed(&quot;POWER_ON_HOURS_R&quot;,&quot;POWER_ON_HOURS_R_3&quot;)<br><br>df=df.join(df_3,(((df.ROW) ==  (df_3.ROW_3)) &amp; ((df.SERIAL_NUMBER) ==  (df_3.SERIAL_NUMBER_3))),&quot;left&quot;)<br>df = df.drop(&quot;SERIAL_NUMBER_3&quot;)<br>df = df.drop(&quot;ROW_3&quot;)</pre><p>Create lagged by 2 features</p><pre>df_2 = dfx.withColumn(&#39;ROW_2&#39;, ( dfx[&#39;ROW&#39;] + 2 ) )<br>df_2 = df_2.drop(&quot;ROW&quot;)<br>df_2 = df_2.drop(&quot;DATE&quot;)<br>df_2 = df_2.drop(&quot;MODEL&quot;)<br>df_2 = df_2.drop(&quot;MANUFACTURER&quot;)<br>df_2 = df_2.drop(&quot;CAPACITY_BYTES&quot;)<br>df_2 = df_2.drop(&quot;FAILURE&quot;)<br>df_2=df_2.withColumnRenamed(&quot;REALLOCATED_SECTOR_COUNT_R&quot;,&quot;REALLOCATED_SECTOR_COUNT_R_2&quot;)<br>df_2=df_2.withColumnRenamed(&quot;SERIAL_NUMBER&quot;,&quot;SERIAL_NUMBER_2&quot;)<br>df_2=df_2.withColumnRenamed(&quot;REALLOCATED_SECTOR_COUNT_N&quot;,&quot;REALLOCATED_SECTOR_COUNT_N_2&quot;)<br>df_2=df_2.withColumnRenamed(&quot;REPORTED_UNCORRECTABLE_ERRORS_N&quot;,&quot;REPORTED_UNCORRECTABLE_ERRORS_N_2&quot;)<br>df_2=df_2.withColumnRenamed(&quot;COMMAND_TIMEOUT_N&quot;,&quot;COMMAND_TIMEOUT_N_2&quot;)<br>df_2=df_2.withColumnRenamed(&quot;CURRENT_PENDING_SECTOR_COUNT_N&quot;,&quot;CURRENT_PENDING_SECTOR_COUNT_N_2&quot;)<br>df_2=df_2.withColumnRenamed(&quot;POWER_ON_HOURS_N&quot;,&quot;POWER_ON_HOURS_N_2&quot;)<br>df_2=df_2.withColumnRenamed(&quot;REPORTED_UNCORRECTABLE_ERRORS_R&quot;,&quot;REPORTED_UNCORRECTABLE_ERRORS_R_2&quot;)<br>df_2=df_2.withColumnRenamed(&quot;COMMAND_TIMEOUT_R&quot;,&quot;COMMAND_TIMEOUT_R_2&quot;)<br>df_2=df_2.withColumnRenamed(&quot;CURRENT_PENDING_SECTOR_COUNT_R&quot;,&quot;CURRENT_PENDING_SECTOR_COUNT_R_2&quot;)<br>df_2=df_2.withColumnRenamed(&quot;POWER_ON_HOURS_R&quot;,&quot;POWER_ON_HOURS_R_2&quot;)<br><br>df=df.join(df_2,(((df.ROW) ==  (df_2.ROW_2)) &amp; ((df.SERIAL_NUMBER) ==  (df_2.SERIAL_NUMBER_2))),&quot;left&quot;)<br>df = df.drop(&quot;SERIAL_NUMBER_2&quot;)<br>df = df.drop(&quot;ROW_2&quot;)</pre><p>Create lagged by 1 features</p><pre>df_1 = dfx.withColumn(&#39;ROW_1&#39;, ( dfx[&#39;ROW&#39;] + 1 ) )<br>df_1 = df_1.drop(&quot;ROW&quot;)<br>df_1 = df_1.drop(&quot;DATE&quot;)<br>df_1 = df_1.drop(&quot;MODEL&quot;)<br>df_1 = df_1.drop(&quot;MANUFACTURER&quot;)<br>df_1 = df_1.drop(&quot;CAPACITY_BYTES&quot;)<br>df_1 = df_1.drop(&quot;FAILURE&quot;)<br>df_1=df_1.withColumnRenamed(&quot;REALLOCATED_SECTOR_COUNT_R&quot;,&quot;REALLOCATED_SECTOR_COUNT_R_1&quot;)<br>df_1=df_1.withColumnRenamed(&quot;SERIAL_NUMBER&quot;,&quot;SERIAL_NUMBER_1&quot;)<br>df_1=df_1.withColumnRenamed(&quot;REALLOCATED_SECTOR_COUNT_N&quot;,&quot;REALLOCATED_SECTOR_COUNT_N_1&quot;)<br>df_1=df_1.withColumnRenamed(&quot;REPORTED_UNCORRECTABLE_ERRORS_N&quot;,&quot;REPORTED_UNCORRECTABLE_ERRORS_N_1&quot;)<br>df_1=df_1.withColumnRenamed(&quot;COMMAND_TIMEOUT_N&quot;,&quot;COMMAND_TIMEOUT_N_1&quot;)<br>df_1=df_1.withColumnRenamed(&quot;CURRENT_PENDING_SECTOR_COUNT_N&quot;,&quot;CURRENT_PENDING_SECTOR_COUNT_N_1&quot;)<br>df_1=df_1.withColumnRenamed(&quot;POWER_ON_HOURS_N&quot;,&quot;POWER_ON_HOURS_N_1&quot;)<br>df_1=df_1.withColumnRenamed(&quot;REPORTED_UNCORRECTABLE_ERRORS_R&quot;,&quot;REPORTED_UNCORRECTABLE_ERRORS_R_1&quot;)<br>df_1=df_1.withColumnRenamed(&quot;COMMAND_TIMEOUT_R&quot;,&quot;COMMAND_TIMEOUT_R_1&quot;)<br>df_1=df_1.withColumnRenamed(&quot;CURRENT_PENDING_SECTOR_COUNT_R&quot;,&quot;CURRENT_PENDING_SECTOR_COUNT_R_1&quot;)<br>df_1=df_1.withColumnRenamed(&quot;POWER_ON_HOURS_R&quot;,&quot;POWER_ON_HOURS_R_1&quot;)<br>df=df.join(df_1,(((df.ROW) ==  (df_1.ROW_1)) &amp; ((df.SERIAL_NUMBER) ==  (df_1.SERIAL_NUMBER_1))),&quot;left&quot;)<br>df = df.drop(&quot;SERIAL_NUMBER_1&quot;)<br>df = df.drop(&quot;ROW_1&quot;)</pre><h3>4.0 Create Max, Min, Sum, Mean and Relative Change Features</h3><pre>from pyspark.sql.functions import col<br><br>from pyspark.sql.functions import greatest<br>from pyspark.sql.functions import  least<br>from pyspark.sql.functions import  mean<br># max of last 8<br>df = df.withColumn(&#39;POWER_ON_HOURS_R_MAX&#39;, greatest(&#39;POWER_ON_HOURS_R&#39;,&#39;POWER_ON_HOURS_R_7&#39;,&#39;POWER_ON_HOURS_R_6&#39;,&#39;POWER_ON_HOURS_R_5&#39;,\<br>                                                    &#39;POWER_ON_HOURS_R_4&#39;,&#39;POWER_ON_HOURS_R_3&#39;,&#39;POWER_ON_HOURS_R_2&#39;,&#39;POWER_ON_HOURS_R_1&#39;))<br># min of last 8<br>df = df.withColumn(&#39;POWER_ON_HOURS_R_MIN&#39;, least(&#39;POWER_ON_HOURS_R&#39;,&#39;POWER_ON_HOURS_R_7&#39;,&#39;POWER_ON_HOURS_R_6&#39;,&#39;POWER_ON_HOURS_R_5&#39;,\<br>                                                    &#39;POWER_ON_HOURS_R_4&#39;,&#39;POWER_ON_HOURS_R_3&#39;,&#39;POWER_ON_HOURS_R_2&#39;,&#39;POWER_ON_HOURS_R_1&#39;))<br># sum of last 8<br>df = df.withColumn(&#39;POWER_ON_HOURS_R_SUM&#39;, (df.POWER_ON_HOURS_R+df.POWER_ON_HOURS_R_7+df.POWER_ON_HOURS_R_6+df.POWER_ON_HOURS_R_5+\<br>                                                    df.POWER_ON_HOURS_R_4+df.POWER_ON_HOURS_R_3+df.POWER_ON_HOURS_R_2+df.POWER_ON_HOURS_R_1))<br><br>#mean of last 8 periods<br>df = df.withColumn(&#39;POWER_ON_HOURS_R_MEAN&#39;, df.POWER_ON_HOURS_R_SUM/8)<br>#variance of last 8<br>df = df.withColumn(&#39;POWER_ON_HOURS_R_VAR&#39;, df.POWER_ON_HOURS_R_MAX/df.POWER_ON_HOURS_R_MIN)<br>#daily variance from running mean<br>df = df.withColumn(&#39;POWER_ON_HOURS_R_DELTA&#39;, df.POWER_ON_HOURS_R/df.POWER_ON_HOURS_R_MEAN)<br>#Running average divided by running max<br>df = df.withColumn(&#39;POWER_ON_HOURS_R_VARX&#39;, df.POWER_ON_HOURS_R_MEAN/df.POWER_ON_HOURS_R_MAX)<br>#runnning average divided by running min<br>df = df.withColumn(&#39;POWER_ON_HOURS_R_VARN&#39;, df.POWER_ON_HOURS_R_MEAN/df.POWER_ON_HOURS_R_MIN)<br>#current valud divided by running max<br>df = df.withColumn(&#39;POWER_ON_HOURS_R_DELTAX&#39;, df.POWER_ON_HOURS_R/df.POWER_ON_HOURS_R_MAX)<br>#current value divided by running min<br>df = df.withColumn(&#39;POWER_ON_HOURS_R_DELTAN&#39;, df.POWER_ON_HOURS_R/df.POWER_ON_HOURS_R_MIN)</pre><pre>df = df.withColumn(&#39;POWER_ON_HOURS_N_MAX&#39;, greatest(&#39;POWER_ON_HOURS_N&#39;,&#39;POWER_ON_HOURS_N_7&#39;,&#39;POWER_ON_HOURS_N_6&#39;,&#39;POWER_ON_HOURS_N_5&#39;,\<br>                                                    &#39;POWER_ON_HOURS_N_4&#39;,&#39;POWER_ON_HOURS_N_3&#39;,&#39;POWER_ON_HOURS_N_2&#39;,&#39;POWER_ON_HOURS_N_1&#39;))<br><br>df = df.withColumn(&#39;POWER_ON_HOURS_N_MIN&#39;, least(&#39;POWER_ON_HOURS_N&#39;,&#39;POWER_ON_HOURS_N_7&#39;,&#39;POWER_ON_HOURS_N_6&#39;,&#39;POWER_ON_HOURS_N_5&#39;,\<br>                                                    &#39;POWER_ON_HOURS_N_4&#39;,&#39;POWER_ON_HOURS_N_3&#39;,&#39;POWER_ON_HOURS_N_2&#39;,&#39;POWER_ON_HOURS_N_1&#39;))<br><br>df = df.withColumn(&#39;POWER_ON_HOURS_N_SUM&#39;, (df.POWER_ON_HOURS_N+df.POWER_ON_HOURS_N_7+df.POWER_ON_HOURS_N_6+df.POWER_ON_HOURS_N_5+\<br>                                                    df.POWER_ON_HOURS_N_4+df.POWER_ON_HOURS_N_3+df.POWER_ON_HOURS_N_2+df.POWER_ON_HOURS_N_1))<br><br><br>df = df.withColumn(&#39;POWER_ON_HOURS_N_MEAN&#39;, df.POWER_ON_HOURS_N_SUM/8)<br>df = df.withColumn(&#39;POWER_ON_HOURS_N_VAR&#39;, df.POWER_ON_HOURS_N_MAX/df.POWER_ON_HOURS_N_MIN)<br>df = df.withColumn(&#39;POWER_ON_HOURS_N_DELTA&#39;, df.POWER_ON_HOURS_N/df.POWER_ON_HOURS_N_MEAN)<br>df = df.withColumn(&#39;POWER_ON_HOURS_N_VARX&#39;, df.POWER_ON_HOURS_N_MEAN/df.POWER_ON_HOURS_N_MAX)<br>df = df.withColumn(&#39;POWER_ON_HOURS_N_VARN&#39;, df.POWER_ON_HOURS_N_MEAN/df.POWER_ON_HOURS_N_MIN)<br>df = df.withColumn(&#39;POWER_ON_HOURS_N_DELTAX&#39;, df.POWER_ON_HOURS_N/df.POWER_ON_HOURS_N_MAX)<br>df = df.withColumn(&#39;POWER_ON_HOURS_N_DELTAN&#39;, df.POWER_ON_HOURS_N/df.POWER_ON_HOURS_N_MIN)</pre><pre>df = df.withColumn(&#39;REALLOCATED_SECTOR_COUNT_R_MAX&#39;, greatest(&#39;REALLOCATED_SECTOR_COUNT_R&#39;,&#39;REALLOCATED_SECTOR_COUNT_R_7&#39;,&#39;REALLOCATED_SECTOR_COUNT_R_6&#39;,&#39;REALLOCATED_SECTOR_COUNT_R_5&#39;,\<br>                                                    &#39;REALLOCATED_SECTOR_COUNT_R_4&#39;,&#39;REALLOCATED_SECTOR_COUNT_R_3&#39;,&#39;REALLOCATED_SECTOR_COUNT_R_2&#39;,&#39;REALLOCATED_SECTOR_COUNT_R_1&#39;))<br><br>df = df.withColumn(&#39;REALLOCATED_SECTOR_COUNT_R_MIN&#39;, least(&#39;REALLOCATED_SECTOR_COUNT_R&#39;,&#39;REALLOCATED_SECTOR_COUNT_R_7&#39;,&#39;REALLOCATED_SECTOR_COUNT_R_6&#39;,&#39;REALLOCATED_SECTOR_COUNT_R_5&#39;,\<br>                                                    &#39;REALLOCATED_SECTOR_COUNT_R_4&#39;,&#39;REALLOCATED_SECTOR_COUNT_R_3&#39;,&#39;REALLOCATED_SECTOR_COUNT_R_2&#39;,&#39;REALLOCATED_SECTOR_COUNT_R_1&#39;))<br><br>df = df.withColumn(&#39;REALLOCATED_SECTOR_COUNT_R_SUM&#39;, (df.REALLOCATED_SECTOR_COUNT_R+df.REALLOCATED_SECTOR_COUNT_R_7+df.REALLOCATED_SECTOR_COUNT_R_6+df.REALLOCATED_SECTOR_COUNT_R_5+\<br>                                                    df.REALLOCATED_SECTOR_COUNT_R_4+df.REALLOCATED_SECTOR_COUNT_R_3+df.REALLOCATED_SECTOR_COUNT_R_2+df.REALLOCATED_SECTOR_COUNT_R_1))<br><br><br>df = df.withColumn(&#39;REALLOCATED_SECTOR_COUNT_R_MEAN&#39;, df.REALLOCATED_SECTOR_COUNT_R_SUM/8)<br>df = df.withColumn(&#39;REALLOCATED_SECTOR_COUNT_R_VAR&#39;, df.REALLOCATED_SECTOR_COUNT_R_MAX/df.REALLOCATED_SECTOR_COUNT_R_MIN)<br>df = df.withColumn(&#39;REALLOCATED_SECTOR_COUNT_R_DELTA&#39;, df.REALLOCATED_SECTOR_COUNT_R/df.REALLOCATED_SECTOR_COUNT_R_MEAN)<br>df = df.withColumn(&#39;REALLOCATED_SECTOR_COUNT_R_VARX&#39;, df.REALLOCATED_SECTOR_COUNT_R_MEAN/df.REALLOCATED_SECTOR_COUNT_R_MAX)<br>df = df.withColumn(&#39;REALLOCATED_SECTOR_COUNT_R_VARN&#39;, df.REALLOCATED_SECTOR_COUNT_R_MEAN/df.REALLOCATED_SECTOR_COUNT_R_MIN)<br>df = df.withColumn(&#39;REALLOCATED_SECTOR_COUNT_R_DELTAX&#39;, df.REALLOCATED_SECTOR_COUNT_R/df.REALLOCATED_SECTOR_COUNT_R_MAX)<br>df = df.withColumn(&#39;REALLOCATED_SECTOR_COUNT_R_DELTAN&#39;, df.REALLOCATED_SECTOR_COUNT_R/df.REALLOCATED_SECTOR_COUNT_R_MIN)</pre><pre>df = df.withColumn(&#39;REPORTED_UNCORRECTABLE_ERRORS_N_MAX&#39;, greatest(&#39;REPORTED_UNCORRECTABLE_ERRORS_N&#39;,&#39;REPORTED_UNCORRECTABLE_ERRORS_N_7&#39;,&#39;REPORTED_UNCORRECTABLE_ERRORS_N_6&#39;,&#39;REPORTED_UNCORRECTABLE_ERRORS_N_5&#39;,\<br>                                                    &#39;REPORTED_UNCORRECTABLE_ERRORS_N_4&#39;,&#39;REPORTED_UNCORRECTABLE_ERRORS_N_3&#39;,&#39;REPORTED_UNCORRECTABLE_ERRORS_N_2&#39;,&#39;REPORTED_UNCORRECTABLE_ERRORS_N_1&#39;))<br><br>df = df.withColumn(&#39;REPORTED_UNCORRECTABLE_ERRORS_N_MIN&#39;, least(&#39;REPORTED_UNCORRECTABLE_ERRORS_N&#39;,&#39;REPORTED_UNCORRECTABLE_ERRORS_N_7&#39;,&#39;REPORTED_UNCORRECTABLE_ERRORS_N_6&#39;,&#39;REPORTED_UNCORRECTABLE_ERRORS_N_5&#39;,\<br>                                                    &#39;REPORTED_UNCORRECTABLE_ERRORS_N_4&#39;,&#39;REPORTED_UNCORRECTABLE_ERRORS_N_3&#39;,&#39;REPORTED_UNCORRECTABLE_ERRORS_N_2&#39;,&#39;REPORTED_UNCORRECTABLE_ERRORS_N_1&#39;))<br><br>df = df.withColumn(&#39;REPORTED_UNCORRECTABLE_ERRORS_N_SUM&#39;, (df.REPORTED_UNCORRECTABLE_ERRORS_N+df.REPORTED_UNCORRECTABLE_ERRORS_N_7+df.REPORTED_UNCORRECTABLE_ERRORS_N_6+df.REPORTED_UNCORRECTABLE_ERRORS_N_5+\<br>                                                    df.REPORTED_UNCORRECTABLE_ERRORS_N_4+df.REPORTED_UNCORRECTABLE_ERRORS_N_3+df.REPORTED_UNCORRECTABLE_ERRORS_N_2+df.REPORTED_UNCORRECTABLE_ERRORS_N_1))<br><br><br>df = df.withColumn(&#39;REPORTED_UNCORRECTABLE_ERRORS_N_MEAN&#39;, df.REPORTED_UNCORRECTABLE_ERRORS_N_SUM/8)<br>df = df.withColumn(&#39;REPORTED_UNCORRECTABLE_ERRORS_N_VAR&#39;, df.REPORTED_UNCORRECTABLE_ERRORS_N_MAX/df.REPORTED_UNCORRECTABLE_ERRORS_N_MIN)<br>df = df.withColumn(&#39;REPORTED_UNCORRECTABLE_ERRORS_N_DELTA&#39;, df.REPORTED_UNCORRECTABLE_ERRORS_N/df.REPORTED_UNCORRECTABLE_ERRORS_N_MEAN)<br>df = df.withColumn(&#39;REPORTED_UNCORRECTABLE_ERRORS_N_VARX&#39;, df.REPORTED_UNCORRECTABLE_ERRORS_N_MEAN/df.REPORTED_UNCORRECTABLE_ERRORS_N_MAX)<br>df = df.withColumn(&#39;REPORTED_UNCORRECTABLE_ERRORS_N_VARN&#39;, df.REPORTED_UNCORRECTABLE_ERRORS_N_MEAN/df.REPORTED_UNCORRECTABLE_ERRORS_N_MIN)<br>df = df.withColumn(&#39;REPORTED_UNCORRECTABLE_ERRORS_N_DELTAX&#39;, df.REPORTED_UNCORRECTABLE_ERRORS_N/df.REPORTED_UNCORRECTABLE_ERRORS_N_MAX)<br>df = df.withColumn(&#39;REPORTED_UNCORRECTABLE_ERRORS_N_DELTAN&#39;, df.REPORTED_UNCORRECTABLE_ERRORS_N/df.REPORTED_UNCORRECTABLE_ERRORS_N_MIN)</pre><pre>df = df.withColumn(&#39;REALLOCATED_SECTOR_COUNT_N_MAX&#39;, greatest(&#39;REALLOCATED_SECTOR_COUNT_N&#39;,&#39;REALLOCATED_SECTOR_COUNT_N_7&#39;,&#39;REALLOCATED_SECTOR_COUNT_N_6&#39;,&#39;REALLOCATED_SECTOR_COUNT_N_5&#39;,\<br>                                                    &#39;REALLOCATED_SECTOR_COUNT_N_4&#39;,&#39;REALLOCATED_SECTOR_COUNT_N_3&#39;,&#39;REALLOCATED_SECTOR_COUNT_N_2&#39;,&#39;REALLOCATED_SECTOR_COUNT_N_1&#39;))<br><br>df = df.withColumn(&#39;REALLOCATED_SECTOR_COUNT_N_MIN&#39;, least(&#39;REALLOCATED_SECTOR_COUNT_N&#39;,&#39;REALLOCATED_SECTOR_COUNT_N_7&#39;,&#39;REALLOCATED_SECTOR_COUNT_N_6&#39;,&#39;REALLOCATED_SECTOR_COUNT_N_5&#39;,\<br>                                                    &#39;REALLOCATED_SECTOR_COUNT_N_4&#39;,&#39;REALLOCATED_SECTOR_COUNT_N_3&#39;,&#39;REALLOCATED_SECTOR_COUNT_N_2&#39;,&#39;REALLOCATED_SECTOR_COUNT_N_1&#39;))<br><br>df = df.withColumn(&#39;REALLOCATED_SECTOR_COUNT_N_SUM&#39;, (df.REALLOCATED_SECTOR_COUNT_N+df.REALLOCATED_SECTOR_COUNT_N_7+df.REALLOCATED_SECTOR_COUNT_N_6+df.REALLOCATED_SECTOR_COUNT_N_5+\<br>                                                    df.REALLOCATED_SECTOR_COUNT_N_4+df.REALLOCATED_SECTOR_COUNT_N_3+df.REALLOCATED_SECTOR_COUNT_N_2+df.REALLOCATED_SECTOR_COUNT_N_1))<br><br><br>df = df.withColumn(&#39;REALLOCATED_SECTOR_COUNT_N_MEAN&#39;, df.REALLOCATED_SECTOR_COUNT_N_SUM/8)<br>df = df.withColumn(&#39;REALLOCATED_SECTOR_COUNT_N_VAR&#39;, df.REALLOCATED_SECTOR_COUNT_N_MAX/df.REALLOCATED_SECTOR_COUNT_N_MIN)<br>df = df.withColumn(&#39;REALLOCATED_SECTOR_COUNT_N_DELTA&#39;, df.REALLOCATED_SECTOR_COUNT_N/df.REALLOCATED_SECTOR_COUNT_N_MEAN)<br>df = df.withColumn(&#39;REALLOCATED_SECTOR_COUNT_N_VARX&#39;, df.REALLOCATED_SECTOR_COUNT_N_MEAN/df.REALLOCATED_SECTOR_COUNT_N_MAX)<br>df = df.withColumn(&#39;REALLOCATED_SECTOR_COUNT_N_VARN&#39;, df.REALLOCATED_SECTOR_COUNT_N_MEAN/df.REALLOCATED_SECTOR_COUNT_N_MIN)<br>df = df.withColumn(&#39;REALLOCATED_SECTOR_COUNT_N_DELTAX&#39;, df.REALLOCATED_SECTOR_COUNT_N/df.REALLOCATED_SECTOR_COUNT_N_MAX)<br>df = df.withColumn(&#39;REALLOCATED_SECTOR_COUNT_N_DELTAN&#39;, df.REALLOCATED_SECTOR_COUNT_N/df.REALLOCATED_SECTOR_COUNT_N_MIN)</pre><pre>df = df.withColumn(&#39;REPORTED_UNCORRECTABLE_ERRORS_R_MAX&#39;, greatest(&#39;REPORTED_UNCORRECTABLE_ERRORS_R&#39;,&#39;REPORTED_UNCORRECTABLE_ERRORS_R_7&#39;,&#39;REPORTED_UNCORRECTABLE_ERRORS_R_6&#39;,&#39;REPORTED_UNCORRECTABLE_ERRORS_R_5&#39;,\<br>                                                    &#39;REPORTED_UNCORRECTABLE_ERRORS_R_4&#39;,&#39;REPORTED_UNCORRECTABLE_ERRORS_R_3&#39;,&#39;REPORTED_UNCORRECTABLE_ERRORS_R_2&#39;,&#39;REPORTED_UNCORRECTABLE_ERRORS_R_1&#39;))<br><br>df = df.withColumn(&#39;REPORTED_UNCORRECTABLE_ERRORS_R_MIN&#39;, least(&#39;REPORTED_UNCORRECTABLE_ERRORS_R&#39;,&#39;REPORTED_UNCORRECTABLE_ERRORS_R_7&#39;,&#39;REPORTED_UNCORRECTABLE_ERRORS_R_6&#39;,&#39;REPORTED_UNCORRECTABLE_ERRORS_R_5&#39;,\<br>                                                    &#39;REPORTED_UNCORRECTABLE_ERRORS_R_4&#39;,&#39;REPORTED_UNCORRECTABLE_ERRORS_R_3&#39;,&#39;REPORTED_UNCORRECTABLE_ERRORS_R_2&#39;,&#39;REPORTED_UNCORRECTABLE_ERRORS_R_1&#39;))<br><br>df = df.withColumn(&#39;REPORTED_UNCORRECTABLE_ERRORS_R_SUM&#39;, (df.REPORTED_UNCORRECTABLE_ERRORS_R+df.REPORTED_UNCORRECTABLE_ERRORS_R_7+df.REPORTED_UNCORRECTABLE_ERRORS_R_6+df.REPORTED_UNCORRECTABLE_ERRORS_R_5+\<br>                                                    df.REPORTED_UNCORRECTABLE_ERRORS_R_4+df.REPORTED_UNCORRECTABLE_ERRORS_R_3+df.REPORTED_UNCORRECTABLE_ERRORS_R_2+df.REPORTED_UNCORRECTABLE_ERRORS_R_1))<br><br><br>df = df.withColumn(&#39;REPORTED_UNCORRECTABLE_ERRORS_R_MEAN&#39;, df.REPORTED_UNCORRECTABLE_ERRORS_R_SUM/8)<br>df = df.withColumn(&#39;REPORTED_UNCORRECTABLE_ERRORS_R_VAR&#39;, df.REPORTED_UNCORRECTABLE_ERRORS_R_MAX/df.REPORTED_UNCORRECTABLE_ERRORS_R_MIN)<br>df = df.withColumn(&#39;REPORTED_UNCORRECTABLE_ERRORS_R_DELTA&#39;, df.REPORTED_UNCORRECTABLE_ERRORS_R/df.REPORTED_UNCORRECTABLE_ERRORS_R_MEAN)<br>df = df.withColumn(&#39;REPORTED_UNCORRECTABLE_ERRORS_R_VARX&#39;, df.REPORTED_UNCORRECTABLE_ERRORS_R_MEAN/df.REPORTED_UNCORRECTABLE_ERRORS_R_MAX)<br>df = df.withColumn(&#39;REPORTED_UNCORRECTABLE_ERRORS_R_VARN&#39;, df.REPORTED_UNCORRECTABLE_ERRORS_R_MEAN/df.REPORTED_UNCORRECTABLE_ERRORS_R_MIN)<br>df = df.withColumn(&#39;REPORTED_UNCORRECTABLE_ERRORS_R_DELTAX&#39;, df.REPORTED_UNCORRECTABLE_ERRORS_R/df.REPORTED_UNCORRECTABLE_ERRORS_R_MAX)<br>df = df.withColumn(&#39;REPORTED_UNCORRECTABLE_ERRORS_R_DELTAN&#39;, df.REPORTED_UNCORRECTABLE_ERRORS_R/df.REPORTED_UNCORRECTABLE_ERRORS_R_MIN)</pre><pre>df = df.withColumn(&#39;COMMAND_TIMEOUT_R_MAX&#39;, greatest(&#39;COMMAND_TIMEOUT_R&#39;,&#39;COMMAND_TIMEOUT_R_7&#39;,&#39;COMMAND_TIMEOUT_R_6&#39;,&#39;COMMAND_TIMEOUT_R_5&#39;,\<br>                                                    &#39;COMMAND_TIMEOUT_R_4&#39;,&#39;COMMAND_TIMEOUT_R_3&#39;,&#39;COMMAND_TIMEOUT_R_2&#39;,&#39;COMMAND_TIMEOUT_R_1&#39;))<br><br>df = df.withColumn(&#39;COMMAND_TIMEOUT_R_MIN&#39;, least(&#39;COMMAND_TIMEOUT_R&#39;,&#39;COMMAND_TIMEOUT_R_7&#39;,&#39;COMMAND_TIMEOUT_R_6&#39;,&#39;COMMAND_TIMEOUT_R_5&#39;,\<br>                                                    &#39;COMMAND_TIMEOUT_R_4&#39;,&#39;COMMAND_TIMEOUT_R_3&#39;,&#39;COMMAND_TIMEOUT_R_2&#39;,&#39;COMMAND_TIMEOUT_R_1&#39;))<br><br>df = df.withColumn(&#39;COMMAND_TIMEOUT_R_SUM&#39;, (df.COMMAND_TIMEOUT_R+df.COMMAND_TIMEOUT_R_7+df.COMMAND_TIMEOUT_R_6+df.COMMAND_TIMEOUT_R_5+\<br>                                                    df.COMMAND_TIMEOUT_R_4+df.COMMAND_TIMEOUT_R_3+df.COMMAND_TIMEOUT_R_2+df.COMMAND_TIMEOUT_R_1))<br><br><br>df = df.withColumn(&#39;COMMAND_TIMEOUT_R_MEAN&#39;, df.COMMAND_TIMEOUT_R_SUM/8)<br>df = df.withColumn(&#39;COMMAND_TIMEOUT_R_VAR&#39;, df.COMMAND_TIMEOUT_R_MAX/df.COMMAND_TIMEOUT_R_MIN)<br>df = df.withColumn(&#39;COMMAND_TIMEOUT_R_DELTA&#39;, df.COMMAND_TIMEOUT_R/df.COMMAND_TIMEOUT_R_MEAN)<br>df = df.withColumn(&#39;COMMAND_TIMEOUT_R_VARX&#39;, df.COMMAND_TIMEOUT_R_MEAN/df.COMMAND_TIMEOUT_R_MAX)<br>df = df.withColumn(&#39;COMMAND_TIMEOUT_R_VARN&#39;, df.COMMAND_TIMEOUT_R_MEAN/df.COMMAND_TIMEOUT_R_MIN)<br>df = df.withColumn(&#39;COMMAND_TIMEOUT_R_DELTAX&#39;, df.COMMAND_TIMEOUT_R/df.COMMAND_TIMEOUT_R_MAX)<br>df = df.withColumn(&#39;COMMAND_TIMEOUT_R_DELTAN&#39;, df.COMMAND_TIMEOUT_R/df.COMMAND_TIMEOUT_R_MIN)</pre><pre>df = df.withColumn(&#39;COMMAND_TIMEOUT_N_MAX&#39;, greatest(&#39;COMMAND_TIMEOUT_N&#39;,&#39;COMMAND_TIMEOUT_N_7&#39;,&#39;COMMAND_TIMEOUT_N_6&#39;,&#39;COMMAND_TIMEOUT_N_5&#39;,\<br>                                                    &#39;COMMAND_TIMEOUT_N_4&#39;,&#39;COMMAND_TIMEOUT_N_3&#39;,&#39;COMMAND_TIMEOUT_N_2&#39;,&#39;COMMAND_TIMEOUT_N_1&#39;))<br><br>df = df.withColumn(&#39;COMMAND_TIMEOUT_N_MIN&#39;, least(&#39;COMMAND_TIMEOUT_N&#39;,&#39;COMMAND_TIMEOUT_N_7&#39;,&#39;COMMAND_TIMEOUT_N_6&#39;,&#39;COMMAND_TIMEOUT_N_5&#39;,\<br>                                                    &#39;COMMAND_TIMEOUT_N_4&#39;,&#39;COMMAND_TIMEOUT_N_3&#39;,&#39;COMMAND_TIMEOUT_N_2&#39;,&#39;COMMAND_TIMEOUT_N_1&#39;))<br><br>df = df.withColumn(&#39;COMMAND_TIMEOUT_N_SUM&#39;, (df.COMMAND_TIMEOUT_N+df.COMMAND_TIMEOUT_N_7+df.COMMAND_TIMEOUT_N_6+df.COMMAND_TIMEOUT_N_5+\<br>                                                    df.COMMAND_TIMEOUT_N_4+df.COMMAND_TIMEOUT_N_3+df.COMMAND_TIMEOUT_N_2+df.COMMAND_TIMEOUT_N_1))<br><br><br>df = df.withColumn(&#39;COMMAND_TIMEOUT_N_MEAN&#39;, df.COMMAND_TIMEOUT_N_SUM/8)<br>df = df.withColumn(&#39;COMMAND_TIMEOUT_N_VAR&#39;, df.COMMAND_TIMEOUT_N_MAX/df.COMMAND_TIMEOUT_N_MIN)<br>df = df.withColumn(&#39;COMMAND_TIMEOUT_N_DELTA&#39;, df.COMMAND_TIMEOUT_N/df.COMMAND_TIMEOUT_N_MEAN)<br>df = df.withColumn(&#39;COMMAND_TIMEOUT_N_VARX&#39;, df.COMMAND_TIMEOUT_N_MEAN/df.COMMAND_TIMEOUT_N_MAX)<br>df = df.withColumn(&#39;COMMAND_TIMEOUT_N_VARN&#39;, df.COMMAND_TIMEOUT_N_MEAN/df.COMMAND_TIMEOUT_N_MIN)<br>df = df.withColumn(&#39;COMMAND_TIMEOUT_N_DELTAX&#39;, df.COMMAND_TIMEOUT_N/df.COMMAND_TIMEOUT_N_MAX)<br>df = df.withColumn(&#39;COMMAND_TIMEOUT_N_DELTAN&#39;, df.COMMAND_TIMEOUT_N/df.COMMAND_TIMEOUT_N_MIN)</pre><pre>df = df.withColumn(&#39;CURRENT_PENDING_SECTOR_COUNT_R_MAX&#39;, greatest(&#39;CURRENT_PENDING_SECTOR_COUNT_R&#39;,&#39;CURRENT_PENDING_SECTOR_COUNT_R_7&#39;,&#39;CURRENT_PENDING_SECTOR_COUNT_R_6&#39;,&#39;CURRENT_PENDING_SECTOR_COUNT_R_5&#39;,\<br>                                                    &#39;CURRENT_PENDING_SECTOR_COUNT_R_4&#39;,&#39;CURRENT_PENDING_SECTOR_COUNT_R_3&#39;,&#39;CURRENT_PENDING_SECTOR_COUNT_R_2&#39;,&#39;CURRENT_PENDING_SECTOR_COUNT_R_1&#39;))<br><br>df = df.withColumn(&#39;CURRENT_PENDING_SECTOR_COUNT_R_MIN&#39;, least(&#39;CURRENT_PENDING_SECTOR_COUNT_R&#39;,&#39;CURRENT_PENDING_SECTOR_COUNT_R_7&#39;,&#39;CURRENT_PENDING_SECTOR_COUNT_R_6&#39;,&#39;CURRENT_PENDING_SECTOR_COUNT_R_5&#39;,\<br>                                                    &#39;CURRENT_PENDING_SECTOR_COUNT_R_4&#39;,&#39;CURRENT_PENDING_SECTOR_COUNT_R_3&#39;,&#39;CURRENT_PENDING_SECTOR_COUNT_R_2&#39;,&#39;CURRENT_PENDING_SECTOR_COUNT_R_1&#39;))<br><br>df = df.withColumn(&#39;CURRENT_PENDING_SECTOR_COUNT_R_SUM&#39;, (df.CURRENT_PENDING_SECTOR_COUNT_R+df.CURRENT_PENDING_SECTOR_COUNT_R_7+df.CURRENT_PENDING_SECTOR_COUNT_R_6+df.CURRENT_PENDING_SECTOR_COUNT_R_5+\<br>                                                    df.CURRENT_PENDING_SECTOR_COUNT_R_4+df.CURRENT_PENDING_SECTOR_COUNT_R_3+df.CURRENT_PENDING_SECTOR_COUNT_R_2+df.CURRENT_PENDING_SECTOR_COUNT_R_1))<br><br><br>df = df.withColumn(&#39;CURRENT_PENDING_SECTOR_COUNT_R_MEAN&#39;, df.CURRENT_PENDING_SECTOR_COUNT_R_SUM/8)<br>df = df.withColumn(&#39;CURRENT_PENDING_SECTOR_COUNT_R_VAR&#39;, df.CURRENT_PENDING_SECTOR_COUNT_R_MAX/df.CURRENT_PENDING_SECTOR_COUNT_R_MIN)<br>df = df.withColumn(&#39;CURRENT_PENDING_SECTOR_COUNT_R_DELTA&#39;, df.CURRENT_PENDING_SECTOR_COUNT_R/df.CURRENT_PENDING_SECTOR_COUNT_R_MEAN)<br>df = df.withColumn(&#39;CURRENT_PENDING_SECTOR_COUNT_R_VARX&#39;, df.CURRENT_PENDING_SECTOR_COUNT_R_MEAN/df.CURRENT_PENDING_SECTOR_COUNT_R_MAX)<br>df = df.withColumn(&#39;CURRENT_PENDING_SECTOR_COUNT_R_VARN&#39;, df.CURRENT_PENDING_SECTOR_COUNT_R_MEAN/df.CURRENT_PENDING_SECTOR_COUNT_R_MIN)<br>df = df.withColumn(&#39;CURRENT_PENDING_SECTOR_COUNT_R_DELTAX&#39;, df.CURRENT_PENDING_SECTOR_COUNT_R/df.CURRENT_PENDING_SECTOR_COUNT_R_MAX)<br>df = df.withColumn(&#39;CURRENT_PENDING_SECTOR_COUNT_R_DELTAN&#39;, df.CURRENT_PENDING_SECTOR_COUNT_R/df.CURRENT_PENDING_SECTOR_COUNT_R_MIN)</pre><pre>df = df.withColumn(&#39;CURRENT_PENDING_SECTOR_COUNT_N_MAX&#39;, greatest(&#39;CURRENT_PENDING_SECTOR_COUNT_N&#39;,&#39;CURRENT_PENDING_SECTOR_COUNT_N_7&#39;,&#39;CURRENT_PENDING_SECTOR_COUNT_N_6&#39;,&#39;CURRENT_PENDING_SECTOR_COUNT_N_5&#39;,\<br>                                                    &#39;CURRENT_PENDING_SECTOR_COUNT_N_4&#39;,&#39;CURRENT_PENDING_SECTOR_COUNT_N_3&#39;,&#39;CURRENT_PENDING_SECTOR_COUNT_N_2&#39;,&#39;CURRENT_PENDING_SECTOR_COUNT_N_1&#39;))<br><br>df = df.withColumn(&#39;CURRENT_PENDING_SECTOR_COUNT_N_MIN&#39;, least(&#39;CURRENT_PENDING_SECTOR_COUNT_N&#39;,&#39;CURRENT_PENDING_SECTOR_COUNT_N_7&#39;,&#39;CURRENT_PENDING_SECTOR_COUNT_N_6&#39;,&#39;CURRENT_PENDING_SECTOR_COUNT_N_5&#39;,\<br>                                                    &#39;CURRENT_PENDING_SECTOR_COUNT_N_4&#39;,&#39;CURRENT_PENDING_SECTOR_COUNT_N_3&#39;,&#39;CURRENT_PENDING_SECTOR_COUNT_N_2&#39;,&#39;CURRENT_PENDING_SECTOR_COUNT_N_1&#39;))<br><br>df = df.withColumn(&#39;CURRENT_PENDING_SECTOR_COUNT_N_SUM&#39;, (df.CURRENT_PENDING_SECTOR_COUNT_N+df.CURRENT_PENDING_SECTOR_COUNT_N_7+df.CURRENT_PENDING_SECTOR_COUNT_N_6+df.CURRENT_PENDING_SECTOR_COUNT_N_5+\<br>                                                    df.CURRENT_PENDING_SECTOR_COUNT_N_4+df.CURRENT_PENDING_SECTOR_COUNT_N_3+df.CURRENT_PENDING_SECTOR_COUNT_N_2+df.CURRENT_PENDING_SECTOR_COUNT_N_1))<br><br><br>df = df.withColumn(&#39;CURRENT_PENDING_SECTOR_COUNT_N_MEAN&#39;, df.CURRENT_PENDING_SECTOR_COUNT_N_SUM/8)<br>df = df.withColumn(&#39;CURRENT_PENDING_SECTOR_COUNT_N_VAR&#39;, df.CURRENT_PENDING_SECTOR_COUNT_N_MAX/df.CURRENT_PENDING_SECTOR_COUNT_N_MIN)<br>df = df.withColumn(&#39;CURRENT_PENDING_SECTOR_COUNT_N_DELTA&#39;, df.CURRENT_PENDING_SECTOR_COUNT_N/df.CURRENT_PENDING_SECTOR_COUNT_N_MEAN)<br>df = df.withColumn(&#39;CURRENT_PENDING_SECTOR_COUNT_N_VARX&#39;, df.CURRENT_PENDING_SECTOR_COUNT_N_MEAN/df.CURRENT_PENDING_SECTOR_COUNT_N_MAX)<br>df = df.withColumn(&#39;CURRENT_PENDING_SECTOR_COUNT_N_VARN&#39;, df.CURRENT_PENDING_SECTOR_COUNT_N_MEAN/df.CURRENT_PENDING_SECTOR_COUNT_N_MIN)<br>df = df.withColumn(&#39;CURRENT_PENDING_SECTOR_COUNT_N_DELTAX&#39;, df.CURRENT_PENDING_SECTOR_COUNT_N/df.CURRENT_PENDING_SECTOR_COUNT_N_MAX)<br>df = df.withColumn(&#39;CURRENT_PENDING_SECTOR_COUNT_N_DELTAN&#39;, df.CURRENT_PENDING_SECTOR_COUNT_N/df.CURRENT_PENDING_SECTOR_COUNT_N_MIN)Fill missing values wtih -9</pre><p>Sort the Data.</p><pre>df=df.sort(&quot;SERIAL_NUMBER&quot;,&quot;DATE&quot;)</pre><h3>5.0 Append mean encoded data variables</h3><pre>z=&#39;model.csv&#39;<br>input_data = spark.read\<br>    .format(&#39;org.apache.spark.sql.execution.datasources.csv.CSVFileFormat&#39;)\<br>    .option(&#39;header&#39;, &#39;true&#39;)\<br>    .load(cos.url(https://medium.com/z,%20&#39;backblazedata-donotdelete-pr-cij57grgkoctem&#39;))#read the file from object storage<br>input_data = input_data.select(&quot;MODEL&quot;,&quot;MODEL_FAIL_RATE&quot;,&quot;MODEL_FAIL_CNT&quot;,&quot;MODEL_FAIL_TOTAL&quot;,&quot;GLOBAL_AVG_FAILURE&quot;) #select the relevant fields<br>df_model = reduce(DataFrame,[input_data])#append the current file to the running data frame <br><br>df_model=df_model[[&#39;MODEL&#39;,&#39;MODEL_FAIL_RATE&#39;,&#39;MODEL_FAIL_CNT&#39;,&#39;MODEL_FAIL_TOTAL&#39;]]</pre><pre>#df_model = spark.createDataFrame(df_model)<br>df_model=df_model.withColumnRenamed(&quot;MODEL&quot;,&quot;MODELM&quot;)<br><br>df=df.join(df_model,(((df.MODEL) ==  (df_model.MODELM)) ),&quot;left&quot;)<br>df = df.drop(&quot;MODELM&quot;)</pre><pre>z=&#39;manufacturer.csv&#39;<br>input_data = spark.read\<br>    .format(&#39;org.apache.spark.sql.execution.datasources.csv.CSVFileFormat&#39;)\<br>    .option(&#39;header&#39;, &#39;true&#39;)\<br>    .load(cos.url(https://medium.com/z,%20&#39;backblazedata-donotdelete-pr-cij57grgkoctem&#39;))#read the file from object storage<br>input_data = input_data.select(&quot;MANUFACTURER&quot;,&quot;MANU_FAIL_RATE&quot;,&quot;MANU_FAIL_CNT&quot;,&quot;MANU_FAIL_TOTAL&quot;,&quot;GLOBAL_AVG_FAILURE&quot;) #select the relevant fields<br>df_manu = reduce(DataFrame,[input_data])#append the current file to the running data frame <br><br>df_manu=df_manu[[&#39;MANUFACTURER&#39;,&#39;MANU_FAIL_RATE&#39;,&#39;MANU_FAIL_CNT&#39;,&#39;MANU_FAIL_TOTAL&#39;]]<br><br>#df_model = spark.createDataFrame(df_model)<br>df_manu=df_manu.withColumnRenamed(&quot;MANUFACTURER&quot;,&quot;MANUFACTURERM&quot;)<br><br>df=df.join(df_manu,(((df.MANUFACTURER) ==  (df_manu.MANUFACTURERM)) ),&quot;left&quot;)<br>df = df.drop(&quot;MANUFACTURERM&quot;)</pre><pre>z=&#39;df_avg_by_model.csv&#39;<br>input_data = spark.read\<br>    .format(&#39;org.apache.spark.sql.execution.datasources.csv.CSVFileFormat&#39;)\<br>    .option(&#39;header&#39;, &#39;true&#39;)\<br>    .load(cos.url(https://medium.com/z,%20&#39;backblazedata-donotdelete-pr-cij57grgkoctem&#39;))#read the file from object storage<br>input_data = input_data.select(&quot;MODEL&quot;,&quot;REALLOCATED_SECTOR_COUNT_N_MOD&quot;,&quot;REPORTED_UNCORRECTABLE_ERRORS_N_MOD&quot;,&quot;COMMAND_TIMEOUT_N_MOD&quot;,<br>                               &quot;CURRENT_PENDING_SECTOR_COUNT_N_MOD&quot;,&quot;POWER_ON_HOURS_N_MOD&quot;,&quot;REALLOCATED_SECTOR_COUNT_R_MOD&quot;,<br>                               &quot;REPORTED_UNCORRECTABLE_ERRORS_R_MOD&quot;,&quot;COMMAND_TIMEOUT_R_MOD&quot;,&quot;CURRENT_PENDING_SECTOR_COUNT_R_MOD&quot;,<br>                               &quot;POWER_ON_HOURS_R_MOD&quot;) #select the relevant fields<br>df_model = reduce(DataFrame,[input_data])#append the current file to the running data frame <br><br>df_model=df_model<br>#df_model = spark.createDataFrame(df_model)<br>df_model=df_model.withColumnRenamed(&quot;MODEL&quot;,&quot;MODELM&quot;)<br><br>df=df.join(df_model,(((df.MODEL) ==  (df_model.MODELM)) ),&quot;left&quot;)<br>df = df.drop(&quot;MODELM&quot;)</pre><pre>z=&#39;df_avg_by_manu.csv&#39;<br>input_data = spark.read\<br>    .format(&#39;org.apache.spark.sql.execution.datasources.csv.CSVFileFormat&#39;)\<br>    .option(&#39;header&#39;, &#39;true&#39;)\<br>    .load(cos.url(https://medium.com/z,%20&#39;backblazedata-donotdelete-pr-cij57grgkoctem&#39;))#read the file from object storage<br>input_data = input_data.select(&quot;MANUFACTURER&quot;,&quot;REALLOCATED_SECTOR_COUNT_N_MAN&quot;,&quot;REPORTED_UNCORRECTABLE_ERRORS_N_MAN&quot;,<br>                               &quot;COMMAND_TIMEOUT_N_MAN&quot;,&quot;CURRENT_PENDING_SECTOR_COUNT_N_MAN&quot;,&quot;POWER_ON_HOURS_N_MAN&quot;,<br>                               &quot;REALLOCATED_SECTOR_COUNT_R_MAN&quot;,&quot;REPORTED_UNCORRECTABLE_ERRORS_R_MAN&quot;,&quot;COMMAND_TIMEOUT_R_MAN&quot;,<br>                               &quot;CURRENT_PENDING_SECTOR_COUNT_R_MAN&quot;,&quot;POWER_ON_HOURS_R_MAN&quot;) #select the relevant fields<br>df_manu = reduce(DataFrame,[input_data])#append the current file to the running data frame <br><br>df_manu=df_manu<br><br>#df_model = spark.createDataFrame(df_model)<br>df_manu=df_manu.withColumnRenamed(&quot;MANUFACTURER&quot;,&quot;MANUFACTURERM&quot;)<br><br>df=df.join(df_manu,(((df.MANUFACTURER) ==  (df_manu.MANUFACTURERM)) ),&quot;left&quot;)<br>df = df.drop(&quot;MANUFACTURERM&quot;)</pre><p>Fill in Null values with -99</p><pre>df=df.na.fill(value=-99)</pre><h3>6.0 Create even more features</h3><pre><br>df = df.withColumn(&#39;REALLOCATED_SECTOR_COUNT_N_MOD_IDX&#39;, df.REALLOCATED_SECTOR_COUNT_N/df.REALLOCATED_SECTOR_COUNT_N_MOD)<br><br>df = df.withColumn(&#39;REPORTED_UNCORRECTABLE_ERRORS_N_MOD_IDX&#39;, df.REPORTED_UNCORRECTABLE_ERRORS_N/df.REPORTED_UNCORRECTABLE_ERRORS_N_MOD)<br>df = df.withColumn(&#39;COMMAND_TIMEOUT_N_MOD_MOD_IDX&#39;, df.COMMAND_TIMEOUT_N/df.COMMAND_TIMEOUT_N_MOD)<br><br>df = df.withColumn(&#39;CURRENT_PENDING_SECTOR_COUNT_N_MOD_IDX&#39;, df.CURRENT_PENDING_SECTOR_COUNT_N/df.CURRENT_PENDING_SECTOR_COUNT_N_MOD)<br><br>df = df.withColumn(&#39;POWER_ON_HOURS_N_MOD_IDX&#39;, df.POWER_ON_HOURS_N/df.POWER_ON_HOURS_N_MOD)<br>df = df.withColumn(&#39;REALLOCATED_SECTOR_COUNT_R_MOD_IDX&#39;, df.REALLOCATED_SECTOR_COUNT_R/df.REALLOCATED_SECTOR_COUNT_R_MOD)<br>df = df.withColumn(&#39;REPORTED_UNCORRECTABLE_ERRORS_R_MOD_IDX&#39;, df.REPORTED_UNCORRECTABLE_ERRORS_R/df.REPORTED_UNCORRECTABLE_ERRORS_R_MOD)<br><br>df = df.withColumn(&#39;COMMAND_TIMEOUT_R_MOD_IDX&#39;, df.COMMAND_TIMEOUT_R/df.COMMAND_TIMEOUT_R_MOD)<br>df = df.withColumn(&#39;CURRENT_PENDING_SECTOR_COUNT_R_MOD_IDX&#39;, df.CURRENT_PENDING_SECTOR_COUNT_R/df.CURRENT_PENDING_SECTOR_COUNT_R_MOD)<br><br>df = df.withColumn(&#39;POWER_ON_HOURS_R_MOD_IDX&#39;, df.POWER_ON_HOURS_R/df.POWER_ON_HOURS_R_MOD)</pre><pre>df = df.withColumn(&#39;REALLOCATED_SECTOR_COUNT_N_MAN_IDX&#39;, df.REALLOCATED_SECTOR_COUNT_N/df.REALLOCATED_SECTOR_COUNT_N_MAN)<br><br>df = df.withColumn(&#39;REPORTED_UNCORRECTABLE_ERRORS_N_MAN_IDX&#39;, df.REPORTED_UNCORRECTABLE_ERRORS_N/df.REPORTED_UNCORRECTABLE_ERRORS_N_MAN)<br>df = df.withColumn(&#39;COMMAND_TIMEOUT_N_MAN_IDX&#39;, df.COMMAND_TIMEOUT_N/df.COMMAND_TIMEOUT_N_MAN)<br><br>df = df.withColumn(&#39;CURRENT_PENDING_SECTOR_COUNT_N_MAN_IDX&#39;, df.CURRENT_PENDING_SECTOR_COUNT_N/df.CURRENT_PENDING_SECTOR_COUNT_N_MAN)<br><br>df = df.withColumn(&#39;POWER_ON_HOURS_N_MAN_IDX&#39;, df.POWER_ON_HOURS_N/df.POWER_ON_HOURS_N_MAN)<br>df = df.withColumn(&#39;REALLOCATED_SECTOR_COUNT_R_MAN_IDX&#39;, df.REALLOCATED_SECTOR_COUNT_R/df.REALLOCATED_SECTOR_COUNT_R_MAN)<br>df = df.withColumn(&#39;REPORTED_UNCORRECTABLE_ERRORS_R_MAN_IDX&#39;, df.REPORTED_UNCORRECTABLE_ERRORS_R/df.REPORTED_UNCORRECTABLE_ERRORS_R_MAN)<br><br>df = df.withColumn(&#39;COMMAND_TIMEOUT_R_MAN_IDX&#39;, df.COMMAND_TIMEOUT_R/df.COMMAND_TIMEOUT_R_MAN)<br>df = df.withColumn(&#39;CURRENT_PENDING_SECTOR_COUNT_R_MAN_IDX&#39;, df.CURRENT_PENDING_SECTOR_COUNT_R/df.CURRENT_PENDING_SECTOR_COUNT_R_MAN)<br><br>df = df.withColumn(&#39;POWER_ON_HOURS_R_MAN_IDX&#39;, df.POWER_ON_HOURS_R/df.POWER_ON_HOURS_R_MAN)</pre><h3>7.0 Export to Parquet file for step 5</h3><pre>import ibmos2spark, os<br># @hidden_cell<br><br>if os.environ.get(&#39;RUNTIME_ENV_LOCATION_TYPE&#39;) == &#39;external&#39;:<br>    endpoint_ae0ee98cbce04bcbb3163be1d0955096 = &#39;https://s3-api.us-geo.objectstorage.softlayer.net&#39;<br>else:<br>    endpoint_ae0ee98cbce04bcbb3163be1d0955096 = &#39;https://s3-api.us-geo.objectstorage.service.networklayer.com&#39;<br><br>credentials = {<br>    &#39;endpoint&#39;: XXXXX,<br>    &#39;service_id&#39;: &#39;XXXXX&#39;,<br>    &#39;iam_service_endpoint&#39;: &#39;XXXXX&#39;,<br>    &#39;api_key&#39;: &#39;XXXXX&#39;<br>}<br><br>configuration_name = &#39;XXXXX&#39;<br>cos = ibmos2spark.CloudObjectStorage(sc, credentials, configuration_name, &#39;bluemix_cos&#39;)</pre><pre>df.write.mode(&quot;overwrite&quot;).parquet(cos.url(https://medium.com/&#39;data_2020_model.parquet&#39;,%20&#39;bucketname&#39;))</pre><p>All data used in this notebook is the property of Backblaze.</p><p>For questions regarding use of data please see the following website.</p><ul><li><a href="https://www.backblaze.com/b2/hard-drive-test-data.html">Backblaze Hard Drive Stats</a></li><li><a href="https://www.kaggle.com/datasets/backblaze/hard-drive-test-data">Hard Drive Test Data</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c0f51429908" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/a-complete-solution-to-the-backbaze-com-kaggle-problem-7c0f51429908">A Complete Solution to the BackBaze.com Kaggle Problem</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Complete Solution to the BackBaze.com Kaggle Problem]]></title>
            <link>https://medium.com/geekculture/a-complete-solution-to-the-backbaze-com-kaggle-problem-cd51259787b7?source=rss-b2cb0fe3df91------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd51259787b7</guid>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[equipment-failure]]></category>
            <category><![CDATA[kaggle]]></category>
            <category><![CDATA[predictive-maintenance]]></category>
            <category><![CDATA[feature-engineering]]></category>
            <dc:creator><![CDATA[Shad Griffin]]></dc:creator>
            <pubDate>Wed, 28 Dec 2022 01:33:11 GMT</pubDate>
            <atom:updated>2026-06-03T17:27:33.977Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Complete Solution to the Backblaze Machine Failure Kaggle Problem, III</h3><h3>Step Three, Shaping and cleaning the data</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s4fwIhjYir1hfWb3pJNvSA.jpeg" /></figure><p><a href="https://github.com/shadgriffin/backblazedata/blob/master/Backblaze.com%20--%20Step%20Three%20--%20Shape%20and%20Clean.ipynb">backblazedata/Backblaze.com -- Step Three -- Shape and Clean.ipynb at master · shadgriffin/backblazedata</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FGJewNI72VTE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DGJewNI72VTE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FGJewNI72VTE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce6fcde0251c03f1e41e42e1eefd4955/href">https://medium.com/media/ce6fcde0251c03f1e41e42e1eefd4955/href</a></iframe><ul><li><a href="https://jshadgriffin.medium.com/a-complete-solution-to-the-backbaze-com-kaggle-problem-9d5cb45a88db">A Complete Solution to the BackBaze.com Kaggle Problem</a></li><li><a href="https://jshadgriffin.medium.com/a-complete-solution-to-the-backbaze-com-kaggle-problem-3a9558cd8929">A Complete Solution to the BackBaze.com Kaggle Problem</a></li><li><a href="https://jshadgriffin.medium.com/a-complete-solution-to-the-backbaze-com-kaggle-problem-7c0f51429908">A Complete Solution to the BackBaze.com Kaggle Problem</a></li><li><a href="https://jshadgriffin.medium.com/a-complete-solution-to-the-backbaze-com-kaggle-problem-1f53235bdb4e">A Complete Solution to the BackBaze.com Kaggle Problem</a></li><li><a href="https://jshadgriffin.medium.com/a-complete-solution-to-the-backbaze-com-kaggle-problem-cf1fab1af529">A Complete Solution to the BackBaze.com Kaggle Problem</a></li></ul><h3>1.0 Introduction</h3><p>Note this is part three of a six-part solution.</p><p>Backblaze, you are the “GOAT.” You are the “cat’s meow.” You “Rock the House.” In case you don’t know why Backblaze is so totally “kick-ass,” they open-sourced a vast set of hard drive information a few years ago and continue updating it each quarter. What a treasure trove of superb data. Backblaze, thank you from the bottom of my heart.</p><p>The Backblaze data includes operational metrics from hard drives with an indicator of a hard-drive failure. It is an excellent source for teaching techniques related to machine failure. Again, thank you for making this available to the open-source community. Here is a link to the data.</p><p><a href="https://www.backblaze.com/b2/hard-drive-test-data.html">Backblaze Hard Drive Stats</a></p><p>My goal in this series of articles is not to give the best solution with the highest AUC. My goal is to show you how to approach equipment failure problems and build solutions that reflect realistic accuracy, and provide an easy transition from the lab to the real world.</p><p>I will use a Spark/Python Jupyter notebook inside IBM’s Watson Studio on the cloud as a tool in this discussion.</p><p><a href="https://www.ibm.com/cloud/watson-studio">IBM Watson Studio - Overview</a></p><p>I will also be using cloud object storage on the IBM cloud.</p><p><a href="https://cloud.ibm.com/docs/cloud-object-storage">https://cloud.ibm.com/docs/cloud-object-storage</a></p><p>The third article in this series is not very exciting but is critical. I will be shaping and scoping the data set I created in the first article, so it is ready for machine learning.</p><p>Rarely is it a good idea to take the data as it comes. It is almost always a good idea to shape your data to be consistent with the problem that needs solving. The Backblaze data is no different. In this notebook, we will take the raw data and shape it to pass it to a machine-learning model.</p><p>In the first article of this series, we read the raw data from 2018,2019, and 2020. Data from 2017, 2018, and 2019 are for creating features. The 2020 data is for modeling. Therefore, our shaping exercise is limited to 2020 data.</p><p>I created these notebooks with a runtime useing 1 driver with 1 vCPU and 4 GB RAM, and 2 executors each with 1 vCPU and 4 GB RAM. This is available for free on the IBM Cloud. Some of the notebooks take a few hours to run. You’ll need to schedule your notebooks to run as jobs.</p><p><a href="https://dataplatform.cloud.ibm.com/docs/content/wsj/analyze-data/schedule-task.html">https://dataplatform.cloud.ibm.com/docs/content/wsj/analyze-data/schedule-task.html</a></p><p>I recommend working through this article if you have not previously done so. It will provide further details on the techniques used to understand the data from Backblaze.</p><p><a href="https://medium.com/swlh/machine-learning-for-equipment-failure-prediction-and-predictive-maintenance-pm-e72b1ce42da1">Machine Learning for Equipment Failure Prediction and Predictive Maintenance (PM)</a></p><h3>2.0 Establish environment and Parameters</h3><p>Import the Relevant Libraries and connect to object storage.</p><pre>#Import relevant Libraries<br>from functools import reduce<br>from pyspark.sql import DataFrame<br><br>import pyspark.sql.functions as F<br><br>from pyspark.sql.functions import when</pre><pre>#Define cloud object storages parameters<br>import ibmos2spark, os<br># @hidden_cell<br><br>if os.environ.get(&#39;RUNTIME_ENV_LOCATION_TYPE&#39;) == &#39;external&#39;:<br>    endpoint_ae0ee98cbce04bcbb3163be1d0955096 = &#39;https://s3-api.us-geo.objectstorage.softlayer.net&#39;<br>else:<br>    endpoint_ae0ee98cbce04bcbb3163be1d0955096 = &#39;https://s3-api.us-geo.objectstorage.service.networklayer.com&#39;<br><br>credentials = {<br>    &#39;endpoint&#39;: XXXXX,<br>    &#39;service_id&#39;: &#39;XXXXX&#39;,<br>    &#39;iam_service_endpoint&#39;: &#39;XXXXX&#39;,<br>    &#39;api_key&#39;: &#39;XXXXX&#39;<br>}<br><br>configuration_name = &#39;XXXXX&#39;<br>cos = ibmos2spark.CloudObjectStorage(sc, credentials, configuration_name, &#39;bluemix_cos&#39;)</pre><h3>3.0 Data Shaping and Cleaning</h3><h4>3.1 Read in Data</h4><p>Read in the data we created in the first notebook.</p><pre>df_2020 = spark.read.parquet(cos.url(https://medium.com/&#39;data2020.parquet&#39;,%20&#39;backblazedata-donotdelete-pr-cij57grgkoctem&#39;)).cache()</pre><p>Note at the begining of the exercise we have 52,286,398 records.</p><p>Check for duplicate records. There are none.</p><pre>#df_2020=df_2020.distinct()<br>#df_2020.count()</pre><h4>3.2 Remove disks installed after to January 1st 2020</h4><p>When we deploy this model, we will do so on the existing set of disks at the current time. I want the model to reflect that as well. In other words, when we deploy this model, we will not predict disks installed in the future. We will only know about the disks currently in the data center. To approximate model deployment, it is essential to pick a point in time and only include the disk operating at that time. In this case, our point in time is 1/1/2020.</p><p>We are defining our modeling data set to include all disk drives installed and operating on January 1, 2020.</p><p>Create a list of disk drives operating on 1/1/2020</p><pre>#Copy the data set so we can aggregate and transform it<br>df_start=df_2020<br>#Keep Serial number and date.<br>df_start=df_start.select([c for c in df_start.columns if c in [&#39;SERIAL_NUMBER&#39;,&#39;DATE&#39;]])<br>#select records that existed on 1/1/2020<br>df_start=df_start.filter(df_start.DATE ==&#39;2020-01-01&#39;)</pre><p>Include the disks operating on 1/1/20 with an inner join on the original data frame. The result is only disks running on 1/1/20.</p><pre>df_start=df_start.select([c for c in df_start.columns if c in [&#39;SERIAL_NUMBER&#39;]])<br>df_start = df_start.withColumnRenamed(&quot;SERIAL_NUMBER&quot;,&quot;DOODEE&quot;)<br><br>df_2020=df_2020.join(df_start,(((df_start.DOODEE) ==  (df_2020.SERIAL_NUMBER))),&quot;inner&quot;)<br>df_2020 = df_2020.drop(&quot;DOODEE&quot;)</pre><h4>3.3 Remove disks that failed in January 2020 and data existing on disks after the failure date.</h4><p>It is essential to remove the disks that failed at the beginning of 2020.</p><p>Why?</p><p>Because these disks were on death’s door before we even started, some, if not most, of the information that would predict failure for these disks doesn’t exist in the data. This information would be in 2019.</p><p>Also, we need to ensure that a disk does not linger in the data set after it fails. If a disk fails on Monday, you don’t want data for the disk on Tuesday or Wednesday.</p><p>Convert Date to a date field.</p><pre>df_2020=df_2020.withColumnRenamed(&quot;DATE&quot;,&quot;INPUT&quot;)<br><br>from pyspark.sql.functions import *<br><br>df_2020=df_2020.select(to_date(col(&quot;INPUT&quot;),&quot;y-M-dd&quot;).alias(&quot;DATE&quot;), &quot;*&quot;)<br>df_2020 = df_2020.drop(&quot;INPUT&quot;).cache()</pre><p>Create a data set that only includes the disks that failed.</p><pre>#select records with a failure<br>df_get=df_2020.filter(df_2020.FAILURE ==1)<br><br>#create a complete set of drives that failed.<br>df_get=df_get.select([c for c in df_get.columns if c in [&#39;SERIAL_NUMBER&#39;]])<br>df_get=df_get.dropDuplicates([&#39;SERIAL_NUMBER&#39;])<br><br>df_get = df_get.withColumnRenamed(&quot;SERIAL_NUMBER&quot;,&quot;DOODEE&quot;)<br>df_failures=df_2020.join(df_get,(((df_get.DOODEE) ==  (df_2020.SERIAL_NUMBER))),&quot;inner&quot;)<br>df_failures = df_failures.drop(&quot;DOODEE&quot;)</pre><p>Capture the minimum failure date for each disk. There may be situations where the same disk has two or more failure dates. We want to identify the first.</p><pre>df_later=df_2020.filter(df_2020.FAILURE ==1)</pre><pre>from pyspark.sql.functions import col, max as max_, min as min_<br>df=df_later<br>v=(df.groupBy(“SERIAL_NUMBER”)<br> .agg(min(“DATE”)))<br>v = v.withColumnRenamed(“min(DATE)”,”MINDATE”)<br>v = v.withColumnRenamed(“SERIAL_NUMBER”,”DOODEE”)</pre><pre>v=v.filter(v.MINDATE&gt;=’2020–01–30&#39;)</pre><pre>v=v.sort((“MINDATE”))</pre><p>Remove any records that exist after the first failure.</p><pre>df_failures=v.join(df_failures,(((v.DOODEE) ==  (df_failures.SERIAL_NUMBER))),&quot;inner&quot;)<br>df_failures = df_failures.drop(&quot;DOODEE&quot;)<br><br><br>df_failures=df_failures.filter(df_failures.DATE&lt;=df_failures.MINDATE)<br>df_failures = df_failures.drop(&quot;DOODEE&quot;)<br>df_failures = df_failures.drop(&quot;MINDATE&quot;)</pre><p>Create a dataframe that only includes disks that did not fail in 2020.</p><pre>df_bysn = df_2020.groupBy(‘SERIAL_NUMBER’).agg(F.sum(“FAILURE”).alias(‘sum_failure’))<br>df_bysn=df_bysn.filter(df_bysn.sum_failure==0)<br><br>df_bysn=df_bysn.select([c for c in df_bysn.columns if c in [&#39;SERIAL_NUMBER&#39;]])<br>df_bysn=df_bysn.dropDuplicates([&#39;SERIAL_NUMBER&#39;])<br><br>df_bysn = df_bysn.withColumnRenamed(&quot;SERIAL_NUMBER&quot;,&quot;DOODEE&quot;)<br>df_nonfailures=df_2020.join(df_bysn,(((df_bysn.DOODEE) == (df_2020.SERIAL_NUMBER))),&quot;inner&quot;)<br>df_nonfailures = df_nonfailures.drop(&quot;DOODEE&quot;)</pre><p>Append the disks with failures and without failures into a single data frame.</p><pre><br>df_total = reduce(DataFrame.unionAll, [df_failures,df_nonfailures])<br><br>#df_total.count()</pre><p>Now we have 43,844,671 records in the modeling dataframe.</p><h4>3.4 Ensure we are not missing any dates.</h4><p>When working with time series or panel data, we need to ensure that all dates are consecutive. That is, there is no missing time. For example, if you have a time series measured daily for June, you must ensure that June 5th is not missing. There are many ways to do this in pandas; unfortunately, I don’t have an elegant way to do it in SPARK. The following code is not elegant, but it works.</p><p>Create a field called “ROW” the represents the sequential value of each record for each disk.</p><pre>from pyspark.sql.window import Window<br>from pyspark.sql.functions import row_number<br>windowSpec  = Window.partitionBy(&quot;SERIAL_NUMBER&quot;).orderBy(&quot;DATE&quot;)<br><br>dfzz1=df_total.withColumn(&quot;ROW&quot;,row_number().over(windowSpec))<br>dfzz=dfzz1</pre><p>Create a data frame with that adds 1 to the existing row number.</p><pre>#select the relevant fields<br>dfzz=dfzz.select([c for c in dfzz.columns if c in [&#39;SERIAL_NUMBER&#39;, &#39;DATE&#39;,&#39;ROW&#39;]])<br>#sort the data<br>dfzz=dfzz.sort(([&#39;SERIAL_NUMBER&#39;,&#39;ROW&#39;]))<br>#add one to row.<br>df_1x = dfzz.withColumn(&#39;ROW_1&#39;, ( dfzz[&#39;ROW&#39;] + 1 ) )<br>#get rid of ROW<br>df_1x = df_1x.drop(&quot;ROW&quot;)<br>df_1=df_1x</pre><p>Rename the working data frame to become the date in the previous record, then merge it to the original data frame.</p><pre><br>#Rename the variables<br>df_1=df_1.withColumnRenamed(&quot;SERIAL_NUMBER&quot;,&quot;SERIAL_NUMBER_1&quot;)<br>df_1=df_1.withColumnRenamed(&quot;DATE&quot;,&quot;DATE_1&quot;)<br>#merge to the original df<br>dfzz=dfzz.join(df_1,(((dfzz.ROW) ==  (df_1.ROW_1)) &amp; ((dfzz.SERIAL_NUMBER) ==  (df_1.SERIAL_NUMBER_1))),&quot;inner&quot;)<br><br></pre><p>Create a field called “datediff” that is the difference between the current date and the previous date.</p><pre>from pyspark.sql.functions import *<br>dfzz=dfzz.select(<br>      col(&quot;SERIAL_NUMBER&quot;),<br>      col(&quot;DATE&quot;),<br>      col(&quot;DATE_1&quot;),<br>      datediff(col(&quot;DATE&quot;),col(&quot;DATE_1&quot;)).alias(&quot;datediff&quot;))</pre><p>Take the maximum “datediff” for each disk.</p><pre>v=(dfzz.groupBy(“SERIAL_NUMBER”)<br> .agg(max(“datediff”)))<br>v = v.withColumnRenamed(“max(datediff)”,”MAXDATEDIFF”)<br>v = v.withColumnRenamed(“SERIAL_NUMBER”,”DOODEE”)</pre><p>Ensure that the maximum is 1, meaning the largest gap between any two consecutive days is 1. The resulting data set will contain drives with no missing dates.</p><pre>v=v.filter(v.MAXDATEDIFF==1)</pre><p>Join the data frame containing drives with no missing dates to the original data frame with an inner join. This join eliminates disks with missing dates from the original data frame.</p><pre>v=v.select([c for c in v.columns if c in [&#39;DOODEE&#39;]])<br><br>df_total=df_total.join(v,(((df_total.SERIAL_NUMBER) ==  (v.DOODEE))),&quot;inner&quot;)<br>df_total = df_total.drop(&quot;DOODEE&quot;)<br>#df_total.count()</pre><p>Now we have 42,202,057 where all disks are not missing consecutive dates.</p><h3>4.0 Sample the data set to fit environment</h3><p>Unfortunately, money does not grow on trees. I don’t have unlimited resources to run this notebook and build a model. In this section I down-sample the data so that I can run it in my environment.</p><h4>4.1 Understand the underlying proportion of failure to non-failure disks.</h4><p>I will stratify the sample based on if a drive failed or did not fail in 2020. The first step in doing so is to understand the underlying base incident failure rate among the disk drives.</p><pre>df_bysn = df_total.groupBy(&#39;SERIAL_NUMBER&#39;).agg(F.sum(&quot;FAILURE&quot;).alias(&#39;sum_failure&#39;))<br>df_nonfailurelist=df_bysn.filter(df_bysn.sum_failure==0)<br>df_failurelist=df_bysn.filter(df_bysn.sum_failure&gt;0)<br>df_q = df_failurelist.unionByName(df_nonfailurelist)<br>#df_q.groupBy(&quot;sum_failure&quot;).count().show()</pre><p>We have 1084 disk drives that failed and 119,041 that did not fail. That is a failure rate of about .9%. Or, for every disk that failed, about 109 did not fail. Your sample will need to fit your computing environment. For me and my environment, I will select 1000 failures and 1000 non-failures. Again, you will need to scale the sample to what you can actualy run in your computing environment.</p><h4>4.2 Build the sample.</h4><p>First, randomly select 1000 disks with a failure.</p><pre>df_2020=df_total<br>#identify disks with a failure<br>df_failure=df_2020.filter(df_2020.FAILURE ==1)<br>#keep relevant columns<br>df_failure=df_failure.select([c for c in df_failure.columns if c in [&#39;SERIAL_NUMBER&#39;]])<br>#dedup the data <br>df_failure=df_failure.dropDuplicates([&#39;SERIAL_NUMBER&#39;])<br>#assign a random number to each serial number<br>df_failure=df_failure.withColumn(&#39;wookie&#39;, rand())<br>#sort by the random number<br>df_failure=df_failure.sort((&quot;wookie&quot;))<br><br>#keep the first 1000 records<br>df_failure=df_failure.limit(1000)<br><br>#clean up the data<br>df_failure_list = df_failure.withColumnRenamed(&quot;SERIAL_NUMBER&quot;,&quot;DOODEE&quot;)<br>df_failure_list = df_failure_list.drop(&quot;wookie&quot;)<br><br>#conduct an inner join to the original data results set will be all records for the 1000 randomly selected disks<br>df_failure=df_2020.join(df_failure_list,(((df_failure_list.DOODEE) ==  (df_2020.SERIAL_NUMBER))),&quot;inner&quot;)<br>df_failure = df_failure.drop(&quot;DOODEE&quot;)</pre><p>Second, randomly select 1000 disks with a failure.</p><pre>#identify disks that did not fail<br>df_bysn = df_2020.groupBy(&#39;SERIAL_NUMBER&#39;).agg(F.sum(&quot;FAILURE&quot;).alias(&#39;sum_failure&#39;))<br>df_nonfailurelist=df_bysn.filter(df_bysn.sum_failure==0)<br>#keep relevant variables<br>df_nonfailurelist=df_nonfailurelist.select([c for c in df_nonfailurelist.columns if c in [&#39;SERIAL_NUMBER&#39;]])<br>#ensure no duplicates<br>df_nonfailurelist=df_nonfailurelist.dropDuplicates([&#39;SERIAL_NUMBER&#39;])<br>#create a random number for each disk<br>df_nonfailurelist=df_nonfailurelist.withColumn(&#39;wookie&#39;, rand())<br>#sort the disks by the random number<br>df_nonfailurelist=df_nonfailurelist.sort((&quot;wookie&quot;))<br>#keep 1000 randomly selected disks.<br>df_nonfailurelist=df_nonfailurelist.limit(1000)<br><br><br>#clean up the data<br>df_nonfailurelist = df_nonfailurelist.withColumnRenamed(&quot;SERIAL_NUMBER&quot;,&quot;DOODEE&quot;)<br>df_nonfailurelist = df_nonfailurelist.drop(&quot;wookie&quot;)<br>#join to the original data.  The results set will be the all records from the randomly selected disks<br>df_nonfailures=df_2020.join(df_nonfailurelist,(((df_nonfailurelist.DOODEE) ==  (df_2020.SERIAL_NUMBER))),&quot;inner&quot;)<br>df_nonfailures = df_nonfailures.drop(&quot;DOODEE&quot;)</pre><p>Third, concentate the failures and non-failures</p><pre>df_total = df_failure.unionByName(df_nonfailures)</pre><h4>5.0 Write DF to a parque file for for use in step 4.</h4><pre>import ibmos2spark, os<br># @hidden_cell<br><br>if os.environ.get(&#39;RUNTIME_ENV_LOCATION_TYPE&#39;) == &#39;external&#39;:<br>    endpoint_ae0ee98cbce04bcbb3163be1d0955096 = &#39;https://s3-api.us-geo.objectstorage.softlayer.net&#39;<br>else:<br>    endpoint_ae0ee98cbce04bcbb3163be1d0955096 = &#39;https://s3-api.us-geo.objectstorage.service.networklayer.com&#39;<br><br>credentials = {<br>    &#39;endpoint&#39;: XXXXX,<br>    &#39;service_id&#39;: &#39;XXXXX&#39;,<br>    &#39;iam_service_endpoint&#39;: &#39;XXXXX&#39;,<br>    &#39;api_key&#39;: &#39;XXXXX&#39;<br>}<br><br>configuration_name = &#39;XXXXX&#39;<br>cos = ibmos2spark.CloudObjectStorage(sc, credentials, configuration_name, &#39;bluemix_cos&#39;)</pre><pre>df_total.write.mode(“overwrite”).parquet(cos.url(https://medium.com/%E2%80%98data_2020_final.parquet%E2%80%99,%20%E2%80%98backblazedata-donotdelete-pr-cij57grgkoctem%E2%80%99))</pre><p>All data used in this article is the property of Backblaze.</p><p>For questions regarding use of data please see the following website.</p><ul><li><a href="https://www.backblaze.com/b2/hard-drive-test-data.html">Backblaze Hard Drive Stats</a></li><li><a href="https://www.kaggle.com/datasets/backblaze/hard-drive-test-data">Hard Drive Test Data</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd51259787b7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/a-complete-solution-to-the-backbaze-com-kaggle-problem-cd51259787b7">A Complete Solution to the BackBaze.com Kaggle Problem</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Complete Solution to the BackBaze.com Kaggle Problem]]></title>
            <link>https://medium.com/geekculture/a-complete-solution-to-the-backbaze-com-kaggle-problem-1f53235bdb4e?source=rss-b2cb0fe3df91------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f53235bdb4e</guid>
            <category><![CDATA[kaggle]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[equipment-failure]]></category>
            <category><![CDATA[predictive-mainetance]]></category>
            <category><![CDATA[mean-encoding]]></category>
            <dc:creator><![CDATA[Shad Griffin]]></dc:creator>
            <pubDate>Wed, 28 Dec 2022 01:31:42 GMT</pubDate>
            <atom:updated>2026-06-03T17:19:59.068Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Complete Solution to the Backblaze Machine Failure Kaggle Problem, II</h3><h3>Step Two, Creating Mean Encoded Features</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s4fwIhjYir1hfWb3pJNvSA.jpeg" /></figure><p><a href="https://github.com/shadgriffin/backblazedata/blob/master/Backblaze.com%20--%20Step%20Two%20--%20Mean%20Encoded%20Features.ipynb">backblazedata/Backblaze.com -- Step Two -- Mean Encoded Features.ipynb at master · shadgriffin/backblazedata</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FGJewNI72VTE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DGJewNI72VTE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FGJewNI72VTE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce6fcde0251c03f1e41e42e1eefd4955/href">https://medium.com/media/ce6fcde0251c03f1e41e42e1eefd4955/href</a></iframe><ul><li><a href="https://jshadgriffin.medium.com/a-complete-solution-to-the-backbaze-com-kaggle-problem-3a9558cd8929">A Complete Solution to the BackBaze.com Kaggle Problem</a></li><li><a href="https://jshadgriffin.medium.com/a-complete-solution-to-the-backbaze-com-kaggle-problem-9d5cb45a88db">A Complete Solution to the BackBaze.com Kaggle Problem</a></li><li><a href="https://jshadgriffin.medium.com/a-complete-solution-to-the-backbaze-com-kaggle-problem-7c0f51429908">A Complete Solution to the BackBaze.com Kaggle Problem</a></li><li><a href="https://jshadgriffin.medium.com/a-complete-solution-to-the-backbaze-com-kaggle-problem-cd51259787b7">A Complete Solution to the BackBaze.com Kaggle Problem</a></li><li><a href="https://jshadgriffin.medium.com/a-complete-solution-to-the-backbaze-com-kaggle-problem-cf1fab1af529">A Complete Solution to the BackBaze.com Kaggle Problem</a></li></ul><h3>1.0 Introduction</h3><p>Backblaze, you are the “GOAT.” You are the “cat’s meow.” You “Rock the House.” In case you don’t know why Backblaze is so totally “kick-ass,” they open-sourced a vast set of hard drive information a few years ago and continue updating it each quarter. What a treasure trove of superb data. Backblaze, thank you from the bottom of my heart.</p><p>The Backblaze data includes operational metrics from hard drives with an indicator of a hard-drive failure. It is an excellent source for teaching techniques related to machine failure. Again, thank you for making this available to the open-source community.</p><p>Here is a link to the data.</p><p><a href="https://www.backblaze.com/b2/hard-drive-test-data.html">Backblaze Hard Drive Stats</a></p><p>My goal in this series of articles is not to give the best solution with the highest AUC. My goal is to show you how to approach equipment failure problems and build solutions that reflect realistic accuracy, and provide an easy transition from the lab to the real world.</p><p>I will use a Spark/Python Jupyter notebook inside IBM’s Watson Studio on the cloud as a tool in this discussion.</p><p><a href="https://www.ibm.com/cloud/watson-studio">IBM Watson Studio - Overview</a></p><p>I will also be using cloud object storage on the IBM cloud.</p><p><a href="https://cloud.ibm.com/docs/cloud-object-storage">IBM Cloud Docs</a></p><p>The second article is about designing features for a predictive model. Specifically, using data from 2017, 2018 and 2019 to build features for our model based on 2020. For more information on mean encoded features, please see the following article.</p><p><a href="https://medium.com/towards-data-science/leveraging-value-from-postal-codes-naics-codes-area-codes-and-other-funky-arse-categorical-be9ce75b6d5a">https://medium.com/towards-data-science/leveraging-value-from-postal-codes-naics-codes-area-codes-and-other-funky-arse-categorical-be9ce75b6d5a</a></p><p>I created these notebooks with a runtime useing 1 driver with 1 vCPU and 4 GB RAM, and 2 executors each with 1 vCPU and 4 GB RAM. This is available for free on the IBM Cloud. Some of the notebooks take a few hours to run. You’ll need to schedule your notebooks to run as jobs.</p><p><a href="https://dataplatform.cloud.ibm.com/docs/content/wsj/analyze-data/schedule-task.html">Scheduling a notebook</a></p><p>I recommend working through this article if you have not previously done so. It will provide further details on the techniques used to understand the data from Backblaze.</p><p><a href="https://medium.com/swlh/machine-learning-for-equipment-failure-prediction-and-predictive-maintenance-pm-e72b1ce42da1">Machine Learning for Equipment Failure Prediction and Predictive Maintenance (PM)</a></p><h3>2.0 Establish environment and parameters</h3><pre>from functools import reduce<br>from pyspark.sql import DataFrame<br><br>import pyspark.sql.functions as F<br><br>from pyspark.sql.functions import when<br><br>from pyspark.sql.functions import rand<br>from pyspark.sql.functions import lit<br><br>#Define cloud object storages parameters<br>import ibmos2spark, os<br># @hidden_cell<br><br>if os.environ.get(&#39;RUNTIME_ENV_LOCATION_TYPE&#39;) == &#39;external&#39;:<br>    endpoint_ae0ee98cbce04bcbb3163be1d0955096 = &#39;https://s3-api.us-geo.objectstorage.softlayer.net&#39;<br>else:<br>    endpoint_ae0ee98cbce04bcbb3163be1d0955096 = &#39;https://s3-api.us-geo.objectstorage.service.networklayer.com&#39;<br><br>credentials = {<br>    &#39;endpoint&#39;: XXXXXX,<br>    &#39;service_id&#39;: &#39;XXXXXX&#39;,<br>    &#39;iam_service_endpoint&#39;: &#39;XXXXX&#39;,<br>    &#39;api_key&#39;: &#39;XXXXXX&#39;<br>}<br><br>configuration_name = &#39;os_ae0ee98cbce04bcbb3163be1d0955096_configs&#39;<br>cos = ibmos2spark.CloudObjectStorage(sc, credentials, configuration_name, &#39;bluemix_cos&#39;)</pre><h3>3.0 Read in data created in step 1</h3><p>Read in the data from 2017–2019 we created in step 1. There are 107,909,839 observations and 16 fields.</p><pre>df = spark.read.parquet(cos.url(https://medium.com/&#39;data2019_2017.parquet&#39;,%20&#39;backblazedata-donotdelete-pr-cij57grgkoctem&#39;))<br><br>#df=df.show(200)<br>#print((df.count(), len(df.columns)))</pre><h3>4.0 Create mean encoded features.</h3><p>In the next few steps we will created mean encoded features and export to a format to be used in our predictive model.</p><p>One thing you want to avoid when building mean encoded features is using irrelevant aggregations. This can occur when you don’t have a big enough sample for the aggregation to be meaningful. The failure rate is tiny in this exercise. This means we must ensure a large number of observations are available for the aggregations to be meaningful. In the code below, I use 10,000 as a threshold. There is no magic number, but I picked 10,000 based on the fact that overall average failure rate across all disk drives.</p><h4>4.1 Establish a global mean</h4><p>Having a global mean in the data frame allows us to easily replace irrelevant values with an average.</p><p>Create a Dummy field to use in aggregations.</p><pre>df = df.withColumn(&quot;wookie&quot;, lit(1))</pre><p>Create a global failure rate accross all three years of data. We will use this when we create the features. We now have a spark dataframe that expresses the average failure rate across all disks for the last three years.</p><pre>#aggregate the data<br>total = df.groupBy(&#39;wookie&#39;).agg(F.mean(&quot;failure&quot;).alias(&#39;avg_failure&#39;)).collect()<br>#convert output to rdd<br>rdd = spark.sparkContext.parallelize(total)<br>#convert output to spark<br>zz=rdd.toDF()<br>#rename the column<br>zz=zz.withColumnRenamed(&quot;avg_failure&quot;,&quot;GLOBAL_AVG_FAILURE&quot;)<br>#multiply by 10,000, for formatting purposes.<br>zz = zz.withColumn(&quot;GLOBAL_AVG_FAILURE&quot;, zz.GLOBAL_AVG_FAILURE*10000)<br>#zz.show(200)</pre><p>Join the global average to the original data frame.</p><pre>df=df.join(zz,(df.wookie) == (zz.wookie),”inner”)</pre><h4>4.2 Aggregate the failure rate by Manufacturer.</h4><pre>#Calculate the summaries.<br>total = df.groupBy(&#39;MANUFACTURER&#39;).agg(F.mean(&quot;failure&quot;).alias(&#39;avg_failure&#39;),F.count(&quot;failure&quot;).alias(&#39;count_failure&#39;),\<br>                                       F.sum(&quot;failure&quot;).alias(&#39;sum_failure&#39;),F.mean(&quot;GLOBAL_AVG_FAILURE&quot;).alias(&#39;GLOBAL_AVG_FAILURE&#39;)).collect()<br>#Convert to RDD<br>rdd = spark.sparkContext.parallelize(total)<br>#convert to spark<br>zz=rdd.toDF()<br>#rename columns<br>zz=zz.withColumnRenamed(&quot;avg_failure&quot;,&quot;MANU_FAIL_RATE&quot;)<br>zz=zz.withColumnRenamed(&quot;sum_failure&quot;,&quot;MANU_FAIL_TOTAL&quot;)<br>zz=zz.withColumnRenamed(&quot;count_failure&quot;,&quot;MANU_FAIL_CNT&quot;)<br>#multiply by 10,000 to make them easier to read and deal with<br>zz = zz.withColumn(&quot;MANU_FAIL_RATE&quot;, zz.MANU_FAIL_RATE*10000)<br><br>#zz.show(200)</pre><p>We want to avoid situations where aggregations are based on a small number of records. In the next step we replace values with the global failure average if the total number of records used to calcluate the value is less than 10,000. Again, 10,000 is reasonable based on the overall failure rate.</p><pre>df_manu = zz.withColumn(&quot;MANU_FAIL_RATE&quot;, when(zz.MANU_FAIL_CNT&lt;100000,zz.GLOBAL_AVG_FAILURE).otherwise(zz.MANU_FAIL_RATE))<br><br>#df_manu.show(200)</pre><p>Convert the aggregated data frame to pandas.</p><pre>df_manup = df_manu.toPandas()</pre><p>Define credentials for object storage</p><pre>import os, types<br>import pandas as pd<br>from botocore.client import Config<br>import ibm_boto3<br><br>def __iter__(self): return 0<br># @hidden_cell<br># The following code contains the credentials for a file in your IBM Cloud Object Storage.<br># You might want to remove those credentials before you share your notebook.<br>credentials = {<br>    &#39;IAM_SERVICE_ID&#39;: &#39;XXXXXX&#39;,<br>    &#39;IBM_API_KEY_ID&#39;: &#39;XXXXXX&#39;,<br>    &#39;ENDPOINT&#39;: &#39;XXXXX&#39;,<br>    &#39;IBM_AUTH_ENDPOINT&#39;: &#39;XXXXXX&#39;,<br>    &#39;BUCKET&#39;: &#39;XXXXXX&#39;,<br>    &#39;FILE&#39;: &#39;XXXXXX&#39;<br>}</pre><pre>from ibm_botocore.client import Config<br>import ibm_boto3<br>cos = ibm_boto3.client(service_name=’s3&#39;,<br> ibm_api_key_id=credentials[‘IBM_API_KEY_ID’],<br> ibm_service_instance_id=credentials[‘IAM_SERVICE_ID’],<br> ibm_auth_endpoint=credentials[‘IBM_AUTH_ENDPOINT’],<br> config=Config(signature_version=’oauth’),<br> endpoint_url=credentials[‘ENDPOINT’])</pre><p>Export the pandas dataframe to csv and upload to cloud object storage.</p><pre>df_manup=df_manup.to_csv(‘manufacturer.csv’,index=False)<br>cos.upload_file(Filename=’manufacturer.csv’,Bucket=credentials[‘BUCKET’],Key=’manufacturer.csv’)</pre><h4>4.3 Aggregate the failure rate by Model.</h4><pre>#Calculate the summaries.<br>total = df.groupBy(‘MODEL’).agg(F.mean(“failure”).alias(‘avg_failure’),F.count(“failure”).alias(‘count_failure’),\<br> F.sum(“failure”).alias(‘sum_failure’),F.mean(“GLOBAL_AVG_FAILURE”).alias(‘GLOBAL_AVG_FAILURE’)).collect()<br>#Convert to RDD<br>rdd = spark.sparkContext.parallelize(total)<br>#convert output to spark</pre><pre>zz=rdd.toDF()<br>#rename columns<br>zz=zz.withColumnRenamed(“avg_failure”,”MODEL_FAIL_RATE”)<br>zz=zz.withColumnRenamed(“sum_failure”,”MODEL_FAIL_TOTAL”)<br>zz=zz.withColumnRenamed(“count_failure”,”MODEL_FAIL_CNT”)<br>#multiply by 10,000 to make them easier to read and deal with<br>zz = zz.withColumn(“MODEL_FAIL_RATE”, zz.MODEL_FAIL_RATE*10000)</pre><pre>#replace values when total for a summary is less than 10,000<br>df_model = zz.withColumn(“MODEL_FAIL_RATE”, when(zz.MODEL_FAIL_CNT&lt;100000,zz.GLOBAL_AVG_FAILURE).otherwise(zz.MODEL_FAIL_RATE))</pre><pre>#convert to Pandas<br>df_modelp = df_model.toPandas()<br>#export to csv<br>df_modelp=df_modelp.to_csv(‘model.csv’,index=False)<br>#upload to object storage<br>cos.upload_file(Filename=’model.csv’,Bucket=credentials[‘BUCKET’],Key=’model.csv’)<br>#zz.show(200)</pre><h4>4.4 Calculate the values of predictors when a disk fails by model.</h4><p>This aggregation could be a useful predictor when compared to other non-failure values. For example, if a disk fails everytime a field is equal to 76.4, you should probably take note.</p><p>Select disks that failed</p><pre>df_failure=df.filter(df.FAILURE == 1)</pre><p>Aggregate the fields by model</p><pre>#Calculate the summaries.<br>total = df_failure.groupBy(&#39;MODEL&#39;).agg(F.mean(&quot;REAllOCATED_SECTOR_COUNT_N&quot;).alias(&#39;REALLOCATED_SECTOR_COUNT_N_MOD&#39;),\<br>                                F.mean(&quot;REPORTED_UNCORRECTABLE_ERRORS_N&quot;).alias(&#39;REPORTED_UNCORRECTABLE_ERRORS_N_MOD&#39;),\<br>                                F.mean(&quot;COMMAND_TIMEOUT_N&quot;).alias(&#39;COMMAND_TIMEOUT_N_MOD&#39;),\<br>                                F.mean(&quot;CURRENT_PENDING_SECTOR_COUNT_N&quot;).alias(&#39;CURRENT_PENDING_SECTOR_COUNT_N_MOD&#39;),\<br>                                F.mean(&quot;POWER_ON_HOURS_N&quot;).alias(&#39;POWER_ON_HOURS_N_MOD&#39;),\<br>                                F.mean(&quot;REAllOCATED_SECTOR_COUNT_R&quot;).alias(&#39;REALLOCATED_SECTOR_COUNT_R_MOD&#39;),\<br>                                F.mean(&quot;REPORTED_UNCORRECTABLE_ERRORS_R&quot;).alias(&#39;REPORTED_UNCORRECTABLE_ERRORS_R_MOD&#39;),\<br>                                F.mean(&quot;COMMAND_TIMEOUT_R&quot;).alias(&#39;COMMAND_TIMEOUT_R_MOD&#39;),\<br>                                F.mean(&quot;CURRENT_PENDING_SECTOR_COUNT_R&quot;).alias(&#39;CURRENT_PENDING_SECTOR_COUNT_R_MOD&#39;),\<br>                                F.mean(&quot;POWER_ON_HOURS_R&quot;).alias(&#39;POWER_ON_HOURS_R_MOD&#39;)).collect()<br>#Convert to RDD<br>rdd = spark.sparkContext.parallelize(total)<br><br>#convert to spark<br>df_avg_by_model=rdd.toDF()<br>#convert to pandas<br>df_avg_by_model = df_avg_by_model.toPandas()<br>#export to csv<br>df_avg_by_model=df_avg_by_model.to_csv(&#39;df_avg_by_model.csv&#39;,index=False)<br>#upload to cloud object storage<br>cos.upload_file(Filename=&#39;df_avg_by_model.csv&#39;,Bucket=credentials[&#39;BUCKET&#39;],Key=&#39;df_avg_by_model.csv&#39;)</pre><h4>4.5 Calculate the values of predictors when a disk fails by manufacturer.</h4><pre>#Calculate the summaries.<br>total = df_failure.groupBy(‘MANUFACTURER’).agg(F.mean(“REAllOCATED_SECTOR_COUNT_N”).alias(‘REALLOCATED_SECTOR_COUNT_N_MAN’),\<br> F.mean(“REPORTED_UNCORRECTABLE_ERRORS_N”).alias(‘REPORTED_UNCORRECTABLE_ERRORS_N_MAN’),\<br> F.mean(“COMMAND_TIMEOUT_N”).alias(‘COMMAND_TIMEOUT_N_MAN’),\<br> F.mean(“CURRENT_PENDING_SECTOR_COUNT_N”).alias(‘CURRENT_PENDING_SECTOR_COUNT_N_MAN’),\<br> F.mean(“POWER_ON_HOURS_N”).alias(‘POWER_ON_HOURS_N_MAN’),\<br> F.mean(“REAllOCATED_SECTOR_COUNT_R”).alias(‘REALLOCATED_SECTOR_COUNT_R_MAN’),\<br> F.mean(“REPORTED_UNCORRECTABLE_ERRORS_R”).alias(‘REPORTED_UNCORRECTABLE_ERRORS_R_MAN’),\<br> F.mean(“COMMAND_TIMEOUT_R”).alias(‘COMMAND_TIMEOUT_R_MAN’),\<br> F.mean(“CURRENT_PENDING_SECTOR_COUNT_R”).alias(‘CURRENT_PENDING_SECTOR_COUNT_R_MAN’),\<br> F.mean(“POWER_ON_HOURS_R”).alias(‘POWER_ON_HOURS_R_MAN’)).collect()<br>#Convert to RDD<br>rdd = spark.sparkContext.parallelize(total)</pre><pre>#convert to spark<br>df_avg_by_manu=rdd.toDF()</pre><pre>#convert to pandas<br>df_avg_by_manu = df_avg_by_manu.toPandas()<br>#export to csv<br>df_avg_by_manu=df_avg_by_manu.to_csv(‘df_avg_by_manu.csv’,index=False)<br>#upload to cloud object storage<br>cos.upload_file(Filename=’df_avg_by_manu.csv’,Bucket=credentials[‘BUCKET’],Key=’df_avg_by_manu.csv’)</pre><pre>#df_avg_by_manu.show(10)</pre><p>All data used in this notebook is the property of Backblaze.</p><p>For questions regarding use of data please see the following website.</p><ul><li><a href="https://www.backblaze.com/b2/hard-drive-test-data.html">Backblaze Hard Drive Stats</a></li><li><a href="https://www.kaggle.com/datasets/backblaze/hard-drive-test-data">Hard Drive Test Data</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f53235bdb4e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/a-complete-solution-to-the-backbaze-com-kaggle-problem-1f53235bdb4e">A Complete Solution to the BackBaze.com Kaggle Problem</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Complete Solution to the BackBaze.com Kaggle Problem]]></title>
            <link>https://medium.com/geekculture/a-complete-solution-to-the-backbaze-com-kaggle-problem-cf1fab1af529?source=rss-b2cb0fe3df91------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf1fab1af529</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[equipment-failure]]></category>
            <category><![CDATA[kaggle]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[spark]]></category>
            <dc:creator><![CDATA[Shad Griffin]]></dc:creator>
            <pubDate>Wed, 28 Dec 2022 01:30:56 GMT</pubDate>
            <atom:updated>2026-06-03T17:27:12.991Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Complete Solution to the Backblaze Machine Failure Kaggle Problem, I</h3><p>Step One, File Processing</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s4fwIhjYir1hfWb3pJNvSA.jpeg" /></figure><p><a href="https://github.com/shadgriffin/backblazedata/blob/master/Backblaze.com%20--%20Step%20One%20--%20File%20Processing.ipynb">backblazedata/Backblaze.com -- Step One -- File Processing.ipynb at master · shadgriffin/backblazedata</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FGJewNI72VTE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DGJewNI72VTE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FGJewNI72VTE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce6fcde0251c03f1e41e42e1eefd4955/href">https://medium.com/media/ce6fcde0251c03f1e41e42e1eefd4955/href</a></iframe><ul><li><a href="https://jshadgriffin.medium.com/a-complete-solution-to-the-backbaze-com-kaggle-problem-9d5cb45a88db">A Complete Solution to the BackBaze.com Kaggle Problem</a></li><li><a href="https://jshadgriffin.medium.com/a-complete-solution-to-the-backbaze-com-kaggle-problem-3a9558cd8929">A Complete Solution to the BackBaze.com Kaggle Problem</a></li><li><a href="https://jshadgriffin.medium.com/a-complete-solution-to-the-backbaze-com-kaggle-problem-7c0f51429908">A Complete Solution to the BackBaze.com Kaggle Problem</a></li><li><a href="https://jshadgriffin.medium.com/a-complete-solution-to-the-backbaze-com-kaggle-problem-cd51259787b7">A Complete Solution to the BackBaze.com Kaggle Problem</a></li><li><a href="https://jshadgriffin.medium.com/a-complete-solution-to-the-backbaze-com-kaggle-problem-1f53235bdb4e">A Complete Solution to the BackBaze.com Kaggle Problem</a></li></ul><h3>1.0 Introduction</h3><p>Backblaze, you are the “GOAT.” You are the “cat’s meow.” You “Rock the House.” In case you don’t know why Backblaze is so totally “kick-ass,” they open-sourced a vast set of hard drive information a few years ago and continue updating it each quarter. What a treasure trove of superb data. Backblaze, thank you from the bottom of my heart.</p><p>The backblaze data includes operational metrics from hard drives with an indicator of a hard-drive failure. It is an excellent source for teaching techniques related to machine failure. Again, thank you for making this available to the open-source community.</p><p>Here is a link to the data.</p><p><a href="https://www.backblaze.com/b2/hard-drive-test-data.html">Backblaze Hard Drive Stats</a></p><p>My goal in this series of articles is not to give the best solution with the highest AUC. My goal is to show you how to approach equipment failure problems and build solutions that reflect realistic accuracy, and provide an easy transition from the lab to the real world.</p><p>I will use a Spark/Python Jupyter notebook inside IBM’s Watson Studio on the cloud as a tool in this discussion.</p><p><a href="https://www.ibm.com/cloud/watson-studio">IBM Watson Studio - Overview</a></p><p>I will also be using cloud object storage on the IBM cloud.</p><p><a href="https://cloud.ibm.com/docs/cloud-object-storage">IBM Cloud Docs</a></p><p>The first article in this series is, without question, the most mundane. I will be loading data from the CSV files provided by Backblaze into SPARK data frames. File processing is a tedious but necessary part of the process.</p><p>Before running this code, I downloaded the .csv files from Backblaze and uploaded them to IBM Cloud object storage. Note our friends at Backblaze conveniently labeled the CSV files in the following format.</p><p>“YYYY_MM_DD.csv.”</p><p>The naming convention makes it easy to load them systematically from cloud object storage to spark data frames. Also, note that I only use a handful of the fields in the CSV file. And finally, I limited my work here to 2018, 2019, and 2020.<br> <br> I created these notebooks with a runtime useing 1 driver with 1 vCPU and 4 GB RAM, and 2 executors each with 1 vCPU and 4 GB RAM. This is available for free on the IBM Cloud. Some of the notebooks take a few hours to run. You’ll need to schedule your notebooks to run as jobs.</p><p><a href="https://dataplatform.cloud.ibm.com/docs/content/wsj/analyze-data/schedule-task.html">Scheduling a notebook</a></p><p>I recommend working through this article if you have not previously done so. It will provide further details on the techniques used to understand the data from Backblaze.</p><p><a href="https://medium.com/swlh/machine-learning-for-equipment-failure-prediction-and-predictive-maintenance-pm-e72b1ce42da1">Machine Learning for Equipment Failure Prediction and Predictive Maintenance (PM)</a></p><h3>2.0 Establish environment and parameters</h3><p>Import the Relevant Libraries and connect to object storage.</p><pre>#Import relevant Libraries<br>from functools import reduce<br>from pyspark.sql import DataFrame<br><br>import pyspark.sql.functions as F<br><br>from pyspark.sql.functions import when<br><br>#Define cloud object storages parameters<br>import ibmos2spark, os<br># @hidden_cell<br><br>#Define cloud object storages parameters<br>import ibmos2spark, os<br># @hidden_cell<br><br>if os.environ.get(&#39;RUNTIME_ENV_LOCATION_TYPE&#39;) == &#39;external&#39;:<br>    endpoint_ae0ee98cbce04bcbb3163be1d0955096 = &#39;https://s3-api.us-geo.objectstorage.softlayer.net&#39;<br>else:<br>    endpoint_ae0ee98cbce04bcbb3163be1d0955096 = &#39;https://s3-api.us-geo.objectstorage.service.networklayer.com&#39;<br><br>credentials = {<br>    &#39;endpoint&#39;: XXXXXX,<br>    &#39;service_id&#39;: &#39;XXXXXX&#39;,<br>    &#39;iam_service_endpoint&#39;: &#39;XXXXXX&#39;,<br>    &#39;api_key&#39;: &#39;XXXXXX&#39;<br>}<br><br>configuration_name = &#39;XXXXX&#39;<br>cos = ibmos2spark.CloudObjectStorage(sc, credentials, configuration_name, &#39;bluemix_cos&#39;)</pre><h3>3.0 Process Data</h3><h4>3.1 Create Null Data frame</h4><p>There are many ways to import CSV files into SPARK data frames. I can not say my approach is the best, but I can say with certainty it works.</p><p>The first step is to create a <em>null</em> data frame with the relevant fields and no records.</p><p>Again, I am using only some of the fields available. The schema of the files has changed over time. The fields in the final data appear historically in all files. I also removed columns that did not seem relevant. The point of this exercise is not to build the ultimate model. Instead, it is to demonstrate how I approach these types of problems.</p><pre>#read in a specific csv file<br>base = spark.read\<br> .format(‘org.apache.spark.sql.execution.datasources.csv.CSVFileFormat’)\<br> .option(‘header’, ‘true’)\<br> .load(cos.url(https://medium.com/%E2%80%982020%E2%80%9301%E2%80%9302.csv%E2%80%99,%20%E2%80%98backblazedata-donotdelete-pr-cij57grgkoctem%E2%80%99))<br>#Truncate the file so there is no records.<br>base=base.filter(base.serial_number ==’DAN PASTORINI’)<br>#limit the fields to those we are interested in<br>base = base.select(“date”, “serial_number”, “model”,”capacity_bytes”,”failure”,”smart_5_normalized”,”smart_187_normalized”,”smart_188_normalized”,\<br> “smart_197_normalized”,”smart_9_normalized”,”smart_5_raw”,”smart_187_raw”,”smart_188_raw”,\<br> “smart_197_raw”,”smart_9_raw”)</pre><h4>3.2 Read in Data from csv files</h4><p>In the following blocks of code, I will read each .csv file for 2020, 2019, and 2018. I created a separate block of code for months based on the number of days in the month. I process months with 31, 30, 29, and 28 days in separate blocks of code.</p><p>Note that looping through each file one at a time from CSV import to spark minimizes the amount of memory. The final result is a parque file I can use in the second notebook of this series.</p><p><strong>3.21 Read in Months with 31 days.</strong></p><pre># define the years<br>for d in ([&#39;2017&#39;,&#39;2020&#39;,&#39;2019&#39;,&#39;2018&#39;]):    <br>    #define the months with 31 days<br>    for t in ([&#39;01&#39;,&#39;03&#39;,&#39;05&#39;,&#39;07&#39;,&#39;08&#39;,&#39;10&#39;,&#39;12&#39;]):<br>        #define the first 9 days -- these will need a leading 0 to identify them<br>        for q in range(1,10):  <br>            #define the file name based on d, t and q<br>            z=(d + &quot;-&quot; + t + &quot;-&quot; + &#39;0&#39; +str(q)+&quot;.csv&quot;)<br>        <br>            #read the file from object storage<br>            input_data = spark.read\<br>              .format(&#39;org.apache.spark.sql.execution.datasources.csv.CSVFileFormat&#39;)\<br>              .option(&#39;header&#39;, &#39;true&#39;)\<br>              .load(cos.url(https://medium.com/z,%20&#39;backblazedata-donotdelete-pr-cij57grgkoctem&#39;))<br>            #select the relevant fields<br>            input_data = input_data.select(&quot;date&quot;, &quot;serial_number&quot;, &quot;model&quot;,&quot;capacity_bytes&quot;,&quot;failure&quot;,&quot;smart_5_normalized&quot;,&quot;smart_187_normalized&quot;,&quot;smart_188_normalized&quot;,\<br>                   &quot;smart_197_normalized&quot;,&quot;smart_9_normalized&quot;,&quot;smart_5_raw&quot;,&quot;smart_187_raw&quot;,&quot;smart_188_raw&quot;,\<br>                   &quot;smart_197_raw&quot;,&quot;smart_9_raw&quot;)<br>            #append the current file to the running data frame originally based on the null frame<br>            base = reduce(DataFrame.unionAll, [base,input_data])<br>        <br>        for q in range(10,32): #define days 10 -31 -- these will NOT need a leading 0 to identify them   <br>            z=(d + &quot;-&quot; + t + &quot;-&quot; +str(q)+&quot;.csv&quot;)#define the file name based on d, t and q<br>        <br>            #print(z)<br>            input_data = spark.read\<br>              .format(&#39;org.apache.spark.sql.execution.datasources.csv.CSVFileFormat&#39;)\<br>              .option(&#39;header&#39;, &#39;true&#39;)\<br>              .load(cos.url(https://medium.com/z,%20&#39;backblazedata-donotdelete-pr-cij57grgkoctem&#39;))#read the file from object storage<br>            input_data = input_data.select(&quot;date&quot;, &quot;serial_number&quot;, &quot;model&quot;,&quot;capacity_bytes&quot;,&quot;failure&quot;,&quot;smart_5_normalized&quot;,&quot;smart_187_normalized&quot;,&quot;smart_188_normalized&quot;,\<br>                   &quot;smart_197_normalized&quot;,&quot;smart_9_normalized&quot;,&quot;smart_5_raw&quot;,&quot;smart_187_raw&quot;,&quot;smart_188_raw&quot;,\<br>                   &quot;smart_197_raw&quot;,&quot;smart_9_raw&quot;) #select the relevant fields<br>            base = reduce(DataFrame.unionAll, [base,input_data])#append the current file to the running data frame </pre><p><strong>3.22 Read in Months with 30 days.</strong></p><pre>for d in ([&#39;2020&#39;,&#39;2019&#39;,&#39;2018&#39;,&#39;2017&#39;]):   # define the years<br>    for t in ([&#39;04&#39;,&#39;06&#39;,&#39;09&#39;,&#39;11&#39;]): #define the months with 30 days<br>        for q in range(1,10): #define the first 9 days -- these will need a leading 0 to identify them   <br>            z=(d + &quot;-&quot; + t + &quot;-&quot; + &#39;0&#39; +str(q)+&quot;.csv&quot;)#define the file name based on d, t and q<br>        <br>            #print(z)<br>            input_data = spark.read\<br>              .format(&#39;org.apache.spark.sql.execution.datasources.csv.CSVFileFormat&#39;)\<br>              .option(&#39;header&#39;, &#39;true&#39;)\<br>              .load(cos.url(https://medium.com/z,%20&#39;backblazedata-donotdelete-pr-cij57grgkoctem&#39;))#read the file from object storage<br>            input_data = input_data.select(&quot;date&quot;, &quot;serial_number&quot;, &quot;model&quot;,&quot;capacity_bytes&quot;,&quot;failure&quot;,&quot;smart_5_normalized&quot;,&quot;smart_187_normalized&quot;,&quot;smart_188_normalized&quot;,\<br>                   &quot;smart_197_normalized&quot;,&quot;smart_9_normalized&quot;,&quot;smart_5_raw&quot;,&quot;smart_187_raw&quot;,&quot;smart_188_raw&quot;,\<br>                   &quot;smart_197_raw&quot;,&quot;smart_9_raw&quot;)#select the relevant fields<br>            base = reduce(DataFrame.unionAll, [base,input_data]) #append the current file to the running data frame<br>        <br>        for q in range(10,31): #define days 10 - 30 -- these will NOT need a leading 0 to identify them     <br>            z=(d + &quot;-&quot; + t + &quot;-&quot; +str(q)+&quot;.csv&quot;)#define the file name based on d, t and q<br>        <br>            #print(z)<br>            input_data = spark.read\<br>              .format(&#39;org.apache.spark.sql.execution.datasources.csv.CSVFileFormat&#39;)\<br>              .option(&#39;header&#39;, &#39;true&#39;)\<br>              .load(cos.url(https://medium.com/z,%20&#39;backblazedata-donotdelete-pr-cij57grgkoctem&#39;))#read the file from object storage<br>            input_data = input_data.select(&quot;date&quot;, &quot;serial_number&quot;, &quot;model&quot;,&quot;capacity_bytes&quot;,&quot;failure&quot;,&quot;smart_5_normalized&quot;,&quot;smart_187_normalized&quot;,&quot;smart_188_normalized&quot;,\<br>                   &quot;smart_197_normalized&quot;,&quot;smart_9_normalized&quot;,&quot;smart_5_raw&quot;,&quot;smart_187_raw&quot;,&quot;smart_188_raw&quot;,\<br>                   &quot;smart_197_raw&quot;,&quot;smart_9_raw&quot;)#select the relevant fields<br>            base = reduce(DataFrame.unionAll, [base,input_data])#append the current file to the running data frame </pre><p><strong>3.23 Read in Months with 29 days.</strong></p><pre>for d in ([&#39;2020&#39;]):    # define the years  <br>    for t in ([&#39;02&#39;]):#define the months with 29 days<br>        for q in range(1,10):  #define the first 9 days -- these will need a leading 0 to identify them    <br>            z=(d + &quot;-&quot; + t + &quot;-&quot; + &#39;0&#39; +str(q)+&quot;.csv&quot;)#define the file name based on d, t and q<br>        <br>            #print(q)<br>            #print(z)<br>            input_data = spark.read\<br>              .format(&#39;org.apache.spark.sql.execution.datasources.csv.CSVFileFormat&#39;)\<br>              .option(&#39;header&#39;, &#39;true&#39;)\<br>              .load(cos.url(https://medium.com/z,%20&#39;backblazedata-donotdelete-pr-cij57grgkoctem&#39;))#read the file from object storage<br>            input_data = input_data.select(&quot;date&quot;, &quot;serial_number&quot;, &quot;model&quot;,&quot;capacity_bytes&quot;,&quot;failure&quot;,&quot;smart_5_normalized&quot;,&quot;smart_187_normalized&quot;,&quot;smart_188_normalized&quot;,\<br>                   &quot;smart_197_normalized&quot;,&quot;smart_9_normalized&quot;,&quot;smart_5_raw&quot;,&quot;smart_187_raw&quot;,&quot;smart_188_raw&quot;,\<br>                   &quot;smart_197_raw&quot;,&quot;smart_9_raw&quot;)#select the relevant fields<br>            base = reduce(DataFrame.unionAll, [base,input_data])#append the current file to the running data frame<br>        <br>        for q in range(10,30):   #define days 10 -29 -- these will NOT need a leading 0 to identify them   <br>            z=(d + &quot;-&quot;  + t + &quot;-&quot; +str(q)+&quot;.csv&quot;)#define the file name based on d, t and q<br>        <br>            #print(q)<br>            #print(z)<br>            input_data = spark.read\<br>              .format(&#39;org.apache.spark.sql.execution.datasources.csv.CSVFileFormat&#39;)\<br>              .option(&#39;header&#39;, &#39;true&#39;)\<br>              .load(cos.url(https://medium.com/z,%20&#39;backblazedata-donotdelete-pr-cij57grgkoctem&#39;))#read the file from object storage<br>            input_data = input_data.select(&quot;date&quot;, &quot;serial_number&quot;, &quot;model&quot;,&quot;capacity_bytes&quot;,&quot;failure&quot;,&quot;smart_5_normalized&quot;,&quot;smart_187_normalized&quot;,&quot;smart_188_normalized&quot;,\<br>                   &quot;smart_197_normalized&quot;,&quot;smart_9_normalized&quot;,&quot;smart_5_raw&quot;,&quot;smart_187_raw&quot;,&quot;smart_188_raw&quot;,\<br>                   &quot;smart_197_raw&quot;,&quot;smart_9_raw&quot;)#select the relevant fields<br>            base = reduce(DataFrame.unionAll, [base,input_data])#append the current file to the running data frame </pre><p><strong>3.24 Read in Months with 28 days.</strong></p><pre>for d in ([&#39;2019&#39;,&#39;2018&#39;,&#39;2017&#39;]):    # define the years   <br>    for t in ([&#39;02&#39;]):#define the months with 28 days <br>        for q in range(1,10):  #define the first 9 days -- these will need a leading 0 to identify them <br>            z=(d + &quot;-&quot; + t + &quot;-&quot; + &#39;0&#39; +str(q)+&quot;.csv&quot;) #define the file name based on d, t and q<br>        <br>            #print(q)<br>            #print(z)<br>            input_data = spark.read\<br>              .format(&#39;org.apache.spark.sql.execution.datasources.csv.CSVFileFormat&#39;)\<br>              .option(&#39;header&#39;, &#39;true&#39;)\<br>              .load(cos.url(https://medium.com/z,%20&#39;backblazedata-donotdelete-pr-cij57grgkoctem&#39;))#read the file from object storage<br>            input_data = input_data.select(&quot;date&quot;, &quot;serial_number&quot;, &quot;model&quot;,&quot;capacity_bytes&quot;,&quot;failure&quot;,&quot;smart_5_normalized&quot;,&quot;smart_187_normalized&quot;,&quot;smart_188_normalized&quot;,\<br>                   &quot;smart_197_normalized&quot;,&quot;smart_9_normalized&quot;,&quot;smart_5_raw&quot;,&quot;smart_187_raw&quot;,&quot;smart_188_raw&quot;,\<br>                   &quot;smart_197_raw&quot;,&quot;smart_9_raw&quot;)#select the relevant fields<br>            base = reduce(DataFrame.unionAll, [base,input_data])#append the current file to the running data frame<br>        <br>        for q in range(10,29):  #define days 10 - 28 -- these will NOT need a leading 0 to identify them   <br>            z=(d + &quot;-&quot;  + t + &quot;-&quot; +str(q)+&quot;.csv&quot;)#define the file name based on d, t and q<br>        <br>            #print(q)<br>            #print(z)<br>            input_data = spark.read\<br>              .format(&#39;org.apache.spark.sql.execution.datasources.csv.CSVFileFormat&#39;)\<br>              .option(&#39;header&#39;, &#39;true&#39;)\<br>              .load(cos.url(https://medium.com/z,%20&#39;backblazedata-donotdelete-pr-cij57grgkoctem&#39;))#read the file from object storage<br>            input_data = input_data.select(&quot;date&quot;, &quot;serial_number&quot;, &quot;model&quot;,&quot;capacity_bytes&quot;,&quot;failure&quot;,&quot;smart_5_normalized&quot;,&quot;smart_187_normalized&quot;,&quot;smart_188_normalized&quot;,\<br>                   &quot;smart_197_normalized&quot;,&quot;smart_9_normalized&quot;,&quot;smart_5_raw&quot;,&quot;smart_187_raw&quot;,&quot;smart_188_raw&quot;,\<br>                   &quot;smart_197_raw&quot;,&quot;smart_9_raw&quot;)#select the relevant fields<br>            base = reduce(DataFrame.unionAll, [base,input_data])#append the current file to the running data frame</pre><h3>4.0 Prepare Fields</h3><p>In the next section I clean up the fields.</p><pre># rename the dataframe for simplicity<br>df=base</pre><p>Give the fields descriptive names</p><pre># rename each field so it is more descriptive<br>df = df.withColumnRenamed(&quot;smart_5_normalized&quot;,&quot;REAllOCATED_SECTOR_COUNT_N&quot;) \<br>    .withColumnRenamed(&quot;smart_187_normalized&quot;,&quot;REPORTED_UNCORRECTABLE_ERRORS_N&quot;)\<br>    .withColumnRenamed(&quot;smart_188_normalized&quot;,&quot;COMMAND_TIMEOUT_N&quot;)\<br>    .withColumnRenamed(&quot;smart_197_normalized&quot;,&quot;CURRENT_PENDING_SECTOR_COUNT_N&quot;)\<br>    .withColumnRenamed(&quot;smart_198_normalized&quot;,&quot;OFFLINE_UNCORRECTABLE_N&quot;)\<br>    .withColumnRenamed(&quot;smart_9_normalized&quot;,&quot;POWER_ON_HOURS_N&quot;)\<br>    .withColumnRenamed(&quot;smart_5_raw&quot;,&quot;REAllOCATED_SECTOR_COUNT_R&quot;)\<br>    .withColumnRenamed(&quot;smart_187_raw&quot;,&quot;REPORTED_UNCORRECTABLE_ERRORS_R&quot;)\<br>    .withColumnRenamed(&quot;smart_188_raw&quot;,&quot;COMMAND_TIMEOUT_R&quot;)\<br>    .withColumnRenamed(&quot;smart_197_raw&quot;,&quot;CURRENT_PENDING_SECTOR_COUNT_R&quot;)\<br>    .withColumnRenamed(&quot;smart_198_raw&quot;,&quot;OFFLINE_UNCORRECTABLE_R&quot;)\<br>    .withColumnRenamed(&quot;smart_9_raw&quot;,&quot;POWER_ON_HOURS_R&quot;)\<br>    .withColumnRenamed(&quot;date&quot;,&quot;DATE&quot;)\<br>    .withColumnRenamed(&quot;serial_number&quot;,&quot;SERIAL_NUMBER&quot;)\<br>    .withColumnRenamed(&quot;model&quot;,&quot;MODEL&quot;)\<br>    .withColumnRenamed(&quot;capacity_bytes&quot;,&quot;CAPACITY_BYTES&quot;)\<br>    .withColumnRenamed(&quot;failure&quot;,&quot;FAILURE&quot;).cache()</pre><p>The model field needs a little cleaning up. The Seagate brand, for example, has 5 different values in the data. We will create a new field called “Manufacturer” to correct this.</p><pre><br><br>df = df.withColumn(&#39;MANUFACTURER&#39;,when (F.instr(df.MODEL, &#39;TOSHIBA&#39;) &gt; 0,&#39;TOSHIBA&#39;)\<br>                   .when(F.instr(df.MODEL, &#39;SG&#39;) &gt; 0,&#39;SEAGATE&#39;)\<br>                   .when(F.instr(df.MODEL, &#39;ST&#39;) &gt; 0,&#39;SEAGATE&#39;)\<br>                   .when(F.instr(df.MODEL, &#39;Sea&#39;) &gt; 0,&#39;SEAGATE&#39;)\<br>                   .when(F.instr(df.MODEL, &#39;SG&#39;) &gt; 0,&#39;SEAGATE&#39;)\<br>                   .when(F.instr(df.MODEL, &#39;HGST&#39;) &gt; 0,&#39;HGST&#39;)\<br>                   .when(F.instr(df.MODEL, &#39;WD&#39;) &gt; 0,&#39;WD&#39;)\<br>                   .when(F.instr(df.MODEL, &#39;DELL&#39;) &gt; 0,&#39;DELL&#39;)\<br>                   .when(F.instr(df.MODEL, &#39;Hit&#39;) &gt; 0,&#39;HITACHI&#39;).otherwise(&#39;pp&#39;)).cache()</pre><h3>5.0 Export to Parquet files</h3><p>As we progress through this exercise, I will use the 2018 and 2019 to create mean encoded dummy variables and I will use the 2020 to build my model. Given that each year in the available data has a different function, I will create two different dataframes. One, for 2020 and another for 2018 and 2019.</p><p>For more info on mean encoded dummy variables, please see the following article.</p><p><a href="https://towardsdatascience.com/leveraging-value-from-postal-codes-naics-codes-area-codes-and-other-funky-arse-categorical-be9ce75b6d5a">Leveraging Value from Postal Codes, NAICS Codes, Area Codes and Other Funky-Arse Categorical…</a></p><pre>df_2020=df.filter(df.DATE&gt;=&#39;2020-01-01&#39;).cache()<br>df_2019_2017=df.filter(df.DATE&lt;=&#39;2019-12-31&#39;).cache()</pre><p>Now I will export these data frames to a parque file that we can use in subsequent steps.</p><p>Write 2020 data to parquet file.</p><pre>#cos.url(https://medium.com/filenametowrite,bucketnameforyourproject). For example:<br><br>df_2020.write.mode(&quot;overwrite&quot;).parquet(cos.url(https://medium.com/&#39;data2020.parquet&#39;,%20&#39;backblazedata-donotdelete-pr-cij57grgkoctem&#39;))</pre><p>Write 2019, 2018 and 2017 data to a parquet file.</p><pre>#cos.url(https://medium.com/filenametowrite,bucketnameforyourproject). For example:<br><br>df_2019_2017.write.mode(&quot;overwrite&quot;).parquet(cos.url(https://medium.com/&#39;data2019_2017.parquet&#39;,%20&#39;backblazedata-donotdelete-pr-cij57grgkoctem&#39;))</pre><p>All data used in this notebook is the property of Backblaze.</p><p>For questions regarding use of data please see the following website.</p><ul><li><a href="https://www.backblaze.com/b2/hard-drive-test-data.html">Backblaze Hard Drive Stats</a></li><li><a href="https://www.kaggle.com/datasets/backblaze/hard-drive-test-data">Hard Drive Test Data</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf1fab1af529" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/a-complete-solution-to-the-backbaze-com-kaggle-problem-cf1fab1af529">A Complete Solution to the BackBaze.com Kaggle Problem</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine Learning with Biased Data]]></title>
            <link>https://medium.com/geekculture/understanding-bias-in-modern-machine-learning-8795403ea1c7?source=rss-b2cb0fe3df91------2</link>
            <guid isPermaLink="false">https://medium.com/p/8795403ea1c7</guid>
            <category><![CDATA[gender-discrimination]]></category>
            <category><![CDATA[racial-discrimination]]></category>
            <category><![CDATA[bias]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Shad Griffin]]></dc:creator>
            <pubDate>Sat, 08 Jan 2022 15:31:18 GMT</pubDate>
            <atom:updated>2022-01-13T23:08:36.019Z</atom:updated>
            <content:encoded><![CDATA[<h4>Moving Forward when the Historical Record Includes Racial, Gender or Other Types of Discrimination</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Bh6ngohQoREdVB5H_PTBg.jpeg" /></figure><ul><li><a href="https://medium.com/geekculture/ai-has-the-power-to-save-the-world-or-destroy-it-efeb59f287e">AI has the power to save the world or destroy it.</a></li><li><a href="https://github.com/shadgriffin/ml_bias/blob/main/Bias%20final%20version.ipynb">ml_bias/Bias final version.ipynb at main · shadgriffin/ml_bias</a></li></ul><p>A few years ago, I heard someone talking about bias in machine learning models. My initial response? “What the heck is bias in machine learning models?” I seriously had no idea. Of course, there are different types of bias when doing Data Science, for example, confirmation bias, but I had no idea what this person was talking about. Over time, I began hearing the term more frequently, and eventually, I had to figure what everyone was talking about.</p><p>As an aside, I don’t particularly appreciate calling the issue at hand bias. Say what you want about terms like heteroskedasticity, but you know exactly what I mean when I use that term. Bias is too generic. It can mean many different things in many different situations. Nonetheless, after some research, I realized that the bias everyone was talking about refers to situations when your historical data is not consistent with your current business objectives.</p><p>Why is biased data a problem? If you build a machine learning model on biased data, the model’s results will reflect this bias.</p><p>For example, suppose your historical data reflects discrimination against a cohort of people, and you do not want to continue discriminating against them. In that case, the data is biased, and machine learning built on that data will also be biased. It isn’t that machine learning is prejudiced against anyone, but the people/organization/social constructs who generated the historical data were. This means that a machine learning model based on a history of excluding specific cohorts will replicate that behavior.</p><p>In the case of gender discrimination in tech hiring, if the historical record of hires lacks females, a machine learning model may conclude that females are not worthy candidates and predict them as less hireable. The model does not know that women were denied employment in tech roles based on their gender, not their ability to do the job. Machine Learning is a matter-of-fact kind of thing. It can not automatically adjust itself to correct the fact that previous managers failed to hire qualified females. Note that this is only a problem if the organization wants more females in its workforce. If it is happy hiring men as it did in the past, a machine learning model using the historical data will be acceptable.<br>Here in North America, historical discrimination and how it impacts life today is a sensitive topic. I’ll do my best to steer clear of saying anything controversial and attempt to focus on the use cases from an objective point of view.</p><p>To stay neutral and non-political, I will examine this issue from a broader perspective. As I mentioned, the term bias in this context is somewhat new to me, but the general idea that the historical record may not meet your current objective isn’t. That’s the core issue. Machine learning models can be problematic when organizations seek to achieve new goals that differ from the past.</p><p>Generally, there are three ways you can adjust your models when the current objectives differ from the historical data. One, you can monkey with the scoring data. Two, you can monkey with the modeling sample. Or, three, you can monkey with the output data.</p><p>Note that neither of these three fixes is perfect. Each is just a way to get actionable results in a less-than-ideal situation. Which method makes the most sense depends on the context of the problem.</p><p>I will be looking at two different use cases to highlight the methods of correcting bias. The first is new market expansion, a classic example of when the historical record does not reflect the current objectives of the business. The second is a discrimination example, where a particular group has had minimal access historically.</p><p>Note that all of the data used in this article are 100% fake. I created the data, and 100% own it.</p><h3><strong>1.0 Getting Setup</strong></h3><p><strong>1.1 Import Relevant Libraries.</strong></p><pre>import numpy.dual as dual<br>import pandas as pd<br>import numpy as np<br>import xgboost as xgb<br>from xgboost.sklearn import XGBClassifier<br>from sklearn import metrics</pre><pre>import xgboost as xgb<br>from sklearn.metrics import mean_squared_error</pre><pre>from IPython.display import Image<br>from IPython.core.display import HTML</pre><pre>#Un-Comment these options if you want to exapand the number of rows and columns of you see visually in the notebook.<br>#pd.set_option(&#39;display.max_columns&#39;, None)<br>#pd.set_option(&#39;display.max_rows&#39;, None)</pre><h3>2.0 New Market Expansion</h3><p>Barney BA and Associates (BBAA) operates a successful carpet cleaning business. Their business model is pretty simple. Their marketing budget is limited, and they have found great success by mailing coupons to prospects in the mail. Consumers open their mailbox, find a coupon, realize their carpets are dirty, and call BBAA for an appointment. Again, BBAA has a limited marketing budget, so they can not mail coupons to every household in their target market. They use a machine learning model to maximize their marketing dollars to predict which consumers are most likely to need a carpet cleaning. After constructing their machine learning model, they only mail to the top 30% of the prospects. Focusing on the 30% most likely to buy enables them to maximize their marketing expenditures.</p><p>Karma, Yuba, and Yarnaby are three suburban communities in a larger metro area. BBAA focuses on Yuba and Karma, but they are looking to expand into Yarnaby. Note that BBAA has not spent any marketing dollars in Yarnaby or focused on doing business in Yarnaby. They do have a few customers in Yarnaby, however. These customers come from referrals or customers who lived in either Karma or Yuba and moved to Yarnaby as a BBAA customers.</p><p>Consistent with their business model, BBAA would like machine learning to guide their market expansion.</p><p><strong>2.1 Import Data From GitHub</strong></p><pre>!rm markets.csv<br>!wget <a href="https://raw.githubusercontent.com/shadgriffin/ml_bias/main/markets.csv">https://raw.githubusercontent.com/shadgriffin/ml_bias/main/markets.csv</a><br>    <br>df = pd.read_csv(&quot;markets.csv&quot;, sep=&quot;,&quot;, header=0)</pre><p><strong>2.2 Examining the Data</strong></p><p>Let’s take a look at that the data</p><pre>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LjFmHWI358ZH85P_H8N_oA.png" /></figure><p>The dataset is pretty simple. Again, it is 100% fake.</p><p>CUST_ID — Unique Identifier of the prospect</p><p>THEPREDICTOR — This is the primary independent variable of the model.</p><p>MARKET — The market of the prospect. Can be Yuba, Yarnaby, or Karma</p><p>BUY — The dependent variable. A ‘1’ means the prospect purchased carpet cleaning in the past, a ‘0’ means they did not.</p><p>The three markets have about the same number of prospects.</p><pre>df_count = pd.DataFrame(df.groupby([&#39;MARKET&#39;])[&#39;BUY&#39;].count())<br>df_count</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*zdPCSK2KGCE0WySKgz_1Vw.png" /></figure><p>As expected, the conversion rate and the number of conversions in Yarnaby are much lower than in other markets.</p><p>Fewer conversions in Yarnaby is because BBAA has never focused on doing business there. If historically they have never tried to sell products in Yarnaby, they will not have many sales there. Building a model on historical data will not facilitate selling into a new market.</p><pre>df_count = pd.DataFrame(df.groupby([‘MARKET’])[‘BUY’].mean())<br>df_count</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*bKcQLbh-IABJBIJMSG3daA.png" /></figure><pre>df_count = pd.DataFrame(df.groupby([&#39;MARKET&#39;])[&#39;BUY&#39;].sum())<br>df_count</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*etl3GCvVZdvbNn_FcSn6uw.png" /></figure><p>So, we have three markets. Two markets are mature, and one is new, with few customers. Let’s see our prospect list if we build a machine learning model with the existing data. In the next section, we will create a machine learning model from the historical record and identify the top 30% of prospects that are likely to buy carpet cleaning. Once we have done this, we can mail them coupons in the mail.</p><p><strong>2.3 Machine Learning Model on the Raw Data</strong></p><p>Create a dummy variable that identifies prospects in Yarnaby. We will use this as an independent variable in the model.</p><pre>df[&#39;YARNABY&#39;] = np.where(((df.MARKET == &#39;Yarnaby&#39;)), 1, 0)</pre><p>Define the Independent and dependent variables.</p><pre>X=pd.DataFrame(df[[&#39;THEPREDICTOR&#39;,&#39;YARNABY&#39;]])<br>y=pd.DataFrame(df[&#39;BUY&#39;])</pre><p>Define the model</p><pre>xgb21 = XGBClassifier(objective = &#39;binary:logistic&#39;,use_label_encoder=False);</pre><p>Fit the model.</p><pre>xgb21.fit(X,y,eval_metric=&#39;auc&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nbNnFORquRRYmNyS6FZR1g.png" /></figure><p>Score the data and evaluate the accuracy.</p><pre>phat= xgb21.predict_proba(X);<br>yhat= xgb21.predict(X);<br>df_phat=pd.DataFrame(phat)<br>df_phat=df_phat.rename(columns={0: &quot;P_NOBUY&quot;, 1:&quot;P_BUY&quot;})<br>df_yhat=pd.DataFrame(yhat)<br>print(&quot;\nModel Report&quot;)<br>print(&quot;Accuracy : %.4g&quot; % metrics.accuracy_score(y, yhat))<br>print(&quot;AUC Score: %f&quot; % metrics.roc_auc_score(y, yhat))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*t0osRWSTEvpNl21V9lapcA.png" /></figure><p>Append the scores to the original data.</p><pre>dfx = pd.concat([df, df_phat], axis=1)</pre><p>Assign records to deciles. The firm will send coupons to the top 30%.</p><pre>dfx[&#39;bingbong&#39;] = (np.random.randint(0, 100, df.shape[0]))/100000000000000000</pre><pre>dfx[&#39;P_BUY&#39;]=(dfx[&#39;P_BUY&#39;]+dfx[&#39;bingbong&#39;])#*dfx[&#39;ADJUSTER&#39;]</pre><pre>#Create deciles based on P_BUY<br>dfx[&#39;DECILE&#39;] = pd.qcut(dfx[&#39;P_BUY&#39;], 10, labels=np.arange(100, 0, -10))</pre><p>Look at the accuracy of the model based on the deciles. (10 is the highest, 100 is the lowest.) The bulk or buyers are in the top deciles, which is good. Also, the distribution of prospects in the expansion market is weighted towards the lower deciles.</p><pre>df_sum = pd.DataFrame(dfx.groupby([&#39;DECILE&#39;])[&#39;BUY&#39;].sum())</pre><pre>df_count = pd.DataFrame(dfx.groupby([&#39;DECILE&#39;])[&#39;BUY&#39;].count())<br>df_mean = pd.DataFrame(dfx.groupby([&#39;DECILE&#39;])[&#39;BUY&#39;].mean())<br>df_phat = pd.DataFrame(dfx.groupby([&#39;DECILE&#39;])[&#39;P_BUY&#39;].mean())<br>dfx[&#39;Yarnaby&#39;] = np.where(((dfx.MARKET == &#39;Yarnaby&#39;)), 1, 0)<br>df_yarnaby = pd.DataFrame(dfx.groupby([&#39;DECILE&#39;])[&#39;Yarnaby&#39;].sum())</pre><pre>dfx.head()</pre><pre>df_out = pd.concat([df_mean, df_count,df_sum,df_yarnaby,df_phat], axis=1)</pre><pre>df_out.columns = [[&#39;Historical Conversion Rate&#39;, &#39;Total Prospects&#39;, &#39;Historical Conversions&#39;,&#39;Prospects in Yarnaby&#39;,&#39;Predicted Conversion Rate&#39;]]<br>df_out</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*82fOxfJu-FX4V_Ux2EWtBQ.png" /></figure><p>Identify the top 30% and examine the distribution across markets.</p><pre>dfx[&#39;DECILE&#39;]=dfx[&#39;DECILE&#39;].astype(int)<br>df_x=dfx[dfx[&#39;DECILE&#39;]&lt;=30]<br>df_count = pd.DataFrame(df_x.groupby([&#39;MARKET&#39;])[&#39;BUY&#39;].count())<br>df_count</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*XIvYMSrKJCBACEiyjdfmIw.png" /></figure><p>See the problem? The historical data has almost no sales from Yarnaby, and without doing something, they never will. It becomes a “self-fulfilling prophecy”. If you use historical sales to predict future sales, you will never have many sales in a new market.</p><p>Unless we do something here, we will never be successful in our new market.</p><p><strong>2.4 Monkey with the Scoring Data</strong></p><p>The most straightforward thing to do here is to apply the model to Yarnaby but pretend that the prospects are either in Yuba or Karma. That is, recode the “YARNABY” variable so that all records (even those in Yarnaby) have a value of 0. Changing the market of the Yarnaby records means that when you apply the model, we will score every record as if it was in Yuba or Karma, even if it isn’t.</p><pre>df[&#39;YARNABY&#39;]=0</pre><pre>#Define the independent and dependent variable.<br>X=pd.DataFrame(df[[&#39;THEPREDICTOR&#39;,&#39;YARNABY&#39;]])<br>y=pd.DataFrame(df[&#39;BUY&#39;])</pre><pre>#Score the data <br>phat= xgb21.predict_proba(X);</pre><pre>df_phat=pd.DataFrame(phat)<br>df_phat=df_phat.rename(columns={0: &quot;P_NOBUY&quot;, 1:&quot;P_BUY&quot;})</pre><pre>#Append the scores to the original data</pre><pre>dfx = pd.concat([df, df_phat], axis=1)<br>#Assign records to deciles. The firm will send coupons to the top 30%.<br>dfx[&#39;bingbong&#39;] = (np.random.randint(0, 100, df.shape[0]))/100000000000000000</pre><pre>dfx[&#39;P_BUY&#39;]=(dfx[&#39;P_BUY&#39;]+dfx[&#39;bingbong&#39;])</pre><pre>#Identify the top 30% and examine the distribution across markets.<br>dfx[&#39;DECILE&#39;] = pd.qcut(dfx[&#39;P_BUY&#39;], 10, labels=np.arange(100, 0, -10))<br>dfx[&#39;DECILE&#39;]=dfx[&#39;DECILE&#39;].astype(int)<br>df_x=dfx[dfx[&#39;DECILE&#39;]&lt;=30]<br>df_count = pd.DataFrame(df_x.groupby([&#39;MARKET&#39;])[&#39;BUY&#39;].count())<br>df_count</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*0keJ1Cn1xOdi_0hh3y7FpA.png" /></figure><p>The results of Monkeying with the scoring data appear above. Note there are now a significant number of prospects in Yarnaby.</p><p>A word of caution, however. This method assumes that all market factors exist in one variable and that by changing the variable, you can remove all of the market effects. In practice, this is rarely the case. Data used as inputs in a machine learning model are almost always correlated. In classical regression methods, we call this collinearity or multi-collinearity. So, even if you change the market for Yarnaby prospects, there will likely be some lingering market effect in other variables. A good example is household income. Income and market are typically collinear, given that households with similar incomes tend to live by one another.</p><p>Also, it is essential to point out that the viability of the Yarnaby market is unknown. We are making a pretty big assumption that it is as viable as the other markets, but BBAA won’t know that until they start selling in the market.</p><p>This use case is what I would refer to as a batch use case. That is, we are scoring the complete set of prospects and then taking action by focusing on the top 30%. Sometimes your deployment would be what I would call real-time. That is, you will need to take action on a single prospect without the benefit of aggregating a larger cohort. For example, you could be deploying this model in an application that scores prospects one at a time instead of thousands at a time.</p><p>Monkeying with the scoring data lends itself to a real-time deployment, given that the scores for all three markets are comparable. In other words, the average score or predicted value will be about the same across all three markets. Or, a good prospect will have roughly the same value, regardless of their market.</p><p><strong>2.5 Monkey with the Model Sample</strong></p><p>Another way to address this problem is to resample the original data before building any machine learning model. Again, this is not perfect but does make sense in some situations. Currently, the historical purchase rate for Yarnaby is substantially lower than the other two markets. If we resample Yarnaby to have a similar historical purchase rate, a model should reflect this when applied to prospect data.</p><p>Read in the csv.</p><pre>df = pd.read_csv(&quot;markets.csv&quot;, sep=&quot;,&quot;, header=0)</pre><p>Create a dummy variable for records in Yarnaby.</p><pre>df[&#39;YARNABY&#39;] = np.where(((df.MARKET == &#39;Yarnaby&#39;)), 1, 0)</pre><p>Put the records in random order.</p><pre>df[&#39;loopy&#39;] = (np.random.randint(0, 1000, df.shape[0]))/1000<br>df=df.sort_values(by=[&#39;loopy&#39;])<br>df=df.reset_index(drop=True)</pre><p>Create a separate data frame for each market based on the “Buy” variable.</p><pre>dfyarnb=df[(df[&#39;MARKET&#39;]==&#39;Yarnaby&#39;) &amp; (df[&#39;BUY&#39;]==1)]<br>dfyarnn=df[(df[&#39;MARKET&#39;]==&#39;Yarnaby&#39;) &amp; (df[&#39;BUY&#39;]==0)]<br>dfyubab=df[(df[&#39;MARKET&#39;]==&#39;Yuba&#39;) &amp; (df[&#39;BUY&#39;]==1)]<br>dfyuban=df[(df[&#39;MARKET&#39;]==&#39;Yuba&#39;) &amp; (df[&#39;BUY&#39;]==0)]<br>dfkarmab=df[(df[&#39;MARKET&#39;]==&#39;Karma&#39;) &amp; (df[&#39;BUY&#39;]==1)]<br>dfkarman=df[(df[&#39;MARKET&#39;]==&#39;Karma&#39;) &amp; (df[&#39;BUY&#39;]==0)]</pre><p>For each Buyer in each market, randomly select 20 non-buyers. The conversion rate will be the same for each market in our new data frame.</p><pre>a=(dfyarnb[&#39;CUST_ID&#39;].count())*20<br>b=(dfyubab[&#39;CUST_ID&#39;].count())*20<br>c=(dfkarmab[&#39;CUST_ID&#39;].count())*20</pre><pre>dfyarnn=dfyarnn.sort_values(by=[&#39;loopy&#39;])</pre><pre>dfyarnn=dfyarnn.head(a)<br>dfyuban=dfyuban.head(b)<br>dfkarman=dfkarman.head(c)</pre><p>Concatenate the adjusted data frames into a complete data frame.</p><pre>dfz = pd.concat([dfyarnn, dfyarnb, dfyuban, dfyubab, dfkarman, dfkarmab])</pre><p>Reset the Indexes.</p><pre>dfz=dfz.sort_values(by=[‘CUST_ID’])<br>dfz=dfz.reset_index(drop=True)</pre><pre>df=df.sort_values(by=[‘CUST_ID’])<br>df=df.reset_index(drop=True)</pre><p>The original dataframe has 162,889 records.</p><pre>df.shape</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*-s-u3YKVYihggIB6gprSCg.png" /></figure><p>The new data frame with a consistent conversion rate in each market has 95,319 records.</p><pre>dfz.shape</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*7KKzbVmP6MAfmQbJilCDxQ.png" /></figure><p>Note, now all markets have the same conversion rate.</p><pre>zss = pd.DataFrame(dfz.groupby([&#39;MARKET&#39;])[&#39;BUY&#39;].mean())<br>zss</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*6OHaMJM9ei8mXtOu_-QVsg.png" /></figure><p>Define the dependent and independent variables for the modeling and scoring data set. Note that we will build the model on the data frame with the adjusted sample, and we will apply that model to the complete record data set.</p><pre>#Define the scoring data set<br>X=pd.DataFrame(df[[&#39;THEPREDICTOR&#39;,&#39;YARNABY&#39;]])<br>y=pd.DataFrame(df[&#39;BUY&#39;])<br>#Define the modeling data set<br>X1=pd.DataFrame(dfz[[&#39;THEPREDICTOR&#39;,&#39;YARNABY&#39;]])<br>y1=pd.DataFrame(dfz[&#39;BUY&#39;])</pre><p>Define the model, fit the model, score the model and examine the results.</p><pre>#Define the Model<br>xgb21 = XGBClassifier(objective = ‘binary:logistic’,use_label_encoder=False);<br>#Fit the Model to the adjusted sample<br>xgb21.fit(X1,y1,eval_metric=’auc’)<br>#apply or score the model against the original dataframe<br>phat= xgb21.predict_proba(X);<br>#write to a dataframe<br>df_phat=pd.DataFrame(phat)<br>#Rename the columns in the scored data set<br>df_phat=df_phat.rename(columns={0: “P_NOBUY”, 1:”P_BUY”})<br>#concatenate the scored data to the original non-augmented data frame.<br>dfx = pd.concat([df, df_phat], axis=1)<br>#Examine the results<br>dfx.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qRS_mN5MyDAYFexKbG0KJQ.png" /></figure><p>Evaluate the accuracy on the original data.</p><pre>#Evaluate the accuracy of the model built on the augmented data on the original data<br>yhat= xgb21.predict(X);</pre><pre>df_yhat=pd.DataFrame(yhat)<br>print(&quot;\nModel Report&quot;)<br>print(&quot;Accuracy : %.4g&quot; % metrics.accuracy_score(y, yhat))<br>print(&quot;AUC Score: %f&quot; % metrics.roc_auc_score(y, yhat))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*SAjfjrA2QfH_GxguQW6gqQ.png" /></figure><p>Place the newly scored records into deciles.</p><pre>#assign a tiny random number to the probability to brake ties<br>dfx[&#39;bingbong&#39;] = (np.random.randint(0, 100, dfx.shape[0]))/100000000000000000</pre><pre>dfx[&#39;P_BUY&#39;]=(dfx[&#39;P_BUY&#39;]+dfx[&#39;bingbong&#39;])</pre><pre>#Create deciles based on P_BUY<br>dfx[&#39;DECILE&#39;] = pd.qcut(dfx[&#39;P_BUY&#39;], 10, labels=np.arange(100, 0, -10))</pre><p>Select the top 3 deciles. Examine the Market Distribution.</p><pre>dfx[&#39;DECILE&#39;]=dfx[&#39;DECILE&#39;].astype(int)<br>df_x=dfx[dfx[&#39;DECILE&#39;]&lt;=30]<br>df_count = pd.DataFrame(df_x.groupby([&#39;MARKET&#39;])[&#39;BUY&#39;].count())<br>df_count</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*qdxV-potBERDiD4s9cFNTw.png" /></figure><p>Note the distribution of the top 3 deciles across the various markets. The number of records in each market is about the same, roughly anyway.</p><p>Yarnaby has a few thousand more than either Karma or Yuba. There are a few reasons this could happen. One, it is possible that Yarnaby is a better market than the other two, and as BBAA starts selling in Yarnaby, they will realize better sales than in their existing markets. While that is possible, I kind of doubt that to be the case here. An issue with this method is that we rely on sampling to balance the conversion rates between the markets. Sample, as you know, comes with sampling error. My guess is that if we select a different random selection of records, the results might look different.</p><p>Again, we don’t know for sure because we don’t know the actual conversion rate in Yarnaby. We assume that it will be the same as it is in the other two markets.</p><p>Like the previous example above, this method lends itself to real-time scoring, given that the model output is mostly comparable across the three markets.<br>This method also lends itself to situations when you need to resample your data anyway. For example, if you have a tiny (less than 1%) purchase rate, you may decide need to balance the data to get a more predictive model.</p><h3>3.0 Historical Discrimination</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lBri4XGeea9KBETY0PSJzQ.png" /><figcaption>Basset hound disguising itself as a tiger so he can get a bath from Ed.</figcaption></figure><p>Ed and Son’s Dog Bathing Incorporated is dedicated to cleaning canines in the tri-state area. Ed started the business thirty years ago and added his son as a business partner twelve years ago. Ed, getting up in age, is now looking to retire. Once he retires, his son Elmo will continue the family business for another generation.</p><p>Ed’s business includes all breeds of dogs except for one, the Basset Hound. Ed hates basset hounds. He thinks they are stubborn, their ears are too long, and they insist on stealing humans’ food. He just doesn’t like basset hounds. In fact, you could say Ed has actively discriminated against basset hounds in his thirty years of dog washing, refusing to do business with them.</p><p>Now that Ed is heading into retirement, Elmo is looking to expand the business. One easy way to grow the market is to start bathing basset hounds. Another way Elmo plans to grow the company is to use a machine learning model to identify prospects for dog washing in the tri-state area. Elmo will use historical data to understand who purchased dog washes in the past and then use this learning to find new prospects. Elmo plans to apply a model to the universe of candidates, then call the top 30% to see if they want a dog wash.</p><p><strong>3.1 Pull in the data from GitHub.</strong></p><pre>!rm breeds.csv<br>!wget <a href="https://raw.githubusercontent.com/shadgriffin/ml_bias/main/breeds.csv">https://raw.githubusercontent.com/shadgriffin/ml_bias/main/breeds.csv</a><br>    <br>df = pd.read_csv(&quot;breeds.csv&quot;, sep=&quot;,&quot;, header=0)</pre><p><strong>3.2 Examine the results</strong></p><p>The dataset is pretty simple. Again, it is 100% fake.</p><p>CUST_ID — Unique Identifier of the prospect</p><p>THEPREDICTOR — This is the primary independent variable of the model.</p><p>BREED — The breed of the prospect. It can be Basset Hound or Other.</p><p>BUY — The dependent variable. A ‘1’ means the prospect purchased dog washing in the past; a ‘0’ means they did not.</p><pre>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*IdCS-GtAhC6s-yRIuzTNMg.png" /></figure><p>Looking at the historical data, it is evident that basset hounds have not been a priority. There is only fourteen basset hound customers in the historical data. More than likely a mixed-breeds.</p><pre>df[&#39;wookie&#39;]=1</pre><pre>df_count = pd.DataFrame(df.groupby([&#39;BREED&#39;,&#39;wookie&#39;])[&#39;BUY&#39;].count())<br>df_sum = pd.DataFrame(df.groupby([&#39;BREED&#39;,&#39;wookie&#39;])[&#39;BUY&#39;].sum())<br>df_predictor = pd.DataFrame(df.groupby([&#39;BREED&#39;,&#39;wookie&#39;])[&#39;THEPREDICTOR&#39;].mean())<br>df_total = pd.DataFrame(df.groupby([&#39;wookie&#39;])[&#39;BUY&#39;].count())</pre><pre>df_count=df_count.rename(columns={&quot;BUY&quot;: &quot;Total Prospects&quot;})<br>df_sum=df_sum.rename(columns={&quot;BUY&quot;: &quot;Buyers&quot;})<br>df_total=df_total.rename(columns={&quot;BUY&quot;: &quot;All Breeds&quot;})</pre><pre>df_out = pd.concat([ df_count,df_sum,df_predictor], axis=1)</pre><pre>df_total=df_total.reset_index()<br>df_out=df_out.reset_index()</pre><pre>df_out = pd.merge(df_out, df_total, on=&quot;wookie&quot;)<br>df_out[&#39;Conversion Rate&#39;]=df_out[&#39;Buyers&#39;]/df_out[&#39;Total Prospects&#39;]<br>df_out[&#39;Percent of Prospects&#39;]=df_out[&#39;Total Prospects&#39;]/df_out[&#39;All Breeds&#39;]<br>df_out[&#39;Conversion Rate&#39;]=df_out[&#39;Buyers&#39;]/df_out[&#39;Total Prospects&#39;]</pre><pre>df_out=df_out.drop(columns=&#39;wookie&#39;)<br>df_out</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GrFOCwo683IdgBEsudDZ6A.png" /></figure><h4><strong>3.3 Build a Machine Learning Model to predict the best prospects.</strong></h4><p>Create a dummy variable to identify Basset Hounds.</p><pre>df[&#39;BASSET&#39;] = np.where(((df.BREED == &#39;Basset Hound&#39;)), 1, 0)</pre><p>Define the independent and dependent variables.</p><pre>X=pd.DataFrame(df[[&#39;THEPREDICTOR&#39;]])<br>y=pd.DataFrame(df[&#39;BUY&#39;])</pre><p>Define, fit and score the model.</p><pre>xgb21 = XGBClassifier(objective = &#39;binary:logistic&#39;,use_label_encoder=False);<br>xgb21.fit(X,y,eval_metric=&#39;auc&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*asvCTr3zj-FWKv3De1u-nA.png" /></figure><pre>#Score the original data with the model<br>phat= xgb21.predict_proba(X);<br>#Put the results in a dataframe<br>df_phat=pd.DataFrame(phat)<br>#add Variable lablels<br>df_phat=df_phat.rename(columns={0: &quot;P_NOBUY&quot;, 1:&quot;P_BUY&quot;})<br>#append values to the original data<br>dfx = pd.concat([df, df_phat], axis=1)</pre><p>Evaluate the accuracy of the model</p><pre>yhat= xgb21.predict(X);</pre><pre>df_yhat=pd.DataFrame(yhat)<br>print(&quot;\nModel Report&quot;)<br>print(&quot;Accuracy : %.4g&quot; % metrics.accuracy_score(y, yhat))<br>print(&quot;AUC Score: %f&quot; % metrics.roc_auc_score(y, yhat))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*a8SY24JePwfYyLdD6f9Kjg.png" /></figure><p>Place the records in Deciles</p><pre>#Add a tiny random number to the probability to break ties<br>dfx[&#39;bingbong&#39;] = (np.random.randint(0, 100, df.shape[0]))/100000000000000000</pre><pre>dfx[&#39;P_BUY&#39;]=(dfx[&#39;P_BUY&#39;]+dfx[&#39;bingbong&#39;])</pre><pre>#Create deciles based on P_BUY<br>dfx[&#39;DECILE&#39;] = pd.qcut(dfx[&#39;P_BUY&#39;], 10, labels=np.arange(100, 0, -10))</pre><p>Evaluate the deciles. The model does an excellent job of identifying prospects, but note that all the basset hounds are weighted toward the bottom deciles.</p><pre>df_sum = pd.DataFrame(dfx.groupby([&#39;DECILE&#39;])[&#39;BUY&#39;].sum())<br>df_count = pd.DataFrame(dfx.groupby([&#39;DECILE&#39;])[&#39;BUY&#39;].count())<br>df_mean = pd.DataFrame(dfx.groupby([&#39;DECILE&#39;])[&#39;BUY&#39;].mean())<br>df_phat = pd.DataFrame(dfx.groupby([&#39;DECILE&#39;])[&#39;P_BUY&#39;].mean())<br>dfx[&#39;BASSET&#39;] = np.where(((dfx.BREED == &#39;Basset Hound&#39;)), 1, 0)<br>df_yarnaby = pd.DataFrame(dfx.groupby([&#39;DECILE&#39;])[&#39;BASSET&#39;].sum())</pre><pre>df_out = pd.concat([df_mean, df_count,df_sum,df_yarnaby,df_phat], axis=1)<br>df_out</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*Yrhm2wAMQP5_U82PDCKpIg.png" /></figure><p>Select on the top 3 deciles.</p><pre>dfx[&#39;DECILE&#39;]=dfx[&#39;DECILE&#39;].astype(int)<br>df_x=dfx[dfx[&#39;DECILE&#39;]&lt;=30]</pre><p>Evaluate the distribution of top records by breed.</p><p>There are not many basset hounds in the top three deciles. Again, hopefully, the problem is apparent. The machine learning model doesn’t know Ed actively discriminated against basset hounds. It has no way to know this. If you use the historical data to identify the best prospects, basset hounds will never make the cut. This isn’t because they are perpetually clean. It is because they were discriminated against in the historical data.</p><pre>df_count = pd.DataFrame(df_x.groupby([‘BREED’])[‘THEPREDICTOR’].count())<br>df_count</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*h2mmiojwe-9L1mRfr0sYOQ.png" /></figure><p><strong>3.4 Monkey with the Output Data.</strong></p><p>Previously, we examined ways of dealing with situations where your historical data does not reflect your current objectives. We saw how you could alter the data or the sample to bring the machine learning model closer to what you hope to achieve. Another approach is to monkey with the output data. In this case, you build the machine learning model on the original data but then change how you use it. Below is a concrete example of how to do this.</p><p>Take the data from the model and separate each breed into a different data frame.</p><pre>df_boogie=dfx[[&#39;CUST_ID&#39;,&#39;P_BUY&#39;,&#39;BREED&#39;,&#39;BUY&#39;]]</pre><pre>df_b=df_boogie[df_boogie[&#39;BREED&#39;]==&#39;Basset Hound&#39;].copy()<br>df_e=df_boogie[df_boogie[&#39;BREED&#39;]!=&#39;Basset Hound&#39;].copy()</pre><p>Remember, the goal is to contact 30% of the prospects. Note that Basset Hounds represent about 11% of the total population. Here is how to ensure that Bassets reflect about 11% of the final targeted prospect file.</p><p>Assign deciles within each breed.</p><pre>df_b[&#39;DECILE&#39;] = pd.qcut(df_b[&#39;P_BUY&#39;], 10, labels=np.arange(100, 0, -10))<br>df_e[&#39;DECILE&#39;] = pd.qcut(df_e[&#39;P_BUY&#39;], 10, labels=np.arange(100, 0, -10))</pre><pre>df_b[&#39;DECILE&#39;]=df_b[&#39;DECILE&#39;].astype(int)<br>df_e[&#39;DECILE&#39;]=df_e[&#39;DECILE&#39;].astype(int)</pre><p>Append the records back together into one dataframe.</p><pre>df_boogie = pd.concat([df_b, df_e])</pre><p>Select the top 3 deciles.</p><pre>df_boogie=df_boogie[df_boogie[&#39;DECILE&#39;]&lt;=30]</pre><p>Examine the results.</p><pre>df_count = pd.DataFrame(df_boogie.groupby([&#39;BREED&#39;])[&#39;P_BUY&#39;].count())<br>df_count</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*83WKmD3rw7LLOqVMf2udcw.png" /></figure><p>Using the method above, we can ensure that Basset Hounds are represented proportionally to their presence in the original prospect file, even though they have experienced historical discrimination.</p><p>What we are doing in this latest example is establishing a quota. The methodology above will ensure that the at-risk group is represented proportionally to their presence in the population. You could easily change this so that Basset Hounds represent 1%, 30%, or 50% of the targeted group. Again, it just depends on your objective.</p><p>Monkeying with the output is another way to correct situations where the historical record does not reflect how you want to do business today. This method could make sense if you are looking for exact numbers. For example, you want 20% of the final targeted list to be basset hounds. This method also lends itself to batch deployments, given that you have to aggregate the data to know how to adjust it.</p><h3>4.0 Conclusion</h3><p>This article has laid out scenarios where building a machine learning model on your historical data will not meet your current business objectives. Some call this bias. If you encounter bias, you have a problem with your data, and there is no sure-fire way to fix data that is missing something you need. This article presented three ways to deal with Bias. Hopefully, I made clear how you can use these techniques to minimize the impact of this kind of problem.</p><p>As far as which of the three techniques is best, it is tough to say. It depends on the specific problem you are looking to solve. I would say that generally, if you are looking to deploy your model in real-time via an application, then the first two mentioned in the article are probably the best. Those being monkeying with the scoring data and monkeying with the model sample. The third (Monkeying with the output data) is probably the best if you are doing a batch deployment. Again, it depends on your objectives and the size of the gap in the historical data. I’d suggest a bit of trial and error with all three methods.</p><p>For what is worth, truth be told, I LOVE Basset Hounds. They are my favorite breed. How can you not love a basset? I’ve had three over the course of my lifetime. I think I was a Basset Hound in a previous life.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*zvuGv4TJ-RHO7Xi-UJSSZQ.png" /><figcaption>Lightning the Basset Hound 1999–2008</figcaption></figure><p>I hope this was helpful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8795403ea1c7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/understanding-bias-in-modern-machine-learning-8795403ea1c7">Machine Learning with Biased Data</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>