<?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 Rodrigo Salles on Medium]]></title>
        <description><![CDATA[Stories by Rodrigo Salles on Medium]]></description>
        <link>https://medium.com/@brdata?source=rss-6dedcc6de1a6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*E3HFgaaCsYJtfndJQJIKDg.jpeg</url>
            <title>Stories by Rodrigo Salles on Medium</title>
            <link>https://medium.com/@brdata?source=rss-6dedcc6de1a6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 17:58:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@brdata/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[Tax collection forecast for Minas Gerais — Brazil]]></title>
            <link>https://medium.com/brdata/tax-collection-forecast-for-minas-gerais-brazil-7c059b91d1d1?source=rss-6dedcc6de1a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c059b91d1d1</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[sarima]]></category>
            <category><![CDATA[arima]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[icms]]></category>
            <dc:creator><![CDATA[Rodrigo Salles]]></dc:creator>
            <pubDate>Thu, 28 Jan 2021 18:53:38 GMT</pubDate>
            <atom:updated>2021-01-29T15:31:22.472Z</atom:updated>
            <content:encoded><![CDATA[<h3>Tax collection forecast for Minas Gerais — Brazil</h3><p>Tax collection forecast for the State of Minas Gerais — Brazil</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uyP9oqZ1Hbx_do88PG8ZhQ.jpeg" /><figcaption>Photo by Marcelo Casal Jr(Agência Brasil)</figcaption></figure><p>One of the interests of the economic sciences is to make efficient predictions of variables that play a central role in decision making by economic agents. To plan the contribution of resources, governments need to have a tax collection forecast, and in Brazil the tax on the circulation of goods and services (ICMS) represents an important source of funds.</p><p>ICMS represents an important source of funds for the State of Minas Gerais. Located in the Southeast region of Brazil, it is the second most populous state in the country, with approximately 20.7 million inhabitants, and is composed of 853 municipalities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*9qx6n2Cw469Y3wyr.jpg" /><figcaption>Belo Horizonte(<a href="https://pt.wikipedia.org/wiki/Belo_Horizonte">https://pt.wikipedia.org/wiki/Belo_Horizonte</a>)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*3NNB7IqyzKeJRE19.jpg" /><figcaption>Minas Gerais(<a href="https://pt.mapsofworld.com/brasil/estados/minas-gerais.html">https://pt.mapsofworld.com/brasil/estados/minas-gerais.html</a>)</figcaption></figure><p>In a state with such dimensions, efficient resource management is extremely important, and to assist in this task, all possible tools must be used. And in this context, time series can be of great value in revenue forecasts.</p><p>This study was developed in R, and the code used can be found <a href="https://github.com/RodrigoSalles">here</a>.</p><h3>Materials and methods</h3><p>The data used are for public use, made available by the Institute for Applied Economic Research (IPEA), and the analyzes were made in R language, with the help of RStudio software.</p><p>The series consists of 276 monthly observations, between the periods of January 1993 and December 2015. Each month has the value of ICMS collection for the State of Minas Gerais. A sample of the data can be seen in the following table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*RVC1oPQ2SA1uUZXWmYrw4w.png" /></figure><p>The methodology adopted consists of first carrying out an exploratory analysis of the data, verifying trends, cycles and seasonality effects. Then tests will be performed to check the stationarity of the series. If necessary, transformations will be made to make the series stationary. Then, several models will be analyzed, and the models that best fit the data will be chosen. Finally, the chosen models will be used to make predictions about the adopted series.<br>The results will be compared in relation to the absolute errors verified in the forecasts.</p><h3>Exploratory Data Analysis</h3><p>As previously explained, the series consists of observations of the amount collected by ICMS in the State of Minas Gerais. The data begins with the value for the month of January 1993, and ends with the collection for the month of December 2015.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*M3G87kWiOug-Juhl0whtxA.png" /></figure><p>Some statistical information of the series can be seen in the following table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*qqqwv4msSMXBFpArJH20lQ.png" /></figure><p>The previous graph shows that the series has an increasing trend, and thus it can be concluded that it is not stationary. It is also noted that the variance is not constant, and the series has shown a particularly turbulent behavior in recent years. This behavior can be partially explained by the economic crisis that the country was going through during that period.<br>The graph of the autocorrelation function, which can be seen in the following graph, shows the typical shape of a non-stationary series.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*7M0TLfVhAPX1rWdmPWk68A.png" /></figure><p>The autocorrelation function decreases very slowly to zero, indicating the effects of the trend and possibly seasonality.<br>The non-stationarity of the series can be confirmed by the unit root test:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*p9RvLFMyUx5Uj-YWLtVZCA.png" /></figure><p>The Augmented Dickey-Feller test works with the null hypothesis of the existence of a unit root, the series being non-stationary. It can be seen that the p-value has a value above 0.05 (level of significance), so the test indicates that the series is not stationary.</p><p>One more test can be applied to confirm non-stationarity. The Kwiatkowski-Phillips-Schmidt (KPSS) test adopts as a null hypothesis that the series is stationary. The result applied to the ICMS series is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*7B9QFlITOGhI07sl1iySlg.png" /></figure><p>The p-value of 0.01 indicates the rejection of the null hypothesis, and thus, according to the test, the series is not stationary.</p><h3>Time series stationarity</h3><p>Stationarity is an important characteristic because it indicates that probabilistic and statistical properties of the time series remain unchanged over time.<br>The tests applied previously indicate that the series is not stationary, and therefore, we must resort to some transformations to achieve the objective of making the series stationary.<br>Assuming an additive model, the series can be broken down into its seasonal, random and trend components. This decomposition can be seen in the following figure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*1KP-C5j0lcdvCJb3hr9MGA.png" /></figure><p>When analyzing the decomposition of the series, it is possible to notice a strong trend component, and an effect relative to seasonality that is practically negligible.<br>Taking into account the previous results, differentiation of the series will be used to try to achieve stationarity.<br>The <em>ndiffs</em> function tells us the number of differentiations needed. When applying this function to the series, we have the indication that only one differentiation is enough. There is also the <em>nsdiffs</em> function, which indicates the number of seasonal differentiations required. When applying the <em>nsdiffs</em> function, we have zero as a return, which confirms the initial analyzes of a negligible seasonal effect.</p><h3>Building the forecasting models</h3><p>To start modeling, a first differentiation was carried out, as previously suggested. The result of the autocorrelation and partial autocorrelation function can be seen in the figures below, where the ACF values fall rapidly to the region close to zero.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*nN1ZiRzoKA1AH2DLQ2rGgQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*SaHNtaAFPADC7r2vxKFpRQ.png" /></figure><p>The unit root test has a low p-value, confirming that a differentiation was, in fact, sufficient to make the series stationary:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*Yq715JaNheaaEcgpF1SZLA.png" /></figure><p>The KPSS test, with a p-value above 0.05, indicates that the null hypothesis that the series is stationary cannot be rejected:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*ct5IVtVQ3Qm2x2sYwcs_WQ.png" /></figure><p>To start the tests with the models, the <em>auto.arima</em> function will initially be used to determine the arima model that best fits the series. The result obtained was an ARIMA model (1,1,1) with drift. The model confirms the need for differentiation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*NINVSxRZHL5tu1b9Ox70qA.png" /></figure><p>The following figure shows the AIC and BIC parameters for model evaluation. In the same figure you can see that the parameters found <strong>ar1</strong> and <strong>ma1</strong> are statistically significant:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*IpYcQSCUKzxVoMHmCZjAPA.png" /></figure><p>From the analysis of the figure below, it can be concluded that the residues are not correlated, they are independent and identically distributed. Despite the form presented by the Q-Q graph, it can be said that this model fits well with the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*PUPy9NSYVE8K6p9hnNi13w.png" /></figure><p>In order to make comparisons and possibly obtain better models, it was decided to perform several tests, with different AR and MA parameters, but always maintaining a differentiation (d = 1). The results obtained were grouped in the following table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*4ZmfNS6jyZkhkjiell1IcQ.png" /></figure><p>In the previous table you can see the values of AIC and BIC for the model, obtained by the <em>auto.arima</em> function. The ARIMA model (3,1,3) obtained the lowest values of AIC and BIC.</p><p>An analysis of the parameters and residues of the ARIMA model (3,1,3) can be seen in the figure below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*fgA78r8vzQqtB1KhaEusJw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*6CieCyDp3-_kuqQWhI3Uug.png" /></figure><p>The graph in the figure above suggests that the parameters are statistically significant, the residues are not correlated, they are independent and identically distributed. Despite the shape presented by the Q-Q graph, in which the extremes deviate from normality.</p><h3>Model with seasonality effects</h3><p>Despite the indication of the insignificance of the effects of seasonality, a test was carried out with a model including this effect.</p><p>The model found was ARIMA (1,1,1) x (2,0,1)_12. Other possibilities were tested, but there were problems related to the stationarity of the seasonal AR part.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*PDJZT6vq1XqgBKD5mlxjSw.png" /></figure><p>It can be seen that the term <strong>sar2</strong>, with p-value above 0.05 is not statistically significant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*kRUnlvE4SqptEWnCr2QFEw.png" /></figure><p>Residue analysis shows some problems. The autocorrelation graph shows some values outside the limits, and the p-value for the Ljung-Box test shows oscillation and high values in relation to the proximity to zero.</p><h3><strong>Model with Box Cox transformation</strong></h3><p>To finish analyzing the possibilities of the Arima models, a model was considered in which the data underwent a Box Cox transformation.</p><p>By looking at the graph of the original series, one can see a possible variance problem. To try to stabilize variance, a Box Cox transformation was used. The value of <strong>λ</strong> was obtained with the aid of the <em>BoxCox.lambda ()</em> function, and the value found was 0.5993. This value was used, together with the <em>arima ()</em> function, to produce the forecasts.</p><p>In the following figure, the analysis suggests that the residues are not correlated:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*hTJd8VJhwxLtgAJ6SEdSyw.png" /></figure><h3>Forecasts</h3><p>The previously adjusted models will be used to make predictions about the collection of ICMS for the year 2016. The real values for that year are known and will be used for performance evaluation. Another model, which combines predictors, will also be evaluated. The absolute error will be calculated in each forecast, in order to compare the performances.</p><h4>ARIMA model (1,1,1) with drift</h4><p>The first model used will be ARIMA (1,1,1), with drift, automatically adjusted by the <em>auto.arima</em> function. In the figure below you can see the graph related to the model.<br>The model seems to capture the variation form of the series. The errors associated with the forecast can be seen in the following table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*mZNt961LNjGMCHSf7jGiFg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*9jM-Gw6JCadqFAsM8WZiZQ.png" /></figure><p>It can be seen that the smallest error was related to the month of March, and the biggest error occurred in the last month, December, with a value close to 15%. The average absolute error for that year was 5.15%.</p><h4>ARIMA model (3,1,3) with drift</h4><p>The next model tested was the ARIMA (3,1,3) manually adjusted. In the next graph it can be seen that the model seems to capture the pattern of change in the series.<br>In the sequence, the table shows the observed values, real, and the predicted values for each month, as well as the error associated with each forecast.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*psBonQ-qNaGUXNuWEbNx8w.png" /><figcaption>ARIMA(3,1,3)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*nt3iDbxzse8bgQQcU9_nmQ.png" /></figure><p>Similar to the ARIMA model (1,1,1), the smallest error found was for the month of March, and the highest, for the month of December. The average absolute error was 5.08%.</p><h4>Model with seasonality ARIMA (1,1,1) x (2,0,1)_12</h4><p>The forecasts for a model that considers seasonality can be seen in the following graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*TZDGBUP1BAD2Jm3-s2nbIg.png" /><figcaption>ARIMA (1,1,1) with seasonality</figcaption></figure><p>The predictions made, and the model errors can be seen in the following table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*TIx09sdtgDjw_QwkchHo3w.png" /></figure><p>It can be seen that the smallest error was related to the month of August, and the biggest error occurred in the last month, with a value close to 15%. The average absolute error for this model was 5.41%.</p><h4>Model with Box Cox transformation</h4><p>The forecast graph and performance tables for the model that used the Box Cox transformation, can be seen below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*6koP9-KHE19iFee08CP2dA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*GEHOYCea1YA_sPB7-cgmIg.png" /></figure><p>The average absolute error for the predictor with the Box Cox transformation was 6.14%, the smallest error being verified for the month of February, and the largest, like the previous models, was for the month of December.</p><p>The next model tested will be the combination of predictors.</p><h4>Combination of predictors</h4><p>An interesting possibility to improve the performance of forecasts is the combination of forecasts. Each predictor produces a result, for the same series, and the end result is a combination of the individual results.<br>To try to approximate the value of ICMS for the year 2016, the following models were chosen: ETS, ARIMA and TBATS. As the ARIMA models have already been explained previously, the ETS and TBATS models will be briefly commented.</p><h4>ETS (Error, Trend, seasonal)</h4><p>Exponential smoothing is a method of forecasting time series for univariate data.<br>Time series methods such as the Box-Jenkins family of methods develop a model in which the forecast is a weighted linear sum of recent observations or delays.</p><p>The exponential smoothing forecasting methods are similar in that a forecast is a weighted sum of past observations, but the model explicitly uses a decreasing weight for past observations. Collectively, the methods are sometimes called ETS models, referring to modeling based on Error, Trend and Seasonality.</p><h4>TBATS</h4><p>The BATS model is an exponential smoothing method combined with Box-Cox transformation and ARMA model. The Box-Cox transformation is intended to handle non-linear data. Alysha M. (2010) demonstrated that the BATS model can improve the performance of predictions compared to a simple state space model.</p><p>BATS models do not do well when the series has high frequencies, so Alysha M. (2011) proposed the TABTS model, which is a BATS model combined with seasonal trigonometry. In a reduced way, the exponential smoothing method led to a state space model, which in turn led to a BATS model, which was finally complemented by seasonal trigonometry, forming the TBATS model.</p><h4>Combination of predictors — forecasts</h4><p>The forecasts previously described have been combined, and the forecast result is a simple arithmetic mean of the individual results.</p><p>The models were trained with the same series used for the previous models. The results can be seen in the following table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*OfplpHvHrdPoqbMGLcAaVg.png" /></figure><p>It can be seen that the smallest forecast error was for the month of February, and the highest for the month of December. Contrary to expectations, the model combination underperformed the ARIMA models, with an average absolute error of 7.29%.</p><h3>Conclusions</h3><p>Among the models analyzed, the best performance was achieved by the ARIMA models, with an average absolute error of approximately 5.1%. As suggested by the <em>auto.arima</em> function, the model that considers seasonality did not show any improvement in performance. The model that considered the Box Cox transformation, to stabilize the variance, also did not show significant improvements in relation to the ARIMA (1,1,1) and ARIMA (3,1,3) models.</p><p>Financial crises and changes in legislation have made forecasts less reliable in recent years. Despite all the difficulties and instabilities, the ARIMA models proved to be efficient, and would be the options for making predictions outside the considered series. In particular the ARIMA model (3,1,3), which had the lowest mean absolute error in the forecasts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c059b91d1d1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/brdata/tax-collection-forecast-for-minas-gerais-brazil-7c059b91d1d1">Tax collection forecast for Minas Gerais — Brazil</a> was originally published in <a href="https://medium.com/brdata">BrData</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Applied computer vision: reading water consumption meters]]></title>
            <link>https://medium.com/brdata/applied-computer-vision-reading-water-consumption-meters-3e4064e961a4?source=rss-6dedcc6de1a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e4064e961a4</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Rodrigo Salles]]></dc:creator>
            <pubDate>Tue, 26 Jan 2021 19:22:29 GMT</pubDate>
            <atom:updated>2021-01-27T15:09:37.712Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A small computer vision application project</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/1*wdVs8R_M5jialpfBuyoU6Q.png" /></figure><p>Tasks that can be automated must be automated. But ordinary tasks developed by human beings prove to be complex to be done by machines. Digit reading in images is one of them.</p><p>The task of reading digits in an image is easily performed by humans, but when trying to implement this ability on machines, difficulties arise. Light conditions, image angle, noise, definition, etc. There are many variables that can affect the performance of the system.</p><p>This small project analyzes the application of computer vision techniques to the reading of water consumption meters.</p><p>The code used in this project was developed in python and can be found <a href="https://github.com/RodrigoSalles">here</a>. And feel free to contact me if you have any questions or suggestions.</p><h3>Problem definition</h3><p>Nowadays many companies accept that electricity and water consumption readings be sent through a photo of the meters. That way the company is easily faced with thousands of images that need to be processed.</p><p>This small project aims to analyze techniques that would make it possible to automate this process.</p><p>By doing a little research you can see that there are several solutions available. Some are “closed”, and others only perform well under controlled conditions. And as they are techniques that have many possibilities of application, I found it interesting to look with a little more attention, and thus learn a little more.</p><p>Briefly, the objective of the project is to read the digits in the meter images:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*zozj_NjKjw_MYCtHDrJbcA.png" /><figcaption>Photo by Roman Kucev(<a href="https://ieee-dataport.org/open-access/water-meter-dataset">https://ieee-dataport.org/open-access/water-meter-dataset</a>)</figcaption></figure><p>But how to do that? Let’s look at some possibilities.</p><h3>Divide to conquer!</h3><p>How to read digits in images? I will divide the problem into three parts.</p><p><strong>Part 1:</strong> in the first stage the objective is to find some way of identifying and cutting out the region of interest, which contains the digits.</p><p><strong>Part 2</strong>: the goal now is to segment the digits contained in the image cropped in the first step</p><p><strong>Part 3</strong>: reading the digits resulting from step 2</p><h3>Let’s do it. Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qBj1x-ywRD_aOvI_U_UmYw.png" /><figcaption>Photo by <a href="https://www.codespeedy.com/author/g_babbar/"><em>Gaurav Babbar</em></a></figcaption></figure><p>I found several possibilities to segment the region that contains the digits. Many are used to read license plates, based on morphological operations such as erosion, dilation, etc. The results are good, but I would like to try something more robust. I decided to use a convolutional neural network to accomplish the task.</p><p>To achieve this goal, the YOLOv3 system (you look only once) was adopted. The algorithm makes use of a convolutional neural network with special characteristics. The network has only fully connected convolutional networks(FCN). Called Darknet-53, it contains 53 convolutional layers, each followed by a batch normalization layer and Leaky ReLU activation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*hVyPerb6Z_f7OcfwX7yYag.png" /><figcaption>Mini-YOLOv3 - DOI: 10.1109/ACCESS.2019.2941547</figcaption></figure><p>I found a very interesting tutorial on YOLO (can be seen <a href="https://www.youtube.com/watch?v=_FNfRtXEbr4">here</a>), and a dataset with more than 1000 images of water meters (which can be found <a href="https://ieee-dataport.org/open-access/water-meter-dataset">here</a>).<br>To train the network we need to design the image labels. Hard work. I labeled 500 images with the aid of the LabelImg software.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*upFqrE2cdRWyuAjWugaxKg.png" /><figcaption>LabelImg in action(photo by Roman Kucev)</figcaption></figure><p>As my computer is already a little tired, I decided to train the model in Google Colab. With the help of the GPU offered by the platform, the training lasted 5 hours, and the result was very satisfactory.</p><p>With the region of interest located, it is easy, from the coordinates obtained, to cut out the region containing the numbers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*nw1djmAuMvna0_bngQXxgg.png" /><figcaption>Successfully targeted region</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*WyeGeHiU_OiCASJoe2LMpg.png" /><figcaption>Successfully targeted region</figcaption></figure><h3>Part 2 : digit segmentation of the cropped region</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*yNDEXFZM94LagWh2sm8mLg.png" /><figcaption>Cropped region</figcaption></figure><p>To segment the digits of the region obtained in part 1, traditional techniques were used. The steps were as follows:<br>• First, the image was changed to gray scale:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*sxWQhqQPgzy6Y36fiDFMUg.png" /></figure><p>• In the sequence, the best threshold for the problem was chosen (the best result was obtained with TOZERO - If the pixel value is less than the adopted limit, it is set to zero, and the other values are maintained.):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*5CQn-ULprpUrfoikKEDYAw.png" /></figure><p>• With the <em>findContours</em> function (OpenCV), the contours were located. The contours found were ordered, and filtered according to their area. The values with areas most likely to contain the digits were selected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*N0950P1U8ruhyJeOHBmcXQ.png" /></figure><p>The result obtained can be seen below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/271/1*k0cLWZfM1NuE00kiBDZXnA.png" /></figure><p>As you can see, the number 6 was not identified.</p><h3>Part 3: digit reading</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*JDMwIoPpgU2XUa5uSRo9Lg.png" /><figcaption>MNIST dataset</figcaption></figure><p>The task of this last phase is to read the digits segmented in step 2. For this task, I will adopt another convolutional neural network, trained with the help of the well-known MNIST dataset.</p><p>The MNIST dataset is an acronym that stands for the Modified National Institute of Standards and Technology dataset. It is a dataset of 60,000 small square 28 × 28 pixel grayscale images of digits between 0 and 9.</p><p>The result obtained by the algorithm can be seen in the figure below. It can be seen that the network performed well, and that the error in identifying the digit 6 comes from phase two.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*wLhX-Gvofb7FK1pnUJPo8Q.png" /></figure><h3>Could be better?</h3><p>One of the most complex parts of computer vision is segmentation. Many factors can affect the performance of the system, and there are many parameters to be adjusted. And how could the system be improved? The first and third phases showed good results. The error appeared in phase two. The improvement, which I intend to implement soon, is to replace phases two and three with another YOLO network, to directly identify the digit in the image obtained in the first phase. The system will become more robust.</p><p>In the first phase, the YOLO network was implemented to identify only one object in the image. In this new format I will have to train the network to identify the digits from 0 to 9, that is, 10 possible objects in an image. For the first phase I labeled 500 images, now I would have to label 5000. It is a lot of work. But I think the result will be interesting.</p><p>Anyway, it was a small project that allowed me to learn a little more about computer vision. Any questions or suggestions, feel free to write to me. Bye.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e4064e961a4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/brdata/applied-computer-vision-reading-water-consumption-meters-3e4064e961a4">Applied computer vision: reading water consumption meters</a> was originally published in <a href="https://medium.com/brdata">BrData</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Correlation: straight to the point]]></title>
            <link>https://medium.com/brdata/correlation-straight-to-the-point-e692ab601f4c?source=rss-6dedcc6de1a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/e692ab601f4c</guid>
            <category><![CDATA[correlation]]></category>
            <category><![CDATA[pearson-correlation]]></category>
            <category><![CDATA[kendall-correlation]]></category>
            <category><![CDATA[spearman-correlation]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Rodrigo Salles]]></dc:creator>
            <pubDate>Sat, 30 Mar 2019 12:36:04 GMT</pubDate>
            <atom:updated>2019-03-30T12:39:02.565Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Correlation: Interdependence of variable quantities(Oxford dictionary).</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*C-Vu5U1up-6bpHRuMoHcww.jpeg" /></figure><p>What is correlation? What are correlation indices? How to interpret them? How to use Python Pandas to calculate the correlation?</p><p>These are some questions that I intend to answer in this small study, clearly and directly. I will not deepen statistical concepts. These concepts are very important, but it is not my goal at this time. The idea of this research is to do a “ <em>get to the point</em>”, in which I will prepare the minimum necessary to use the Pandas and interpret the results, adding important information to your project.</p><p>This study is available on Github. Access by clicking <a href="https://github.com/RodrigoSalles">here</a>.</p><p>You can find this study in Portuguese by clicking <a href="https://medium.com/brdata/correla%C3%A7%C3%A3o-direto-ao-ponto-9ec1d48735fb">here</a>.</p><h3>What is correlation?</h3><p>The initial definition sums up the idea well: correlation indicates the interdependence between two or more variables.</p><p>In some cases this interdependence is clear:</p><ul><li>Body mass and height;</li><li>Fuel consumption and distance traveled;</li><li>Number of ads and products sold;</li><li>Study time and performance in the evaluation (<em>not always … :-)</em>).</li></ul><p>But in many cases this relationship is not apparent, and so we must resort to more reliable methods of detection. Among the most common methods we have the Pearson, Spearman and Kendall indexes. Let’s talk a bit about these indicators.</p><h3>Pearson’s Correlation Coefficient</h3><p>Also called “product-moment correlation coefficient” or simply “Pearson’s ρ” measures the degree of correlation (and the direction of this correlation — whether positive or negative) between two variables. This coefficient, usually represented by ρ, only assumes values between -1 and 1.</p><p>The formula developed by Karl Pearson, more than 120 years ago, continues to be the most used for calculating correlation.</p><p>The Pearson correlation coefficient is calculated according to the following formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*h3ECOe-xmIS2sB8xvxk_Fg.png" /></figure><p>Pearson’s correlation measures the linear association between <strong>continuous variables</strong>. It is the value that indicates how much the relationship between variables can be described by a line.</p><h4>Interpreting the value of ρ</h4><ul><li>0.9 to 1 positive or negative indicates a very strong correlation.</li><li>0.7 to 0.9 positive or negative indicates a strong correlation.</li><li>0.5 to 0.7 positive or negative indicates a moderate correlation.</li><li>0.3 to 0.5 positive or negative indicates a weak correlation.</li><li>0 to 0.3 positive or negative indicates a negligible correlation.</li></ul><p>There are several possibilities for interpretation of correlation. We can consider the slope of the line representing the relation between the variables, we can consider the series of values as vectors, and the ρ, in a geometric interpretation, would represent the cosine of the angle formed between the vectors, etc. Some interesting information can be found in the article “<a href="https://www.stat.berkeley.edu/~rabbee/correlation.pdf">Thirteen ways to look at the correlation coefficient</a>”.</p><h3>Spearman Correlation Coefficient</h3><p>The Spearman correlation coefficient is indicated for the calculation of the correlation between random variables x and y related monotonically to each other, but not necessarily linearly. If the relation is linear Pearson’s method is the most indicated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*kp-xwo8z_LOoWbzYBXRAQw.png" /></figure><p>If the random variables perfectly follow the function y = log (x), the Pearson correlation coefficient will not be equal to 1. The Spearman coefficient will be 1, since it reflects the relation that is not linear.</p><p>The form of this coefficient of correlation is the same as the Pearson coefficient, but the variables x and y are no longer the original values collected. Instead of the values of x and y, the rank of each variable is used. The rank is nothing more than the value that each variable has in a numerical order. The smallest value is number one, the second smallest value will be number two, and thus all variables will have new values.</p><p>If the data sets do not have repeated values the Spearman correlation coefficient can be calculated using the following formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*9UfPBKMaaDjgG4sTHTqVDg.png" /></figure><p>If there are repeated values, use the following formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*lu4ZSWxZMr-w9VndV2rqJw.png" /></figure><p>The formulas are big, but the way to calculate is simple. <a href="https://pt.wikipedia.org/wiki/Coeficiente_de_correla%C3%A7%C3%A3o_de_postos_de_Spearman">Here</a> you find a practical example with the calculations about the correlation between a person’s Intelligence quotient and the number of hours they watch television per week.</p><h3>Kendall tau correlation coefficient</h3><p>It is a measure of rank correlation, that is, it checks the similarity between the orders of the data when ordered by each of the quantities. It is named in honor of the British statistician Maurice Kendall, who developed it in 1938.</p><p>Kendall’s correlation takes into account only the directional agreement of the so-called concordant and discordant pairs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*LCRSauAVlRTLcuIse_D4NQ.png" /></figure><p>To clarify the concept of concordant and discordant pairs I will reproduce a simple example found in Ruslana Dalinina’s <em>Introduction to Correlation</em> study.</p><p>Consider the following values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/76/1*hchlSa1B2iWn3ghLArubfA.png" /></figure><p>Matching pairs (x1, y1), (x2, y2) are the pairs that obey the following rules: x1 &lt;x2 and y1 &lt;y2, or x1&gt; x2 and y1&gt; y2. In the example the pairs (4,6) and (5,9) in lines 3 and 4 are concordant pairs. The pairs (1,7) and (2,5) of lines 0 and 1 do not obey the rules and are called discordants.</p><p>All pairs are compared, counted, and in sequence you just apply the formula.</p><p>Matching pairs:</p><ul><li>(1,7) e (5,9)</li><li>(2,5) e (4,6)</li><li>(2,5) e (5,9)</li><li>(3,1) e (4,6)</li><li>(3,1) e (5,9)</li><li>(4,6) e (5,9)</li></ul><p>Discordant pairs:</p><ul><li>(1,7) e (2,5)</li><li>(1,7) e (3,1)</li><li>(1,7) e (4,6)</li><li>(2,5) e (3,1)</li></ul><p>The correlation found for this example was 0.2.</p><p>The Kendall correlation coefficient is particularly efficient for <strong>discrete data</strong>.</p><h3>Warning: correlation does not imply cause!</h3><p>It is very important to note that even a strong correlation does not imply that x “causes” y! A great example to illustrate this concept can be found in “A Basic Course in Statistics” (Clarke &amp; Cooke): A student has good grades in physics and chemistry. But good performance in chemistry can not be explained by good performance in physics. The good grades in these subjects could be explained by the good performance in mathematics, a factor not considered in the first moment.</p><p>An interesting real example can be found in the article <a href="http://comcept.org/cepticismo/correlacao-nao-implica-necessariamente-causalidade/"><em>Correlation does not necessarily imply causality</em></a>, by Marco Philip:</p><blockquote>Several studies initially suggested that menopausal women who received hormone replacement therapy (HRT) also had a lower risk of coronary heart disease, which led to the idea that TSH conferred protection against coronary heart disease. However, controlled and randomized (more rigorous) studies later on showed that TSH actually caused a small but significant increase in the risk of coronary heart disease. A re-analysis of the studies revealed that women who received TSH were also more likely to belong to a higher socioeconomic class with better diet and exercise habits. The use of TSH and the low incidence of coronary heart disease were not cause and effect, but the result of a common cause — the benefits associated with a high socioeconomic status.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*8wkmLkocdm2UcIbypb9vtw.png" /><figcaption><a href="https://xkcd.com/552/">https://xkcd.com/552/</a></figcaption></figure><p>We must beware of misinterpretation.</p><h3>Calculating Correlation with Pandas</h3><p>We already know the basics about correlation, now we go to the direct calculation with the help of Pandas. I will use the example found in the article “<a href="https://www.datascience.com/learn-data-science/fundamentals/introduction-to-correlation-python-data-science">Introduction to Correlation</a>”, by Ruslana Dalinina, with some minor modifications.</p><p>The data set used “Auto-Mpg Data” can be found <a href="https://archive.ics.uci.edu/ml/datasets/Auto+MPG">here</a>.</p><p>The idea is to check which vehicle feature is most closely associated with your fuel consumption (mpg: miles per gallon — 1.6 miles per gallon).</p><p>Looking at the first few lines of the dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*zAbr6a57Pj10ADmtP_kmUQ.png" /></figure><p>More information:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*zDmzzv_JjoqB1d7juklhEA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*c2jaWjUH-ISCDOmpmTi1zQ.png" /></figure><h3>A little pre-processing.</h3><p>It can be seen that there are 6 values remaining in the horsepower column. Let’s fill these gaps with the average power according to the number of cylinders of the engine. It was the form I chose. There are several possibilities.</p><p>Looking at the relation between the number of cylinders and the power of the engine we have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*GY1fasCFUHXLh_BzkGm_yQ.png" /></figure><p>Let’s replace the missing values by the mean:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*V3T7vOQjTrzyhDEdy-6yYA.png" /></figure><p>The function to update the values can be seen below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*URjTpsQd0gFKBsuvFoc2vw.png" /></figure><p>After using the update function we have the following result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/1*oxeHVyeUeO0wFqqvYT9pKg.png" /></figure><p>Now all the columns are complete!</p><p>I chose to do this process, but the pandas can work well even with some missing data.</p><p>Now let’s get the correlation.</p><h3>Pandas</h3><p>The Pandas provides us with the <strong>corr ()</strong> function to calculate the correlation between two columns. Let’s check the correlation between the vehicle’s weight and its mpg performance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*gIC_XD60eKQA9_qd7UaReA.png" /></figure><p>As expected there is a strong negative correlation between performance and vehicle weight. The heavier the lower the mpg performance.</p><p>You can check all the correlations simultaneously:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*PfaYgeUtnhhzV8lcsGfEnA.png" /></figure><p>The Pearson method is used by default, but the Pandas allows the use of other indexes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*LgbkDiu6-tUHgNB_IGvrrg.png" /></figure><p>To facilitate the visualization of the correlations it is possible to use the colors:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*nn2G47RqX2j1Yx1vNeOF-w.png" /></figure><p>The color gradation is observed in relation to the positive and negative correlations.</p><p>Several important information from the data set can be obtained simultaneously with few programming lines.</p><h3>Conclusion</h3><p>The correlation indicates the interdependence between two or more variables. It is important information that can be applied in various situations.</p><p>Pandas allow us to obtain the correlation quickly, according to the desired method, but we must pay special attention to the interpretation of the results. As has been said, correlation does not necessarily imply a causal relationship.</p><p>In general, correlation is another tool that can help us build more reliable models.</p><h4>References</h4><p><a href="https://www.datascience.com/learn-data-science/fundamentals/introduction-to-correlation-python-data-science">https://www.datascience.com/learn-datscience/fundamentals/introduction-to-correlation-python-data-science</a></p><p><a href="https://bloqm.wordpress.com/2013/10/13/coeficiente-de-correlacao-de-postos-de-spearman/">https://bloqm.wordpress.com/2013/10/13/coeficiente-de-correlacao-de-postos-de-spearman</a></p><p><a href="https://pt.wikipedia.org/wiki/Coeficiente_de_correla%C3%A7%C3%A3o_de_postos_de_Spearman">https://pt.wikipedia.org/wiki/Coeficiente_de_correla%C3%A7%C3%A3o_de_postos_de_Spearman</a></p><p><a href="http://www.statisticshowto.com/kendalls-tau/">http://www.statisticshowto.com/kendalls-tau</a></p><p><a href="http://comcept.org/cepticismo/correlacao-nao-implica-necessariamente-causalidade/">http://comcept.org/cepticismo/correlacao-nao-implica-necessariamente-causalidade</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e692ab601f4c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/brdata/correlation-straight-to-the-point-e692ab601f4c">Correlation: straight to the point</a> was originally published in <a href="https://medium.com/brdata">BrData</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Science applied to predictive maintenance: water pumps in Tanzania.]]></title>
            <link>https://medium.com/brdata/data-science-applied-to-predictive-maintenance-water-pumps-in-tanzania-a9aed503edcf?source=rss-6dedcc6de1a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9aed503edcf</guid>
            <category><![CDATA[random-forest]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[predictive-maintenance]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <dc:creator><![CDATA[Rodrigo Salles]]></dc:creator>
            <pubDate>Mon, 25 Mar 2019 13:52:31 GMT</pubDate>
            <atom:updated>2019-03-25T13:52:31.869Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cmaXnmfLTT6_1VCoq5oROQ.png" /></figure><blockquote>Is it possible to predict, from real data, which water pump is working properly, which one needs repairs and which one is out of operation?</blockquote><p>This project is available on Github. Access by clicking <a href="https://github.com/RodrigoSalles/Tanzania_water_Pump">here</a>.</p><p>You can find this study in Portuguese by clicking <a href="https://medium.com/ensina-ai/data-science-aplicado-%C3%A0-manuten%C3%A7%C3%A3o-preditiva-bombas-d%C3%A1gua-na-tanz%C3%A2nia-32a85de8b41">here</a>.</p><p>Part of the study was done at Colaboratory. Do not know what it is? <a href="https://medium.com/brdata/deep-learning-colaboratory-a3fdf5932425">Here’s</a> a little tutorial.</p><h3>The problem of water scarcity in the world</h3><p><em>Terra…planeta água…!</em></p><p>The planet water that Guilherme Arantes, a brazilian singer, describes in his song has more than 70% of its surface covered by water. The big problem is that of this total only 3% can be considered appropriate for human consumption. In a world with approximately 7.6 billion people, more than 1 billion face problems of access to water. For 2.7 billion it lacks at least a month a year.</p><p>According to UN projections, the demand for fresh water will exceed supply by 40% by the year 2030. In this way several cities in the world run the risk of running out of water.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*p4KJ6Om7u6PSF78KjGbPRw.jpeg" /></figure><p>April 21, 2018 was considered “zero day” for Cape Town, South Africa. It was expected that taps in this important city would stop supplying water on that day. At the time of writing, I still do not know what happened on “zero day”, but the prospects are scary. At the same level are many other cities like Tokyo, Moscow, Beijing and São Paulo.</p><p>In some places this crisis may present more dramatic contours. In some countries the water crisis can have its effects potentiated by the eternal financial crises, humanitarian crises, wars, etc.</p><p>In this context we find Tanzania.</p><h3>The problem of water scarcity in Tanzania</h3><p>The United Republic of Tanzania is an East African country. It is a unitary state consisting of 26 regions, and in addition to its continental part, includes the archipelago of Zanzibar in the Indian Ocean.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*r-M-lLPIJgMOgVBF9RRjNA.png" /></figure><p>Like many nations around the world Tanzania suffers from serious water supply problems. Finding potable water is not a simple task in a country with a third of its arid or semiarid regions.</p><p>In the following image you can see the three largest lakes in Tanzania: Lake Victoria to the north, Lake Tanganyika to the west and Lake Malawi to the south. These three reservoirs cater to large numbers of people.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*fqHn740_R11Zr5rQ244drQ.png" /></figure><p>That way if you do not live near one of the three largest lakes in the country, you will certainly face serious water problems!</p><p>And what are the alternatives for these people? Not many possibilities, but the best of them is the use of groundwater.</p><p>Groundwater represents the best possibility, but the process is not so simple. In order to establish a point of supply a considerable initial investment and an efficient maintenance system are necessary.</p><p>Several supply points were built in Tanzania. They are insufficient, but they already help many people.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*xDlYtp5ATylhQfdRumNcJw.png" /></figure><p>The map above shows the states of the country and the coverage of the supply points.</p><p>With the first step given (even in a timid manner), the following is to establish an efficient maintenance system. An efficient system can guarantee drinking water for thousands of people.</p><p>A supply point may stop working, or run below capacity for several reasons. Specifically at supply points established in Tanzania, the main problems are: broken taps, broken pumps, broken pipes, a damaged supply source and theft of water pumps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*qjmObBc7LcWLyRd5vgHwzA.jpeg" /></figure><p>The most common form of maintenance adopted is the corrective one. It is the most primary form of maintenance, and can be summarized in the “break-repair” cycle. It is the most expensive form, and in the case of a supply point, represents people without drinking water, for their basic needs, for a certain time.</p><p><strong>Is it possible to implement a predictive maintenance system from data collected from the supply points?</strong></p><h3>To the Point</h3><p>The purpose of this small project is to predict, from actual data, which water pumps are operating correctly, which are in need of maintenance and which do not work. It is a case of Data Science applied to predictive maintenance.</p><p>Predictive maintenance periodically monitors the machines, based on the analysis of data collected through monitoring or field inspections. The main objective of predictive maintenance is the timely verification of the equipment in order to anticipate eventual problems that may cause greater expenses with corrective maintenance.</p><p>By anticipating the problems the maintenance costs are reduced, and the drinking water supply guaranteed.</p><h3>Knowing the data</h3><p>The data used were provided by <a href="http://taarifa.org/"><strong>Taarifa</strong></a> and <a href="http://maji.go.tz/"><strong>Tanzanian Ministry of Water</strong></a>. Actual data collected at the points of supply.</p><p>The dataset used is composed of the following information:</p><ul><li>id — Supply point identification number;</li><li>amount_tsh — amount of water available for the supply point;</li><li>date_recorded — Date of data recording;</li><li>funder — Who financed the point of supply;</li><li>gps_height — Altitude of the supply point;</li><li>installer — Organization that installed the supply point;</li><li>longitude — GPS coordinates — longitude;</li><li>latitude — GPS coordinates — latitude;</li><li>wpt_name — Supply point name, if there is a name;</li><li>num_private — No information about this column;</li><li>basin — River basin;</li><li>subvillage — Geographic localization;</li><li>region — Geographic localization;</li><li>region_code — Geographic localization (code);</li><li>district_code — Geographic location (code);</li><li>lga — Geographic localization;</li><li>ward — Geographic localization;</li><li>Population in the vicinity of the Supply point;</li><li>public_meeting — True / False;</li><li>recorded_by — Group that entered the data;</li><li>scheme_management — Who operates the Supply point;</li><li>scheme_name — Who operates the Supply point;</li><li>permit — if the Supply point is allowed;</li><li>construction_year — Year of construction of the supply point;</li><li>extraction_type — Type of extraction used at the supply point;</li><li>extraction_type_group — Extraction type used at the supply point;</li><li>extraction_type_class — Type of extraction used at the supply point;</li><li>management — How the supply point is managed;</li><li>management_group — How the supply point is managed;</li><li>payment — Water costs;</li><li>payment_type — form of payment;</li><li>water_quality — Water quality;</li><li>quality_group — Water quality;</li><li>quantity — The amount of water;</li><li>quantity_group — The amount of water;</li><li>The source of the supply point;</li><li>source_type — The source of the supply point;</li><li>source_class — The source of the supply point;</li><li>waterpoint_type — The type of supply point;</li><li>waterpoint_type_group — The type of supply point.</li></ul><p>The current state of the target point is described as:</p><ul><li>functional — It is working in its entirety;</li><li>non functional — does not work;</li><li>functional needs repair — Running, but needing maintenance.</li></ul><p>It can be observed that many information is categorical. This feature requires special attention.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*1GbqEEWT0l-UCJCaaKQMsQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/169/1*oguJGD4VgGb71gAiE9nFmQ.png" /></figure><p>A more detailed observation in the operating state reveals that many of the pumps are not working:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*RNifaMB3PtkPfuhDKsMCPQ.png" /></figure><p>Taking into account that the points need maintenance, and that maintenance requires financial resources, the “form of payment” gives us important information:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*3WiPwOZUJgRnAjTuzrDXJQ.png" /></figure><p>Most of the supply points are never paid for their use.</p><p>By representing the relationship between functional status and form of payment, we have a clearer view:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*iymRY7D4RqgoO97C2_31iQ.png" /></figure><p>Most points that are not paid are not working. One possible explanation for this feature would be the lack of maintenance resources. When there is some form of payment, the functional status changes.</p><p>One feature that may be important is the amount of water available.When the amount of water is sufficient most of the points are working. It is justified to be more careful about these points. When it is dry, of course, the point is not working.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*MJ6adwyhWa7Hcv3vWEhDAw.png" /></figure><p>After this initial observation, let’s clean up the data.</p><h3>Cleaning the data</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*U5xiq3U7ML2QEfctQefZkw.jpeg" /></figure><p>Looking at the data set, we see that several columns of information are incomplete, and many are categorical. There are many possibilities to solve these problems. With advantages and disadvantages. Let’s take a strategy and check the results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*TVeg1zoX6Aim0-1Uls461A.png" /></figure><h3>Information that does not “add value”</h3><p>In the data set, some categories may not carry relevant information, and we can work well without them. At first you can highlight wpt_name and recorded_by. I believe it is not very important for the condition of operation of the supply point to know your name. In the case of recorded_by, the entire column was filled with GeoData Consultants Ltd. It does not add anything of value to the algorithm. This way, these two columns will be deleted:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*r6aV6Z7lL-SNRBKMpB855g.png" /></figure><h3>Incomplete Information</h3><p>Some columns are incomplete:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*EalbMMqDxBbW64FBvNzbpA.png" /></figure><p>Incomplete columns are:</p><ul><li>to merge</li><li>installer</li><li>subvillage</li><li>public_meeting</li><li>scheme_management</li><li>scheme_name</li><li>permit</li></ul><p>Let’s fill in these gaps with “SI” (no information):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*5zDK8PZGV9W4duUxsBuAAA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*rggO7gA8SryKIVAXOgDYxw.png" /></figure><p>Now … let’s go to categorical information.</p><h3>Data cleansing: treatment of categorical information</h3><p>As was previously observed, much of the information is categorical. These data represent problems for the algorithms, which for the most part work algebraically.</p><p>Categories can pose problems, which would be simple for humans: a “cars” category could contain “Ferrari” and “Fiat”, which for most people have clear differences, starting with price.<br>For the computer are just cars. For the representation, and differentiation, we must add extra information, such as price, power, model, etc.</p><p>There are several techniques for handling categorical information: category numbering, one hot encoding, feature hashing, etc. Each technique has advantages and disadvantages. For example, category numbering is easy to implement, but it has the disadvantage that algorithms can “see” greater similarity in categories with close values. The famous “one-hot-encoding” is also simple to implement but we must be aware of the real possibility of overfitting, greater dimensionality of the problem and greater consumption of computational resources.</p><h3>Strategy for handling categorical information</h3><p>As discussed above, there are many possibilities for handling categorical information. And as every choice entails a loss … let us go to ours.</p><p>To encode our features we will use the one-hot encoding get_dummies. Its operation is very simple: A new column for each subgroup of the original column.</p><p>In the following example a new column with zeros and ones was created for each state of the original table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*7iQw7T_H-DcxehXTB2gbxg.png" /></figure><p>The problem of dimensionality starts to worry us. Look at an example from our dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*dYitNvnQTrTXzzKKldZyuA.png" /></figure><p>Several categories appear only once. Thousands of new columns would be created.</p><p>Let’s check, in the data set, the existence of categories that appear only once:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*mut-Q2KWJ5MhDS-_lJwI_g.png" /></figure><p>As a result we have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*PNIyB-Ji_4d0XypbK1eX1g.png" /></figure><p>You can verify that the groups “funder”, “installer”, “subvillage”, “ward” and “scheme_name” have many unit categories.</p><p>To mitigate this problem I will group all the rare cases into a “raro” group, before coding. The case “date_recorded” will be treated separately.</p><p>As a limit, I have set the value 50. All names that have a frequency lower than the limit will be grouped as “raro”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*pvmemtuxnEBucrv8-7z2rQ.png" /></figure><h3>Working with dates</h3><p>Before we code the categorical information we will treat the dates. Similar to categorical information, there are many techniques for dealing with dates, years, etc. The form I adopted will be demonstrated below.</p><p>In the dataset we have “date_recorded” which is the data recording date, and “construction_year” which is the year of construction of the supply point. In the first case the format is “year-month-day”. In the second case it is only the value of the year of construction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*Czel90UftSp45nddSAWomA.png" /></figure><p>For the “date_recorded”, the values will be replaced by the months passed until the reference date: 2018–01–01.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*hQXV54uCM29pTRwgS0nNfQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*MuCJ5e0HdOnfVaFyU6_FmA.png" /></figure><p>For “construction_year”, Let’s update the column values with the years in relation to the 2018 reference.</p><p>A small problem that must be solved is the presence of null values in the data set. These values could induce the algorithm to identify non-existent patterns. I will replace these values with the average of the set.</p><p>Checking the average we have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*jdEmptH-YT_xhnzLPqgdPg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*xV8RWHcr-C6r2hcun2_feA.png" /></figure><p>This average is very low. This can be explained by the presence of many zeros in the column.</p><p>Let us calculate the mean of the non-zero values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*gbC78aYi8iSKeYt0df6K0g.png" /></figure><p>Let’s replace the null values by the mean of the set:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*KpMezOryI5YomY6cxbDdZQ.png" /></figure><p>With the complete column we can count the years in relation to the reference:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*gAMAbjnUXHiVQPdquH3mDA.png" /></figure><p>As a result we have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*ft1Wa1MBt5MMbqWgRUxGyQ.png" /></figure><h3>cat.codes and get_dummies</h3><p>Now that the data is ready, let’s use two methods to encode the categorical information. For the column with many subgroups let’s simply enumerate them, with the help of the function <strong><em>cat.codes</em></strong>. For the column with few subgroups we will use <strong><em>get_dummies</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*zIGKV3RgpKF4yXW6hi814w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*LLZfi7C5MeSSTY649sAW-g.png" /></figure><p>In this way we obtain the following result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*GgY1aFiQW4KRWVmfSMkxwg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*7M_7w4orR_5KA2v16AAsdQ.png" /></figure><h3>Interesting information: gps_height</h3><p>Ao observar uma descrição da coluna <em>gps_height</em>, notamos que o valor mínimo é de -90,0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*7HRKnWuGQ2fOAhGd6l3lXg.png" /></figure><p>But researching some information about Tanzania, we see the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*vyuvymGvGnrd6Q-3nSL3xQ.png" /></figure><p>In this way the lowest point of the country is sea level. Maybe someone typed it wrong. I will update the values of the columns with their modules.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*JI7ml2wpbUTuHD1gDh9nlA.png" /></figure><h3>Functional status</h3><p>As shown at the beginning of the study, the functional state of the supply point is described as:</p><ul><li>functional — It is working in its entirety;</li><li>non functional — it is not working;</li><li>functional needs repair — Running, but needing maintenance.</li></ul><p>These groups will be listed:</p><ul><li>functional: 0</li><li>functional needs repair: 1</li><li>non functional: 2</li></ul><p>In this way we will have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/1*LjQif2Oebj9mXJfOv9sumw.png" /></figure><p>Now that the data is already in the desired format, let’s go to the classifier!</p><h3>Creating the classifier</h3><p>In order to forecast the functional status of the supply points I will use two algorithms: multinomial logistic regression and Random Forest.</p><h3>Multinomial Logistic Regression</h3><p>Logistic regression is a statistical technique that aims to produce, from a set of observations, a model that allows the prediction of values taken by a categorical variable, from a series of variables.</p><p>It is possible to estimate a logistic regression in which the dependent variable has more than two categories. That is, the logistic model can be extended when the qualitative response variable has more than two categories. It is multinomial logistic regression. In our case, these categories are the functional states of the supply points.</p><p>K — 1 equations are generated, where k is the number of categories. Equations generate probabilities to predict whether a category is above / below the reference category.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*-f9okqLE23D_z7wQc42pAg.png" /></figure><p>In this first test we obtained an accuracy of approximately 72%.</p><p>To get a better idea of the performance of the classifier we will use the cross validation method, in which different parts of the data set are used to train and evaluate the accuracy of the classifier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*DJoOvkn__bz5gCDpyA4s1Q.png" /></figure><p>Ten evaluations were performed in different parts and the mean of the results was confirmed in approximately 72%.</p><h4>Random Forest</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*2ThQCyoT5aO4nB4syUlsCQ.jpeg" /></figure><p>The Random Forest algorithm is a type of ensemble learning, a method that generates many classifiers and combines their results.</p><p>In the case of Random Forest, the algorithm generates several decision trees, and combines the result of the classification of all of them. This combination of models makes it much more powerful than the conventional Decision Tree algorithm.</p><p>Because it is a set of Decision Trees, the RandomForestClassifier has several additional factors. Among these factors we can highlight:</p><p>n_estimators: The number of Decision Trees that will be used by Random Forest.</p><p>n_jobs: This is the number of parallel runs that will be used by the model. By passing -1, the value will be equal to the number of cores of the computer used. The more “parallelized” the execution, the faster it will be, as long as the machine supports.</p><p>max_features: It is the number of features that will be used by each internal Decision Tree, different features are drawn for each tree, just to be different classifiers.</p><p>Using 20 estimators we obtained the following result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*jj0JuKlz-j-E61Ghpx9FIg.png" /></figure><p>Approximately 80% accuracy. It represents a significant improvement over logistic regression.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*_qXcZ5ThMfIrwqILODwBgg.png" /></figure><p>Cross-validation confirms the result by approximately 80%.</p><h3>Can we improve?</h3><p>Could the performance of the classifiers be improved? I think so.</p><p>Some possibilities:</p><ul><li>Categorical information could be treated in different ways. I think the hashing trick method could improve performance;</li><li>Much information could be standardized;</li><li>More information could be discarded;</li><li>More data could be raised to support the algorithms. Possibly create new features;</li><li>Use different classification algorithms. An RNA could perform better.</li></ul><p>There are many possibilities for improvement, but implementing them now would make this study very extensive. It’s for the “Tanzania Water Pumps, Part II”.</p><h3>Conclusion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Qmkt8hiYoIkSl1gR0M4HgQ.jpeg" /></figure><p>This study aimed to evaluate the possibility of implementing a predictive maintenance system for water pumps in Tanzania. Because it is a country that faces serious water supply difficulties, an efficient system of supply point maintenance can be of great importance.</p><p>The results showed that it is possible to approximate the correct moment of maintenance of the supply points. With this information you can reduce the maintenance costs and the time the point is out of operation.</p><p>The data collected in person or remotely could be addressed and quickly alerted to the need for maintenance, keeping in mind that improvements in data processing and algorithm design could make the system more efficient.</p><p>The study is a good example of the application of Data Science knowledge to real problems with important social consequences.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9aed503edcf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/brdata/data-science-applied-to-predictive-maintenance-water-pumps-in-tanzania-a9aed503edcf">Data Science applied to predictive maintenance: water pumps in Tanzania.</a> was originally published in <a href="https://medium.com/brdata">BrData</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Contacts]]></title>
            <link>https://medium.com/brdata/contatos-174c03bf5957?source=rss-6dedcc6de1a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/174c03bf5957</guid>
            <category><![CDATA[contato]]></category>
            <category><![CDATA[rodrigo-salles]]></category>
            <dc:creator><![CDATA[Rodrigo Salles]]></dc:creator>
            <pubDate>Sat, 09 Jun 2018 15:40:22 GMT</pubDate>
            <atom:updated>2019-03-16T18:16:30.573Z</atom:updated>
            <content:encoded><![CDATA[<p>You can find me going around the city of Porto/Portugal. If you are not here, my e-mail is the best option: <a href="/service/mailto:engenharia.salles@gmail.com">engenharia.salles@gmail.com</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=174c03bf5957" width="1" height="1" alt=""><hr><p><a href="https://medium.com/brdata/contatos-174c03bf5957">Contacts</a> was originally published in <a href="https://medium.com/brdata">BrData</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A little bit of my story…]]></title>
            <link>https://medium.com/brdata/um-pouco-da-minha-hist%C3%B3ria-b39902a0b760?source=rss-6dedcc6de1a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/b39902a0b760</guid>
            <category><![CDATA[minha-história]]></category>
            <category><![CDATA[rodrigo-salles]]></category>
            <dc:creator><![CDATA[Rodrigo Salles]]></dc:creator>
            <pubDate>Sat, 09 Jun 2018 15:39:36 GMT</pubDate>
            <atom:updated>2021-01-25T18:28:28.697Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*b2oBRsxXpDRS6EGV7Wa2qw.jpeg" /></figure><p>I was born in the city of Duque de Caxias - Rio de Janeiro. I lived there for a few years and then moved to the City of Palms, the lovely Caratinga, Minas Gerais. Then, in search of new airs, I moved to London, England.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cj2kZTtbdx54CHi785g9cw.jpeg" /></figure><p>I lived there for two and a half years. I returned to Brazil in 2008, but this time to the city of Juiz de Fora, Minas Gerais . After a few good years I decided to change again. This time the chosen city was the undefeated city! Porto, Portugal. And here I am at the moment(january-2021).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TUiL7mCQ44yS_Tvtf3phyA.jpeg" /></figure><p>In this comings and goings I graduated in Physical Science, course concluded in 2003, and after some years I studied Mechatronics Engineering, a bachelors degree completed in 2014.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b39902a0b760" width="1" height="1" alt=""><hr><p><a href="https://medium.com/brdata/um-pouco-da-minha-hist%C3%B3ria-b39902a0b760">A little bit of my story…</a> was originally published in <a href="https://medium.com/brdata">BrData</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Correlação: direto ao ponto.]]></title>
            <link>https://medium.com/brdata/correla%C3%A7%C3%A3o-direto-ao-ponto-9ec1d48735fb?source=rss-6dedcc6de1a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ec1d48735fb</guid>
            <category><![CDATA[pearson]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[correlação]]></category>
            <category><![CDATA[kendall]]></category>
            <category><![CDATA[spearman]]></category>
            <dc:creator><![CDATA[Rodrigo Salles]]></dc:creator>
            <pubDate>Thu, 07 Jun 2018 10:06:38 GMT</pubDate>
            <atom:updated>2021-01-25T18:25:37.753Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>Correlação: interdependência entre duas ou mais variáveis.</em> (Dicionário Priberam da Língua Portuguesa)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/0*_LsGlIYQ1CbUVs4g.jpg" /></figure><p>O que é correlação? O que são índices de correlação? Como interpretá-los? Como utilizar o <strong>Pandas</strong> do Python para calcular a correlação?</p><p>Essas são algumas perguntas que pretendo responder nesse pequeno estudo, de forma clara e direta. Não vou aprofundar conceitos estatísticos. Esses conceitos são muito importantes, mas não é meu objetivo nesse momento. A ideia dessa pesquisa é fazer um “<em>direto ao ponto</em>”, em que vou preparar o mínimo necessário para utilizar o Pandas e interpretar os resultados, agregando importantes informações ao seu projeto.</p><p>Este estudo encontra-se disponível no Github. Acesse clicando <a href="https://github.com/RodrigoSalles">aqui</a>.</p><h3>O que é correlação?</h3><p>A definição inicial resume bem a ideia: a correlação indica a interdependência entre duas ou mais variáveis.</p><p>Em certos casos essa interdependência é clara:</p><ul><li>Massa corporal e altura;</li><li>Consumo de combustível e distância percorrida;</li><li>Número de anúncios e produtos vendidos;</li><li>Tempo de estudo e desempenho na avaliação<em>(nem sempre…rs)</em>.</li></ul><p>Mas em muitos casos essa relação não é aparente, e assim devemos recorrer a métodos mais confiáveis de detecção. Dentre os métodos mais comuns temos os índices de Pearson, Spearman e Kendall. Vamos falar um pouco sobre esses índices.</p><h3>Coeficiente de Correlação de Pearson</h3><p>Também chamado de “coeficiente de correlação produto-momento” ou simplesmente de “<em>ρ</em> de Pearson” mede o grau da correlação (e a direção dessa correlação — se positiva ou negativa) entre duas variáveis. Este coeficiente, normalmente representado por <em>ρ</em> assume apenas valores entre -1 e 1.</p><p>A formula desenvolvida por Karl Pearson, há mais de 120 anos, continua a ser a mais utilizada para o cálculo da correlação.</p><p>Calcula-se o coeficiente de correlação de Pearson pela seguinte fórmula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*KWAowigAR0EqWMmSBwOsqg.png" /></figure><p>A correlação de Pearson mede a associação linear entre <strong>variáveis contínuas. </strong>É<strong> </strong>o valor que indica o quanto a relação entre as variáveis pode ser descrita por uma reta.</p><h4>Interpretando o valor de <em>ρ</em></h4><ul><li>0.9 a 1 positivo ou negativo indica uma correlação muito forte.</li><li>0.7 a 0.9 positivo ou negativo indica uma correlação forte.</li><li>0.5 a 0.7 positivo ou negativo indica uma correlação moderada.</li><li>0.3 a 0.5 positivo ou negativo indica uma correlação fraca.</li><li>0 a 0.3 positivo ou negativo indica uma correlação desprezível.</li></ul><p>Existem várias possibilidades de interpretação da correlação. Pode-se considerar a inclinação da reta que representa a relação entre as variáveis, pode-se considerar as séries de valores como vetores, e o <em>ρ, </em>em uma interpretação geométrica, representaria o cosseno do ângulo formado entre os vetores, etc. Algumas informações interessantes podem ser encontradas no artigo “<a href="https://www.stat.berkeley.edu/~rabbee/correlation.pdf"><em>Thirteen ways to look at the correlation coefficient</em></a>”.</p><h3>Coeficiente de Correlação de Spearman</h3><p>O coeficiente de correlação de Spearman é indicado para o cálculo da correlação entre variáveis aleatórias x e y relacionadas monotonicamente entre si, mas não necessariamente de maneira linear. Se a relação é linear o método de Pearson é o mais indicado.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*UItO0nCkSMNRZW7SZHMKaA.png" /><figcaption>Em uma relação monotônica, as variáveis tendem a mudar juntas mas não necessariamente a uma taxa constante (Fonte: data Analysis — Bui Tram).</figcaption></figure><p>Se as variáveis aleatórias seguirem, à perfeição, a função y = log(x), o coeficiente de correlação de Pearson não será igual a 1. Já o coeficiente de Spearman será 1, pois reflete a relação que não é linear.</p><p>A forma deste coeficiente de correlação é a mesma do coeficiente de Pearson, mas as variáveis x e y não são mais os valores originais coletados. No lugar dos valores de x e y, utiliza-se o posto de cada variável. O posto nada mais é do que o valor que cada variável possui em um ordenamento numérico. O menor valor é o número um, o segundo menor valor será o número dois, e dessa forma todas as variáveis terão novos valores.</p><p>Se os conjuntos de dados não possuem valores repetidos o coeficiente de correlação de Spearman pode ser calculado com o auxílio da seguinte fórmula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*KyplHv3fCtxPQMOqv6-XBA.png" /></figure><p>Caso existam valores repetidos deve-se recorrer à seguinte fórmula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*QmKUAIDKRmOkoXYYp6dlFw.png" /></figure><p>As fórmulas são grandes, mas a forma de calcular é simples. <a href="https://pt.wikipedia.org/wiki/Coeficiente_de_correla%C3%A7%C3%A3o_de_postos_de_Spearman">Aqui</a> você encontra um exemplo prático, com os cálculos, sobre a correlação entre o QI de uma pessoa e o número de horas em que assiste televisão por semana.</p><h3>Coeficiente de correlação tau de Kendall</h3><p>É uma medida de correlação de postos, ou seja, verifica a semelhança entre as ordens dos dados quando classificados por cada uma das quantidades. Recebe este nome em homenagem ao estatístico britânico Maurice Kendall, que o desenvolveu em 1938.</p><p>A correlação de Kendall leva em consideração apenas a concordância direcional dos chamados pares concordantes e discordantes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*rPQsIVhiD3izV5sIiewMBg.png" /></figure><p>Para ficar claro o conceito de pares concordantes e discordantes vou reproduzir um exemplo simples encontrado no estudo <em>Introdução à correlação</em>, de Ruslana Dalinina.</p><p>Considere os seguintes valores:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/92/1*XbKRrKB6XZTvdZlh7AtIRA.png" /></figure><p>Pares concordantes (x1,y1),(x2,y2) são os pares que obedecem às seguintes regras: <em>x</em>1&lt; <em>x</em>2 e <em>y</em>1 &lt; <em>y</em>2, ou <em>x</em>1 &gt; <em>x</em>2 e <em>y</em>1 &gt; <em>y</em>2. No exemplo os pares (4,6) e (5,9) nas linhas 3 e 4 são pares concordantes. Os pares (1,7) e (2,5), das linhas 0 e 1, não obedecem às regras e são chamados de discordantes.</p><p>Todos os pares são comparados, contados, e na sequência é só aplicar a fórmula.</p><p>Pares concordantes:</p><ul><li>(1,7) e (5,9)</li><li>(2,5) e (4,6)</li><li>(2,5) e (5,9)</li><li>(3,1) e (4,6)</li><li>(3,1) e (5,9)</li><li>(4,6) e (5,9)</li></ul><p>Pares discordantes:</p><ul><li>(1,7) e (2,5)</li><li>(1,7) e (3,1)</li><li>(1,7) e (4,6)</li><li>(2,5) e (3,1)</li></ul><p>A correlação encontrada para esse exemplo foi de 0.2.</p><p>O coeficiente de correlação de Kendall é particularmente eficiente para <strong>dados discretos</strong>.</p><h3>Correlação não implica causa!</h3><p>É muito importante observar que mesmo uma correlação forte não implica que x “causa” y! Um ótimo exemplo para ilustrar esse conceito pode ser encontrado no livro “<em>A Basic Course in Statistics”(Clarke &amp; Cooke): </em>um estudante tem boas notas em física e química. Mas o bom desempenho em química não pode ser explicado pelo bom desempenho em física. As boas notas nessas disciplinas poderiam ser explicadas pelo bom desempenho em matemática, fator não considerado no primeiro momento.</p><p>Um exemplo real interessante pode ser encontrado no artigo <a href="http://comcept.org/cepticismo/correlacao-nao-implica-necessariamente-causalidade/"><em>Correlação não implica necessariamente causalidade</em></a><em>, </em>de Marco Filipe:</p><blockquote>Vários estudos apontavam inicialmente que as mulheres em menopausa que recebiam terapia de substituição hormonal (TSH) tinham também um menor risco de doença coronária, o que levou à ideia de que a TSH conferia proteção contra a doença coronária. No entanto, estudos controlados e randomizados (mais rigorosos), feitos posteriormente, mostraram que a TSH causava na verdade um pequeno mas significativo aumento do risco de doença coronária. Uma reanálise dos estudos revelou que as mulheres que recebiam a TSH tinham também uma maior probabilidade de pertencer a uma classe socioeconômica superior, com melhor dieta e hábitos de exercício. A utilização da TSH e a baixa incidência de doença coronária não eram causa e efeito, mas o fruto de uma causa comum — os benefícios associados a um estatuto socioeconômico elevado.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*ggTFzCPAu9OqNnFwrTZcpQ.png" /><figcaption>Fonte: http://comcept.org/cepticismo/correlacao-nao-implica-necessariamente-causalidade</figcaption></figure><p>Os gráficos encontrados no site <a href="https://www.tylervigen.com/spurious-correlations"><em>Spurious correlations</em></a><em> </em>reforçam a ideia de que <strong>correlação não implica necessariamente causalidade</strong>. Temos que ter cuidado pois “nem tudo que parece é”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*8vnDVGxdR_vkm57XPcZu4Q.png" /><figcaption>Fonte: <a href="https://www.tylervigen.com/spurious-correlations">https://www.tylervigen.com/spurious-correlations</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*gJgir5E11xdAz7_MZv7Wxw.png" /><figcaption>Fonte: <a href="https://www.tylervigen.com/spurious-correlations">https://www.tylervigen.com/spurious-correlations</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*sAOBI1kXph_HoJa2PRcvNg.png" /><figcaption>Fonte: <a href="https://www.tylervigen.com/spurious-correlations">https://www.tylervigen.com/spurious-correlations</a></figcaption></figure><p>Cuidado para não errar na interpretação.</p><h3>Calculando a Correlação com o Pandas</h3><p>Já sabemos o básico sobre correlação, agora vamos ao cálculo direto com o auxílio do Pandas. Vou utilizar o exemplo encontrado no artigo “<a href="https://www.datascience.com/learn-data-science/fundamentals/introduction-to-correlation-python-data-science">Introduction to Correlation</a>”, de Ruslana Dalinina, com algumas pequenas modificações.</p><p>O conjunto de dados utilizado “Auto-Mpg Data”, pode ser encontrado <a href="https://archive.ics.uci.edu/ml/datasets/Auto+MPG">aqui</a>.</p><p>A ideia é verificar qual característica do veículo está mais associada ao seu consumo de combustível ( mpg: <strong>m</strong>iles <strong>p</strong>er <strong>g</strong>allon - milhas(1,6 km) por galão( 3,78 litros)).</p><p>Observando as primeiras linhas do dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*j3S3T9rP8NrBFL8DZ3mH_A.png" /></figure><p>Mais algumas informações:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*RwiHQiBfIYagtoJkzqZxAw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*OjOq53_DSmvYhXec8TT1MQ.png" /></figure><h4>Pequeno pré-processamento.</h4><p>Pode-se observar que faltam 6 valores na coluna horsepower. Vamos preencher essas lacunas com a média de potência de acordo com o número de cilindros do motor. Foi a forma que escolhi. Existem várias possibilidades.</p><p>Observando a relação entre o número de cilindros e a potência do motor temos:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8YRgqknytQ9CFEPYtJi6aw.png" /></figure><p>Vamos substituir os valores ausentes pela média:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*fNU_PIrl5Z6LyThqWehWIA.png" /></figure><p>A função para atualizar os valores pode ser vista a seguir:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*nXHspOR3H_dP6ep_Y-zf-g.png" /></figure><p>Após a utilização da função de atualização temos o seguinte resultado:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*6jvwlDKvZ2S7Dve1oj6Ggg.png" /></figure><p>Agora todas as colunas estão completas!</p><p>Eu optei por fazer esse processo, mas o pandas consegue trabalhar bem mesmo com alguns dados ausentes.</p><p>Agora vamos à correlação.</p><h4>Pandas</h4><p>O pandas nos fornece a função <strong>corr()</strong> para calcular a correlação entre duas colunas. Vamos verificar a correlação entre o peso do veículo e seu desempenho mpg:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*7wU_hgzyVAXzd11Tg7s2OQ.png" /></figure><p>Como esperado existe uma forte correlação negativa entre o desempenho e o peso do veículo. Quanto mais pesado menor é o desempenho mpg.</p><p>Pode-se verificar todas as correlações de forma simultânea:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*_cqqFqpBjjqlGnvCGLbcfQ.png" /></figure><p>O método de <strong>Pearson</strong> é utilizado por padrão, mas o pandas permite a utilização de outros índices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*L_Svk0ILGSkIxWZKmoGDCA.png" /></figure><p>Para facilitar a visualização das correlações pode-se recorrer às cores:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*PfN-XMFNiaRO0jFe493Ngg.png" /></figure><p>Pode-se observar a gradação de cores em relação às correlações positivas e negativas.</p><p>Várias informações importantes do conjunto de dados podem ser obtidas simultaneamente com poucas linhas de programação.</p><h3>Conclusão</h3><p>A correlação nos indica a interdependência entre duas ou mais variáveis. É uma informação importante, que pode ser aplicada em várias situações.</p><p>O pandas nos permite obter a correlação de forma rápida, de acordo com o método desejado, mas devemos ter especial atenção à interpretação dos resultados. Como foi dito, correlação não implica necessariamente uma relação de causalidade.</p><p>De forma geral a correlação é mais uma ferramenta que pode nos auxiliar na construção de modelos mais confiáveis.</p><h4>Referências</h4><p><a href="https://www.datascience.com/learn-data-science/fundamentals/introduction-to-correlation-python-data-science">https://www.datascience.com/learn-datscience/fundamentals/introduction-to-correlation-python-data-science</a></p><p><a href="https://bloqm.wordpress.com/2013/10/13/coeficiente-de-correlacao-de-postos-de-spearman/">https://bloqm.wordpress.com/2013/10/13/coeficiente-de-correlacao-de-postos-de-spearman</a></p><p><a href="https://pt.wikipedia.org/wiki/Coeficiente_de_correla%C3%A7%C3%A3o_de_postos_de_Spearman">https://pt.wikipedia.org/wiki/Coeficiente_de_correla%C3%A7%C3%A3o_de_postos_de_Spearman</a></p><p><a href="http://www.statisticshowto.com/kendalls-tau/">http://www.statisticshowto.com/kendalls-tau</a></p><p><a href="http://comcept.org/cepticismo/correlacao-nao-implica-necessariamente-causalidade/">http://comcept.org/cepticismo/correlacao-nao-implica-necessariamente-causalidade</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ec1d48735fb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/brdata/correla%C3%A7%C3%A3o-direto-ao-ponto-9ec1d48735fb">Correlação: direto ao ponto.</a> was originally published in <a href="https://medium.com/brdata">BrData</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Outlier: o ponto fora da curva.]]></title>
            <link>https://medium.com/ensina-ai/outlier-o-ponto-fora-da-curva-1f28f3d9c23?source=rss-6dedcc6de1a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f28f3d9c23</guid>
            <category><![CDATA[outliers]]></category>
            <category><![CDATA[estatistica]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[regressão-linear]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Rodrigo Salles]]></dc:creator>
            <pubDate>Tue, 15 May 2018 10:06:54 GMT</pubDate>
            <atom:updated>2018-06-30T18:27:27.577Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>“Um <em>outlier</em> é uma observação que se diferencia tanto das demais observações que levanta suspeitas de que aquela observação foi gerada por um mecanismo distinto” (Hawkins, 1980).</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*m-sBHPcDkim7D3Tj.jpg" /></figure><p>Como um outlier pode afetar o desempenho do seu algoritmo? Como são gerados? Como detectar? Como tratar? Essas são algumas perguntas que tentarei responder nesse pequeno estudo.</p><p>Este estudo encontra-se disponível no Github. Acesse clicando <a href="https://github.com/RodrigoSalles/Outlier">aqui</a>.</p><h3>O ponto fora da curva</h3><p>Sempre me preocupei com os outliers. Aquele ponto fora da curva…! Como aquele valor anômalo poderia afetar o desempenho do meu sistema? Plotava o gráfico e lá estava ele ou eles. O que fazer? Nunca me dediquei muito ao assunto, e assim utilizava ferramentas para me livrar rapidamente do problema, e passar para partes mais importantes do projeto.</p><p>Com o tempo observei que meus projetos poderiam ganhar em qualidade com a compreensão dos outliers. E é o que vou fazer hoje. Sem rodeios. Direto ao ponto.</p><h3>O que é um outlier?</h3><p>Até agora não encontrei uma tradução perfeita para o termo, mas pode-se dizer que é aquela observação que se diferencia tanto das demais que levanta suspeitas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*0s_CAzYDdDfYaAHMnve_gQ.png" /><figcaption>Fonte: <a href="https://pt.wikihow.com/Calcular-Outliers">https://pt.wikihow.com</a></figcaption></figure><p>Um valor de 300°F em uma tabela que possui valores distribuídos entre 69°F e 73°F levanta suspeitas,não?</p><p>Observem a seguinte tabela:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*uy6tT1y_4-7ZLLJltY4bZQ.png" /><figcaption>Fonte: <a href="https://aquare.la/">https://aquare.la</a></figcaption></figure><p>Precisamos saber qual é o segredo do Sr. Antônio! (Acho que o INSS também vai se interessar). É um outlier que possivelmente resulta de um erro de digitação.</p><p>No estudo “<a href="https://aquare.la/reducao-de-faltas-em-agendamentos-medicos-com-inteligencia-computacional-caso-de-vitoria-es/"><strong><em>Redução de faltas em agendamentos médico com inteligência computacional</em></strong></a><strong><em>”, </em></strong>verificou-se uma senhora “outlier”, de 79 anos, que agendou uma consulta médica com 365 dias de antecedência e de fato compareceu à consulta!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lxc1xITYssFI17Gf.jpg" /><figcaption>Fonte: <a href="https://aquare.la/">https://aquare.la</a></figcaption></figure><p>É um exemplo de outlier que não deriva de erro. É apenas um comportamento atípico. Parabéns para a essa senhora “outlier”( cada falta tem um valor que varia entre R$ 76,00 e R$ 92,00)!</p><p>Bom, acho que os exemplos já tornaram claro o conceito de outlier. Mas quais são os tipos de outliers?</p><h3>Tipos de Outliers</h3><p>Existem dois grandes grupos de outliers: os <strong>univariados</strong> e os <strong>multivariados</strong>. O primeiro caso é detectado ao se analisar a distribuição de uma variável simples: analisando apenas a distribuição de idades pode-se verificar a presença do outlier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*S4cRVBYskjVDDSl-Z0ujuQ.png" /></figure><p>O outlier multivariado pode ser detectado em espaço “n-dimensional”. Para sua observação deve-se recorrer à distribuições multidimensionais.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*i3V-aEfTZEvnuYxpwJ3bkg.png" /></figure><p>A imagem acima representa a distribuição dos preços de automóveis de acordo com o ano de fabricação. Pode-se observar um autlier. Por algum motivo um automóvel fabricado em 1986 está avaliado em R$ 25.000,00. Pode ser um carro raro, de colecionador, ou simplesmente um erro de digitação. O valor correto poderia ser R$ 2500,00.</p><p>Analisando os exemplos anteriores levantamos algumas possibilidades sobre as origens desses outliers. Vamos falar um pouco mais sobre isso.</p><h3>O que causa um outlier?</h3><p>O correto entendimento da causa de um valor anômalo pode nos orientar sobre a forma correta de tratá-los.</p><p>Quanto à causa temos dois grupos de outliers: naturais e artificiais.</p><p>Exemplos de outliers<strong> naturais</strong>:</p><ul><li>A senhora que compareceu á consulta, no exemplo dado anteriormente.</li><li>Declaração de renda, quando verdadeiramente a pessoa se saiu muito melhor, ou pior do que o restante de pessoas de seu perfil econômico.</li><li>Uma idade mais avançada ao se analisar a expectativa de vida para determinada região.</li></ul><p>Grande parte dos outliers possuem origem <strong>artificial</strong>(erro):</p><ul><li><strong>Erro de amostragem</strong>: ao avaliar a média nas notas em física, normalmente baixas, algumas notas de educação física foram incluídas.</li><li><strong>Erro ao processar dados</strong>: ao fazer o pré-processamento dos dados pode-se utilizar algum método que crie um outlier.</li><li><strong>Erro na entrada de dados</strong>: erros de digitação ou coleta de informações.</li><li><strong>Erro de medida</strong>: são os mais comuns. Instrumentos danificados ou usados de forma incorreta são fontes constantes de outliers.</li><li><strong>Erro intencional</strong>: ao verificar-se a quantidade de álcool ingerida na última semana em uma classe de jovens, a maior parte intencionalmente, fornece valores abaixo dos reais. Dessa forma, um jovem que fornece os valores reais aparecerá como um outlier.</li></ul><p>Agora que já sabemos um pouco mais sobre as origens dos outliers, vamos entender o que eles podem provocar no nosso algoritmo.</p><h3>Efeito outlier</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*uHLr_3ktmlnrYatx.jpg" /><figcaption>Fonte: <a href="https://www.misteriosdouniverso.net/2015/04/o-que-e-o-efeito-borboleta.html">https://www.misteriosdouniverso.net</a></figcaption></figure><p>É quase um efeito borboleta. Um pequeno erro inicial que se propaga, e se não for tratado de forma correta pode criar muito problema.</p><p>Em análises estatísticas o efeito do outlier pode ser facilmente observado. Vamos fazer o “com” e “sem” outliers em uma tabela de idades, para observar um pouco melhor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/194/1*O2o-J6lcSecG37niE9hLLw.png" /></figure><p>E agora, novamente o Sr. Antônio modificando quase tudo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/204/1*7wr29KfKnPS3Ehacd_kvfQ.png" /></figure><p>A média, os desvios e a amplitude são especialmente sensíveis aos outliers.</p><p>De forma semelhante muitos algoritmos são afetados por valores anômalos. Esse comportamento será demonstrado com a regressão linear simples.</p><p>A regressão linear é uma técnica de aprendizado supervisionado que estuda o relacionamento entre uma variável dependente e outras variáveis, chamadas independentes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*IXMtSNN1luriofAResPRjA.png" /></figure><p>Não entrarei em maiores detalhes sobre a técnica, mas basicamente o algoritmo constitui uma tentativa de estabelecer uma equação matemática linear (linha reta) que descreva o relacionamento entre as variáveis X e Y.</p><p>O desafio é determinar os coeficientes <strong>a</strong> e <strong>b </strong>da equação de regressão (Y=a+b.X), de maneira que o desvio(erro) entre o valor encontrado pela equação e o valor real seja o menor possível.</p><p>Os coeficientes <strong>a</strong> e <strong>b</strong> são ajustados de acordo com o conjunto de treinamento:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/238/1*GWSnD_ILEVWZjcE_k8dyFg.png" /></figure><p>Como existem valores anômalos no conjunto de treinamento utilizado, o desvio encontrado pelo algoritmo será grande, e na tentativa de reduzir o erro, os valores encontrados para os parâmetros <strong>a</strong> e <strong>b</strong> não serão os melhores.</p><p>O efeito dos outliers pode ser observado nos gráficos a seguir:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*FdI3Mo9BXC9nPUpGrirUwQ.png" /></figure><p>O erro absoluto: <strong>29.8800 u</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*DcoiEPCZTHNIyUPonOJ1cg.png" /></figure><p>Erro absoluto: <strong>152.1535 u</strong></p><p>O mesmo teste poderia ser realizado com outros algoritmos, demonstrando uma maior ou menor sensibilidade.</p><p>Regressão linear é um algoritmo reconhecidamente sensível aos outliers, dessa forma, vários cuidados devem ser adotados para tornar o seu sistema mais resistente. Em projetos mais complexos, deve-se ficar atendo para a presença inicial ou o surgimento de outliers. Muitas técnicas podem ser adotadas para sua detecção. Vamos falar de algumas.</p><h3>Como detectar outliers?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/0*kNOEO4PlFPALVE0M.png" /></figure><p>Vamos falar um pouco sobre técnicas que podem ser utilizadas para detectar aquela ovelha negra do seu conjunto de dados.</p><p>A forma mais comum de se detectar outliers é com o auxílio do <strong>box-plot</strong> e<strong> scatter plot.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*LAkI8olfHKJ4h7VEM2-KnQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*ZYKDfzlgX0d-uNMDXRSJjA.png" /></figure><p>Fora as ferramentas gráficas, podemos utilizar cálculos que podem ser acrescentados às nossas rotinas, tornando o tratamento dos outliers mais eficiente. Na sequência vou demonstrar como detectar outliers com o auxílio do quartil.</p><h4>Amplitude interquartílica: limites internos e externos</h4><p>Considere as temperaturas fornecidas por sensores em um determinado ambiente:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/219/1*ypDT0FJpJz3isqBON2J2gA.png" /></figure><p>Pode-se facilmente observar um outlier. O sensor 10 fornece 300°C em um ambiente com temperaturas a variar entre 69°C e 73°C.</p><p>Vamos utilizar a amplitude interquartílica para determinar esse valor anômalo.</p><p>Para observar melhor vamos colocar os dados em ordem crescente:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*po6P65tK-rLbdhlkDIRxgw.png" /></figure><p>Em um conjunto de dados extenso essa medida já nos dá uma boa ideia dos outliers.</p><p>Ao calcular a mediana obtemos o seguinte resultado:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*J-T6TMX6xUKSWDqhICJxdw.png" /></figure><h4>Quartil</h4><p>O <strong>quartil</strong> pode ser entendido como uma generalização da mediana. O quartil é o valor abaixo do qual está um certo percentual dos dados. No caso da mediana, esse percentual é de 50%. A função utilizada para calcular o quartil(series.quantile), por padrão, adota o percentual de 50%, ou seja, é uma mediana. Vamos configurar a função para calcular o quartil à 25%. É o quartil inferior, e representado por Q1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*YXJmvUBWrxBQd1nxT7BHHg.png" /></figure><p>Vamos agora calcular o quartil superior, Q3, que é a mesma operação à 75%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*gfGnyFqiS1W7o5Klr62nFg.png" /></figure><p>Ao subtrair os valores de Q3 e Q1, obtemos a <strong>amplitude interquartílica</strong>. Essa amplitude deve ser multiplicada por 1.5, e o valor obtido deve ser subtraído de Q1, e somado à Q3. É a barreira interna. Os valores que estiverem entre a barreira interna e externa são considerados outliers moderados.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*WOKUnQqYO2s7tQMI1z-YnA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*uXoZUz7NQ5-et3KW2LJ-dQ.png" /></figure><p>Para calcular a barreira externa deve-se proceder da mesma forma. A única diferença é que o fator de multiplicação deve ser 3 e não 1.5:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*EwrrgEoXT8hDinyvOd5VzA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*fKgIQQ_8oDgX7N8CiCCJSg.png" /></figure><p>Dessa forma o valor fornecido pelo sensor 10, de 300°C, está completamente fora da barreira externa, sendo caracterizado como outlier.</p><p>Existem outras forma de detecção. Os outliers bivariados e multivariados são normalmente medidos usando um índice distância. Índices como a distância de <a href="https://www.steffenruefer.com/2016/12/outlier-detection-with-mahalanobis-distance/">Mahalanobis</a> e <a href="http://www.statisticshowto.com/cooks-distance/">Cook D</a> são frequentemente utilizados para detectar outliers.</p><p>Já detectamos o outlier. E agora? Como resolver esse problema?</p><h3>Outlier detectado. E agora?</h3><p>O que fazer com o valor detectado. Temos algumas possibilidades:</p><ul><li><strong>Eliminar o valor:</strong> se nosso conjunto de dados é grande o suficiente, poderemos simplesmente deletar os valores anômalos sem maiores prejuízos para a análise.</li><li><strong>Transformação logarítmica: </strong>a transformação logarítmica dos dados pode reduzir a variação causada por valores extremos.</li><li><strong>Filtragem de dados:</strong> alguns filtros podem ser utilizados, como o média-móvel.</li><li><strong>Tratamento separado: </strong>se a quantidade de outliers é significante, podemos tratá-los separadamente. Podemos separar os valores em dois grupos e criar modelos individuais.</li></ul><p>Devemos lembrar que o outlier pode ser objeto de nossa procura. Pode ser aquela compra fora dos padrões que indicará que o cartão de créditos foi clonado. Pode ser o valor a indicar uma nova solução para antigos problemas.</p><h3>Conclusão</h3><p>Existem muitas ferramentas que nos auxiliam no tratamento de outliers. Se o conjunto de dados possui muitos valores anômalos, ferramentas que usam média e variância podem não funcionar bem. Para esses casos o <a href="http://scikit-learn.org/stable/modules/preprocessing.html">RobustScaler</a> pode ser uma ótima alternativa. Em sua maioria essas ferramentas são de rápida e fácil implementação, mas é importante o conhecimento um pouco mais aprofundado do problema. O que causou o valor estranho, qual seu impacto no algoritmo, seu tratamento. O conhecimento torna seu sistema mais robusto. No meu caso ajudou muito. Espero que o ajude também. Até a próxima.</p><h4>Referências:</h4><p><a href="https://aquare.la/o-que-sao-outliers-e-como-trata-los-em-uma-analise-de-dados/">https://aquare.la/o-que-sao-outliers-e-como-trata-los-em-uma-analise-de-dados/</a></p><p><a href="https://www.analyticsvidhya.com/blog/2016/01/guide-data-exploration/#three">https://www.analyticsvidhya.com/blog/2016/01/guide-data-exploration/#three</a></p><p><a href="https://pt.wikihow.com/Calcular-Outliers">https://pt.wikihow.com/Calcular-Outliers</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f28f3d9c23" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ensina-ai/outlier-o-ponto-fora-da-curva-1f28f3d9c23">Outlier: o ponto fora da curva.</a> was originally published in <a href="https://medium.com/ensina-ai">Ensina.AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Science aplicado à manutenção preditiva: bombas d’água na Tanzânia.]]></title>
            <link>https://medium.com/ensina-ai/data-science-aplicado-%C3%A0-manuten%C3%A7%C3%A3o-preditiva-bombas-d%C3%A1gua-na-tanz%C3%A2nia-32a85de8b41?source=rss-6dedcc6de1a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/32a85de8b41</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[bomba-dágua]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[manutenção-preditiva]]></category>
            <category><![CDATA[features-categóricas]]></category>
            <dc:creator><![CDATA[Rodrigo Salles]]></dc:creator>
            <pubDate>Sat, 28 Apr 2018 15:53:40 GMT</pubDate>
            <atom:updated>2018-10-13T13:35:36.329Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WFm1bFgpwWo4nS4FRx8w_Q.png" /></figure><p><em>É possível predizer, a partir de dados reais, qual bomba d&#39;água está a funcionar corretamente, qual precisa de reparos e qual está fora de operação?</em></p><p>Este projeto encontra-se disponível no Github. Acesse clicando <a href="https://github.com/RodrigoSalles/Tanzania_water_Pump">aqui</a>.</p><p>Uma parte do estudo foi realizada no Colaboratory. Não sabe o que é? <a href="https://medium.com/@BrData/deep-learning-colaboratory-a3fdf5932425">Aqui</a> tem um pequeno tutorial.</p><h3><strong>O problema da escassez de água no mundo</strong></h3><p><em>Terra…planeta água…!</em></p><p>O planeta água que Guilherme Arantes descreve em sua canção possui mais de 70% de sua superfície coberta por água. O grande problema é que desse total apenas 3% podem ser consideradas apropriadas para o consumo humano. Em um mundo com aproximadamente 7,6 bilhões de pessoas, mais de 1 bilhão enfrentam problemas de acesso à água. Para 2,7 bilhões ela falta ao menos um mês por ano.</p><p>De acordo com projeções da ONU a demanda por água doce vai superar o abastecimento em 40% no ano de 2030. Dessa forma várias cidades do mundo correm o risco de ficar sem água.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*r57x9olD2UbhAjzM.jpg" /></figure><p>O dia 21 de abril de 2018 foi considerado o “dia zero” para a Cidade do Cabo, na África do Sul. A previsão era de que nesse dia as torneiras dessa importante cidade poderiam parar de fornecer água. Na data em que escrevo esse texto ainda não sei o que de fato aconteceu no “dia zero”, mas as perspectivas são assustadoras. No mesmo patamar encontram-se muitas outras cidades como Tóquio, Moscou, Pequim e São Paulo.</p><p>Em determinados lugares essa crise pode apresentar contornos mais dramáticos. Em certos países a crise hídrica pode ter seus efeitos potencializados pelas eternas crises financeiras, humanitárias, guerras, etc.</p><p>Nesse contexto encontramos a Tanzânia.</p><h3>O problema da escassez de água na Tanzânia</h3><p>A República Unida da Tanzânia é um país da África Oriental. É um estado unitário composto por 26 regiões, e além de sua parte continental, inclui o arquipélago de Zanzibar, no Oceano Índico.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*ojXnFV8hGBEqWcLiyVCQIA.png" /></figure><p>Como muitas nações pelo mundo a Tanzânia sofre com sérios problemas envolvendo o fornecimento de água. Em um país com um terço de suas regiões de clima árido ou semiárido, encontrar água potável não é uma tarefa simples.</p><p>Na imagem a seguir é possível verificar os três maiores lagos da Tanzânia: ao norte o lago Victoria, a oeste o lago Tanganyika e ao sul o lago Malawi. Esses três reservatórios abastecem um grande número de pessoas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*zX2SW-nnnSW4Tc8gtlej_w.png" /></figure><p>Dessa forma se você não mora próximo de um dos três maiores lagos do país, você certamente enfrentará sérios problemas para conseguir água!</p><p>E quais são as alternativas para essas pessoas? Não são muitas as possibilidades, mas a melhor delas é a utilização de águas subterrâneas.</p><p>As águas subterrâneas representam a melhor possibilidade, mas o processo não é tão simples. Para se estabelecer um ponto de abastecimento se faz necessário um investimento inicial considerável, e um sistema de manutenção eficiente.</p><p>Vários pontos de abastecimentos foram construídos na Tanzânia. São insuficientes, mas já auxiliam muitas pessoas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*a3kMg8SMjqNxh5DWbNgq-A.png" /></figure><p>No mapa acima estão representados os estados do país e a cobertura dos pontos de abastecimento.</p><p>Com o primeiro passo dado (mesmo de forma tímida), o seguinte é estabelecer um sistema eficiente de manutenção. Um sistema eficiente pode garantir água potável para milhares de pessoas.</p><p>Um ponto de abastecimento pode parar de funcionar, ou funcionar abaixo de sua capacidade por vários motivos. Especificamente nos pontos de abastecimentos estabelecidos na Tanzânia, os principais problemas são: torneiras quebradas, bombas quebradas, canos quebrados, fonte de abastecimento danificada e roubo de bombas d’água.</p><figure><img alt="Resultado de imagem para water pump in tanzania" src="https://cdn-images-1.medium.com/proxy/1*acjGajb52gNQ1iuYGKKJjg.jpeg" /></figure><p>A forma de manutenção mais comum adotada é a corretiva. É a forma mais primária de manutenção, e pode ser resumida no ciclo “quebra-repara”. É a forma mais cara, e no caso de um ponto de abastecimento, representa pessoas sem água potável, para suas necessidades básicas, por determinado tempo.</p><p><strong>Seria possível implementar um sistema de manutenção preditiva a partir de dados coletados dos pontos de abastecimento?</strong></p><h3>Objetivo</h3><p>O objetivo desse pequeno projeto é prever, a partir de dados reais, quais bombas d’água estão a funcionar de forma correta, quais estão a necessitar de manutenção e quais não funcionam. É um caso de Data Science aplicado à manutenção preditiva.</p><p>A manutenção preditiva faz o acompanhamento periódico das máquinas, baseando-se na análise de dados coletados por meio de monitoramentos ou inspeções em campo. O principal objetivo da manutenção preditiva é a verificação pontual dos equipamentos a fim de antecipar eventuais problemas que possam causar gastos maiores com manutenções corretivas.</p><p>Ao antecipar os problemas os custos de manutenção são reduzidos, e o abastecimento de água potável garantido.</p><h3>Conhecendo os dados</h3><p>Os dados utilizados foram fornecidos por <a href="http://taarifa.org/"><strong>Taarifa</strong> </a>e <a href="http://maji.go.tz/"><strong>Tanzanian Ministry of Water </strong></a>. São dados reais coletados nos pontos de abastecimento.</p><p>O conjunto de dados(data) utilizado é composto pelas seguintes informações:</p><ul><li><strong>id</strong> — Número de identificação do ponto de abastecimento;</li><li><strong>amount_tsh</strong> — quantidade de água disponível para o ponto de abastecimento;</li><li><strong>date_recorded</strong> — Data de gravação dos dados;</li><li><strong>funder</strong> — Quem financiou o ponto de abastecimento;</li><li><strong>gps_height</strong> — Altitude do ponto de abastecimento;</li><li><strong>installer</strong> — Organização que instalou o ponto de abastecimento;</li><li><strong>longitude</strong> — Coordenadas do GPS — longitude;</li><li><strong>latitude</strong> — Coordenadas do GPS — latitude;</li><li><strong>wpt_name</strong> — Nome do ponto de abastecimento, se houver um nome;</li><li><strong>num_private</strong> — Sem informações sobre essa coluna;</li><li><strong>basin</strong> — Bacia hidrográfica;</li><li><strong>subvillage</strong> — Localização geográfica;</li><li><strong>region</strong> — Localização geográfica;</li><li><strong>region_code</strong> — Localização geográfica (código);</li><li><strong>district_code </strong>— Localização geográfica (código);</li><li><strong>lga</strong> — Localização geográfica;</li><li><strong>ward</strong> — Localização geográfica;</li><li><strong>population</strong> — População nos arredores do ponto de abastecimento;</li><li><strong>public_meeting</strong> — True/False;</li><li><strong>recorded_by</strong> — Grupo que inseriu os dados;</li><li><strong>scheme_management</strong> — Quem opera o ponto de abastecimento;</li><li><strong>scheme_name</strong> — Quem opera o ponto de abastecimento;</li><li><strong>permit</strong> — Se o ponto de abastecimento é permitido;</li><li><strong>construction_year</strong> — Ano de construção do ponto de abastecimento;</li><li><strong>extraction_type</strong> — Tipo de extração utilizado no ponto de abastecimento;</li><li><strong>extraction_type_group</strong> — Tipo de extração utilizado no ponto de abastecimento;</li><li><strong>extraction_type_class</strong> — Tipo de extração utilizado no ponto de abastecimento;</li><li><strong>management</strong> — Como o ponto de abastecimento é gerenciado;</li><li><strong>management_group </strong>— Como o ponto de abastecimento é gerenciado;</li><li><strong>payment</strong> — Custos da água;</li><li><strong>payment_type</strong> — forma de pagamento;</li><li><strong>water_quality</strong> — A qualidade da água;</li><li><strong>quality_group</strong> — A qualidade da água;</li><li><strong>quantity</strong> — A quantidade de água;</li><li><strong>quantity_group</strong> — A quantidade de água;</li><li><strong>source</strong> — A fonte do ponto de abastecimento;</li><li><strong>source_type</strong> — A fonte do ponto de abastecimento;</li><li><strong>source_class</strong> — A fonte do ponto de abastecimento;</li><li><strong>waterpoint_type</strong> — O tipo de ponto de abastecimento;</li><li><strong>waterpoint_type_group</strong> — O tipo de ponto de abastecimento.</li></ul><p>O estado atual do ponto de abastecimento(target) é descrito como:</p><ul><li><strong>functional </strong>— Está a funcionar em sua totalidade;</li><li><strong>non functional </strong>— Completamente parado;</li><li><strong>functional needs repair </strong>— Funcionando, mas necessitando de manutenção.</li></ul><p>Pode-se observar que muitas informações são categóricas. Essa característica requer especial atenção.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*M7D73mVk6oufuQ3NzHV-Rw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/169/1*E62M5vZOVxXr6CcUVfROUA.png" /></figure><p>Uma observação mais detalhada no estado de funcionamento revela que boa parte das bombas estão paradas:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*CS6VkOnJNY33rXGOta1J5A.png" /></figure><p>Levando em consideração que os pontos necessitam de manutenção, e que a manutenção exige recursos financeiros, a “forma de pagamento” nos dá uma informação importante:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*yEh-uLUef3I85pW5LdODIw.png" /></figure><p>Boa parte dos pontos de abastecimento nunca recebem pagamento por sua utilização.</p><p>Ao representar a relação entre estado funcional e forma de pagamento, temos uma visão mais clara:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*ac-7I3Jxjhz0VnMghd_STA.png" /></figure><p>Boa parte dos pontos que não recebem pagamento estão parados. Uma possível explicação para essa característica seria a ausência de recursos para manutenção. Quando existe alguma forma de pagamento, o estado funcional se modifica.</p><p>Uma característica que pode ser importante é a quantidade de água disponível. Quando a quantidade é suficiente a maior parte dos pontos estão funcionando. Se justifica ter mais cuidado com esse pontos. Quando está seco, logicamente, o ponto não está a funcionar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*F_h7ymFMkwA52zkClhE0hg.png" /></figure><p>Terminada essa observação inicial, vamos à limpeza dos dados.</p><h3>Limpeza de dados</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Yx3dnDB2mlXeUyG4.jpg" /></figure><p>Observando o conjunto de dados, vemos que várias colunas de informações estão incompletas, e muitas são categóricas. Existem muitas possibilidades para resolver esses problemas. Com vantagens e desvantagens. Vamos adotar uma estratégia e verificar os resultados.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*B-QM5CSDCzvc_jALOVHIDw.png" /></figure><h3>Informações que não “agregam valor”</h3><p>No conjunto de dados possivelmente algumas categorias não carregam informações relevantes, e podemos passar bem sem elas. No primeiro momento pode-se destacar <em>wpt_name</em> e <em>recorded_by. </em>Acredito não ser de muita importância para a condição de funcionamento do ponto de abastecimento o conhecimento do seu nome. No caso de <em>recorded_by, </em>toda a coluna foi preenchida com <em>GeoData Consultants Ltd. </em>Não agrega nada de valor para o algoritmo. Dessa forma essas duas colunas serão eliminadas:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*HsQx1D8mMlt08WZh-EiZeg.png" /></figure><h3>Informações incompletas</h3><p>Algumas colunas estão incompletas:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*Kz52q86LXhCZjVn8lW2qFA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*tzs0e1liq-AnZhR1wkStYQ.png" /></figure><p>As colunas incompletas são:</p><ul><li>funder</li><li>installer</li><li>subvillage</li><li>public_meeting</li><li>scheme_management</li><li>scheme_name</li><li>permit</li></ul><p>Vamos completar essas lacunas com “SI”(sem informações):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*yH_Zoz_ttA_qO8oby8gVLg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*RiF5NPxXGeclxNhD8Cd1mA.png" /></figure><p>Agora…às informações categóricas.</p><h3>Limpeza de dados: tratamento de informações categóricas</h3><p>Como foi o observado anteriormente, muitas das informações são categóricas. Esses dados representam problemas para os algoritmos, que em sua grande maioria trabalham de forma algébrica.</p><p>As categorias podem representar problemas, que seriam simples para seres humanos: uma categoria “carros” poderia conter “Ferrari” e “Brasília”, que para a maioria das pessoas possuem diferenças claras, a começar pelo preço.<br>Para o computador são apenas carros. Para a representação, e diferenciação, devemos acrescentar informações extras, como preço, potência, modelo, etc.</p><p>Existem várias técnicas para tratar informações categóricas: numeração de categorias, one hot encoding, feature hashing, etc. Cada técnica possui vantagens e desvantagens. Por exemplo, a numeração de categorias é fácil de ser implementada, mas possui a desvantagem de que algoritmos podem “ver” uma maior similaridade em categorias com valores próximos. O famoso “one-hot-encoding” também é de simples implementação mas deve-se ficar atento para a real possibilidade de overfitting, maior dimensionalidade do problema e maior consumo de recursos computacionais.</p><h3>Estratégia para tratamento de informações categóricas</h3><p>Como foi exposto anteriormente, muitas são as possibilidades de tratamento de informações categóricas. E como toda escolha acarreta uma perda…vamos à nossa.</p><p>Para codificar nossas features vamos utilizar o one-hot encoding <strong>get_dummies. </strong>Seu funcionamento é bem simples: Uma nova coluna para cada subgrupo da coluna original.</p><p>No exemplo a seguir uma nova coluna com zeros e uns foi criada para cada estado da tabela original:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*tJP1hJKfbOgZWBnykQvxLw.png" /></figure><p>O problema da dimensionalidade começar a dar as caras. Observe um exemplo de nosso conjunto de dados:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*iQa1jJoG_9mKIIcRbAKLtQ.png" /></figure><p>Várias categorias aparecem apenas uma vez. Milhares de novas colunas seriam criadas.</p><p>Vamos verificar, no conjunto de dados, a existência de categorias que aparecem apenas uma vez:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*CF2PEK1mChbGkrB_N9LOrQ.png" /></figure><p>Como resultado temos:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*3d6hC89ysBMH03BgvaDGZg.png" /></figure><p>Pode-se verificar que os grupos “funder”, “installer”, “subvillage”,”ward” e “scheme_name” possuem muitas categorias unitárias.</p><p>Para amenizar esse problema vou agrupar todos os casos raros em um grupo “raro”, antes da codificação. O caso “date_recorded” será tratado à parte.</p><p>Como limite adotei o valor 50. Todos os nomes que possuírem frequência inferior ao limite serão agrupados em “raros”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*aweBmqieffF5gpWDN9HRmw.png" /></figure><h3>Tratando datas</h3><p>Antes de codificar as informações categóricas vamos tratar as datas. De forma semelhante às informações categóricas, existem muitas técnicas para tratar datas, anos, etc. A forma que adotei será demonstrada a seguir.</p><p>No conjunto de dados temos “date_recorded” que é a data de gravação dos dados, e “construction_year” que é o ano de construção do ponto de abastecimento. No primeiro caso o formato é “ano-mês-dia”. No segundo caso é apenas o valor do ano de construção.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*VzgHhPV4uJxMnykQQwoK-A.png" /></figure><p>Para o “date_recorded”, seus valores serão substituídos pelos meses passados até a data de referência: 2018–01–01.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*CmiKXP93aTHEbA56yxQmNw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*ucd4xb93d8zt5p9xVp0-6Q.png" /></figure><p>Para “construction_year”, Vamos atualizar os valores da coluna com os anos em relação à referência 2018.</p><p>Um pequeno problema que deve ser tratado é a presença de valores nulos no conjunto de dados. Esses valores poderiam induzir o algoritmo a identificar padrões inexistentes. Vou substituir esse valores pela média do conjunto.</p><p>Verificando a média temos:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/307/1*qo7j9gyzC1pqSMSiifoXMA.png" /></figure><p>Essa média está muito baixa. Isso pode ser explicado pela presença de muitos zeros na coluna.</p><p>Vamos calcular a média dos valores não nulos:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*Une8eaWM-4qm284dm2ySdw.png" /></figure><p>Vamos substituir os valores nulos pela média do conjunto:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*avn5rC6iG5o5fK5IP_on7g.png" /></figure><p>Com a coluna completa podemos contar os anos em relação à referência:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*QhggiCDKAQ3BMMK6uJ8s3Q.png" /></figure><p>Como resultado temos:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*KQmv5RBg6RpFFuoMqFChrw.png" /></figure><h3>cat.codes e get_dummies</h3><p>Agora que os dados estão preparados, vamos utilizar dois métodos para codificar as informações categóricas. Para a coluna com muitos subgrupos vamos simplesmente enumerá-los, com o auxílio da função <strong><em>cat.codes</em></strong>. Para a coluna com poucos subgrupos vamos usar o <strong><em>get_dummies</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*f0SeJ1nC6fkpdGPYG9QilA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*2NCO-ugk-pieEbK07abJrQ.png" /></figure><p>Dessa forma obtemos o seguinte resultado:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*88y88wKAw6ItC_MxdHfT4w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*cH605NsRBXSOuKKxKf5ZbA.png" /></figure><h3>Uma informação interessante: gps_height</h3><p>Ao observar uma descrição da coluna <em>gps_height</em>, notamos que o valor mínimo é de -90,0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*wLWzN9VqMm9EW11KkacOsw.png" /></figure><p>Mas ao pesquisar algumas informações sobre a Tanzânia, vemos o seguinte:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*hbakoYShAD_paJQhMF-bNA.png" /></figure><p>Dessa forma o ponto mais baixo do país é o nível do mar. Possivelmente foi um erro de digitação. Vou atualizar os valores das colunas com seus módulos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*LC8X7JgQV0nvOjUKpum72w.png" /></figure><h3>Estado funcional</h3><p>Como foi mostrado no início do estudo, o estado funcional do ponto de abastecimento é descrito como:</p><ul><li>functional — Está a funcionar em sua totalidade;</li><li>non functional — Completamente parado;</li><li>functional needs repair — Funcionando, mas necessitando de manutenção.</li></ul><p>Esses grupos serão enumerados:</p><ul><li>functional : 0</li><li>functional needs repair : 1</li><li>non functional: 2</li></ul><p>Dessa forma teremos:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/1*smi-T91nynyATQC_I575hA.png" /></figure><p>Agora que os dados já estão no formato desejado, vamos ao classificador!</p><h3>Criando o classificador</h3><p>Para fazer a previsão do estado funcional dos pontos de abastecimento vou utilizar dois algoritmos: Regressão logística multinomial e Random Forest.</p><h4>Regressão Logística Multinomial</h4><p>A regressão logística é uma técnica estatística que tem como objetivo produzir, a partir de um conjunto de observações, um modelo que permita a predição de valores tomados por uma variável categórica, a partir de uma série de variáveis.</p><p>É possível estimar uma regressão logística em que a variável dependente tem mais de duas categorias. Ou seja, o modelo logístico pode ser estendido quando a variável de resposta qualitativa tem mais do que duas categorias. É a regressão logística multinomial. No nosso caso essas categorias são os estados funcionais dos pontos de abastecimento.</p><p>São geradas k — 1 equações, sendo k o número de categorias. As equações geram probabilidades para predizer se uma categoria está acima/abaixo da categoria de referência.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*0bRXV4ZsPwxq92DfXU-taQ.png" /></figure><p>Nesse primeiro teste obtivemos uma precisão de aproximadamente 72%.</p><p>Para ter uma melhor ideia do desempenho do classificador vamos utilizar o método de validação cruzada, em que diferentes partes do conjunto de dados são utilizados para treinar e avaliar a precisão do classificador.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*3NIMYxFsX2lDaKBrf6eGrg.png" /></figure><p>Foram realizadas 10 avaliações em diferentes partes e a média dos resultados foi confirmada em aproximadamente de 72%.</p><h4>Random Forest</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/0*XjN7xeNwEuSEljtM." /></figure><p>O algoritmo Random Forest é um tipo de ensemble learning, método que gera muitos classificadores e combina o seus resultados.</p><p>No caso do Random Forest, o algoritmo gera várias árvores de decisão, e combina o resultado da classificação de todas elas. Essa combinação de modelos, o torna muito mais poderoso do que o algoritmo Decision Tree convencional.</p><p>Por ser um conjunto de Decision Trees, o classificador RandomForestClassifier possui vários fatores adicionais. Dentre esses fatores pode-se destacar:</p><p><strong>n_estimators</strong>: É o número de estimadores (Decision Trees) que serão utilizados pelo Random Forest.</p><p><strong>n_jobs</strong>: É o número de execuções em paralelo que serão usadas pelo modelo. Ao passar -1, o valor será igual ao número de núcleos do computador utilizado. Quanto mais “paralelizado” for a execução, mais rápida ela será, desde que a máquina suporte.</p><p><strong>max_features</strong>: É o número de features que será utilizado por cada Decision Tree interna, são sorteadas features diferentes para cada árvores, justamente para serem classificadores diferentes.</p><p>Utilizando 20 estimadores obtivemos o seguinte resultado:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*kkEZLWw62dpVUfWamyUoqg.png" /></figure><p>Aproximadamente 80% de acerto. Representa uma sensível melhora em relação à regressão logística.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*tCvzZk5C8R1eq4oyBur3Ug.png" /></figure><p>A validação cruzada confirma o resultado em aproximadamente <strong>80%</strong>.</p><h3>Pode melhorar?</h3><p>O desempenho dos classificadores poderia ser melhorado? Penso que sim.</p><p>Algumas possibilidades:</p><ul><li>As informações categóricas poderia ser tratadas de formas diferentes. Acho que o método <strong>hashing trick </strong>poderia melhorar o desempenho;</li><li>Muitas informações poderiam ser normalizadas;</li><li>Mais informações poderiam ser descartadas;</li><li>Mais dados poderiam ser levantados para amparar os algoritmos. Possivelmente criar novas features;</li><li>Utilizar algoritmos de classificação diferentes. Uma RNA poderia apresentar um desempenho melhor.</li></ul><p>São muitas as possibilidades de melhorias, mas implementá-las agora deixaria esse estudo muito extenso. Fica para o “<em>Bombas d´água da Tanzânia, parte II”</em>.</p><h3>Conclusão</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X3fcKZnQAsOZUWhH.jpg" /></figure><p>Esse estudo se propôs a avaliar a possibilidade de implementação de um sistema de manutenção preditiva de bombas d’água na Tanzânia. Por se tratar de um país que enfrenta sérias dificuldades em relação ao abastecimento de água, um sistema eficiente de manutenção dos pontos de abastecimento pode ser de grande importância.</p><p>Os resultados mostraram que é possível aproximar o momento correto de realizar-se a manutenção dos pontos de abastecimento. Com essa informação pode-se reduzir os custos de manutenção e o tempo que o ponto fica fora de operação.</p><p>Os dados coletados de forma presencial ou remota poderiam ser tratados e rapidamente alertar para a necessidade de manutenção, tendo ainda em vista que melhorias no tratamento dos dados e no projeto dos algoritmos poderiam tornar o sistema mais eficiente.</p><p>O estudo caracteriza um bom exemplo da aplicação dos conhecimentos de Data Science em problemas reais, com importantes consequências sociais.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32a85de8b41" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ensina-ai/data-science-aplicado-%C3%A0-manuten%C3%A7%C3%A3o-preditiva-bombas-d%C3%A1gua-na-tanz%C3%A2nia-32a85de8b41">Data Science aplicado à manutenção preditiva: bombas d’água na Tanzânia.</a> was originally published in <a href="https://medium.com/ensina-ai">Ensina.AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>