<?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 Luis Eduardo on Medium]]></title>
        <description><![CDATA[Stories by Luis Eduardo on Medium]]></description>
        <link>https://medium.com/@luis.eduardo?source=rss-efe8cdb02770------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*THmS2WqUFZux8WeM.jpg</url>
            <title>Stories by Luis Eduardo on Medium</title>
            <link>https://medium.com/@luis.eduardo?source=rss-efe8cdb02770------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 04:54:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@luis.eduardo/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[Como o Aprendizado de Máquina pode ser aplicado no mercado imobiliário]]></title>
            <link>https://medium.com/neuronio-br/como-o-aprendizado-de-m%C3%A1quina-pode-ser-aplicado-no-mercado-imobili%C3%A1rio-ee04da21d1b3?source=rss-efe8cdb02770------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee04da21d1b3</guid>
            <category><![CDATA[aprendizado-de-maquina]]></category>
            <category><![CDATA[modelo-de-predição]]></category>
            <category><![CDATA[house-prices]]></category>
            <category><![CDATA[xgboost]]></category>
            <dc:creator><![CDATA[Luis Eduardo]]></dc:creator>
            <pubDate>Tue, 06 Aug 2019 16:33:27 GMT</pubDate>
            <atom:updated>2019-08-06T16:33:27.790Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>Nota</strong>: uma versão em inglês deste artigo está disponível em “<a href="https://medium.com/neuronio/creating-a-ml-model-to-predict-house-prices-d047ce22abd5">How Machine Learning can be applied to the real state market</a>”.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gxVQ-IENaBwQz_Zs" /><figcaption>Photo by <a href="https://unsplash.com/@brenoassis?utm_source=medium&amp;utm_medium=referral">Breno Assis</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Se você já comprou ou vendeu alguma coisa, é provável que tenha se deparado com uma questão: Qual o valor desse produto?</p><p>Para responder essa pergunta, provavelmente, deve ter feito uma pesquisa pra tentar identificar a faixa de preço que o produto se encontra. Outra coisa comum, é a consulta de especialistas, que normalmente são contratados para avaliarem as condições do produto e dar um valor para ele.</p><p>No caso de imóveis não é diferente, seja tentando vender ou comprar um imóvel, você acabará pesquisando sobre o mercado e seus valores. É bem possível que contrate um agente imobiliário para ajudar na pesquisa. Isso não é uma tarefa fácil, pode acabar dando trabalho e consumindo muito tempo.</p><p>Assim, uma ferramenta que facilite a obtenção do valor de um imóvel com determinadas características de forma automática e instantânea, pode auxiliar na decisão sobre compra e venda de imóveis.</p><p>Dessa forma, uma possível aplicação para Aprendizado de Máquina no mercado imobiliário é a predição dos preços dos imóveis, e o objetivo deste artigo é a criação de um modelo para realizar essa função.</p><p>Vamos dar início ao processo.</p><h3>O conjunto de dados e pré-processamento</h3><p>Para obter um melhor resultado, a gente pode realizar algumas ações que vão auxiliar o algoritmo em identificar os pontos mais importantes dentro do conjunto de dados. Essas ações consistem em modificar o conjunto de dados, ou seja, pré-processar os dados, de forma que possa melhorar a qualidade do conjunto antes de mandar para o modelo.</p><p>Para este exemplo, iremos utilizar um conjunto de dados de uma competição no Kaggle que pode ser acessado <a href="https://www.kaggle.com/c/house-prices-advanced-regression-techniques/data">aqui</a>.</p><p>Esse conjunto de dados contém diversas informações sobre a casa, como, a quantidade de quartos, se possui ou não garagem, ano de construção do imóvel, etc. Além disso, contém também o preço de venda das casas, esse que será nosso alvo na criação do modelo.</p><p>Por se tratar de uma competição, podemos utilizá-la para verificar a precisão que iremos atingir com o nosso resultado.</p><p>Depois de pegar os dados, podemos visualizar como que está o conjunto, se está balanceado ou completo por exemplo. Para fazer isso será utilizada a biblioteca <a href="https://github.com/pandas-profiling/pandas-profiling"><strong><em>pandas-profiling</em></strong></a>. Essa biblioteca fornece funções que permitem obter uma visão geral dos dados, criando um html com todas as variáveis disponíveis no conjunto de dados.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eB0Jg0djGh32EvXmLuqSMw.png" /><figcaption>Print do resultado da fornecido por pandas-profiling</figcaption></figure><p>Você pode verificar o resultado <a href="http://house-profiling.surge.sh/">aqui</a>, hospedado com a ferramenta <a href="https://surge.sh/">Surge</a>.</p><p>Com o resultado do pandas-profiling podemos verificar que algumas variáveis possuem valores faltantes e que outras não estão bem equilibradas.</p><p>O primeiro passo do pré-processamento que iremos aplicar, é o preenchimento de variáveis com valores faltantes. Algumas variáveis que estão com valores faltantes serão preenchidas com a opção <em>None</em>, ou <em>0</em>, as demais que não aceitam esses valores serão preenchidas com os valores mais comuns de cada variável.</p><h4>Feature Engineering</h4><p>Uma etapa importante do pré-processamento é chamada de Feature Engineering, que consiste em analisar as features (as colunas, também chamadas de variáveis), realizando modificações nas features, criando novas features ou removendo features que podem atrapalhar a identificação de padrões.</p><p>Depois que preenchemos os valores faltantes podemos aplicar feature engineering ao conjunto de dados. Vamos iniciar com a criação de novas features:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/591c9b45b767f6d54ebb9c536511791b/href">https://medium.com/media/591c9b45b767f6d54ebb9c536511791b/href</a></iframe><ul><li><strong>HasAlleyAccess</strong> é uma nova variável para representar se a casa possui acesso por um beco, essa variável é criada da variável <em>Alley</em> que representa o tipo do beco, e possui uma distribuição bem desbalanceada;</li><li><strong>TotalPorchSF</strong> é uma variável criada para representar o tamanho da varanda da casa, independente do tipo;</li><li><strong>HasMasVnr</strong> é uma nova variável criada para substituir a variável <em>MasVnrArea</em>, que possui muitas entradas com 0 e as demais com valores diversos;</li><li><strong>Has2ndFlr</strong> é uma nova variável criada para substituir a variável <em>2ndFlrSF</em> pois essa também possui uma grande quantidade de entradas com valor 0;</li><li><strong>TotalHouseSF</strong> é uma variável criada para representar o tamanho total da casa.</li></ul><p>Depois de criar algumas variáveis, vamos agora modificar variáveis numéricas e categóricas. Ainda com o resultado do pandas-profiling, podemos verificar a distribuição das variáveis numéricas. Assim, podemos aplicar uma técnica de dividir os valores numéricos em intervalos e marcar esses intervalos com categorias.</p><p>As variáveis numéricas que iremos modificar são <em>LotFrontage</em>, <em>LotArea</em>, <em>TotalBsmtSF</em> e <em>1stFlrSF</em>. Para fazer isso utilizamos a função <em>cut(),</em> disponível no módulo <em>pandas</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6f003021eab042a1b9207d6982c421e/href">https://medium.com/media/d6f003021eab042a1b9207d6982c421e/href</a></iframe><p>Neste exemplo, <em>bins </em>são os intervalos que a variável será dividida e <em>labels </em>são os nomes das categorias que serão adicionados<em>.</em></p><p>Em seguida, nós alteramos as variáveis categóricas, incluindo as que foram criadas, para que fiquem todas como variáveis numéricas.</p><p>Em algumas variáveis podemos simplesmente mapear as categorias em números, pois possuem uma certa ordenação entre os valores. Já as variáveis que não possuem o comportamento ordinal serão transformadas utilizando a técnica One-Hot encoding, que, basicamente, cria uma nova variável para cada uma das categorias de uma variável. E para facilidade desse processo será utilizado a função <em>get_dummies()</em>, disponível no módulo <em>pandas.</em></p><p>Podemos remover algumas variáveis também, variáveis que possuem um alto nível de correlação entre si, que estão muito desbalanceadas ou que não serão mais utilizadas. Assim, as variáveis que serão removidas são: <em>Utilities</em>, <em>GarageYrBlt</em>, <em>2ndFlrSF</em>, <em>MasVnrArea</em>, <em>PoolQC</em>, <em>Alley</em>, <em>OpenPorchSF</em>, <em>EnclosedPorch</em>, <em>3SsnPorch</em>, <em>ScreenPorch</em>, <em>Street</em>, <em>MiscFeature</em>, <em>PoolArea</em>, <em>RoofMatl</em>, <em>LowQualFinSF</em>, <em>Heating</em>, <em>MiscVal</em>, <em>WoodDeckSF</em>.</p><p>Caso tenha mais interesse em Feature Engineering, ou ficou com duvidas, veja <a href="https://towardsdatascience.com/tagged/tds-feature-engineering">essa série de artigos</a> que podem ajudar a entender melhor esse processo.</p><h3>O modelo</h3><p>Após finalizar o pré-processamento do conjunto de dados, podemos dar início ao treinamento do modelo. Nós temos varias opções de modelos para utilizar, o escolhido para este exemplo foi o <a href="https://xgboost.readthedocs.io/en/latest/">XGBoost</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ccc8a11f7a6bb4c5e44b2bea566ffbf1/href">https://medium.com/media/ccc8a11f7a6bb4c5e44b2bea566ffbf1/href</a></iframe><p>Como parâmetro usamos o RMSLE (Root Mean Squared Logarithmic Error) para avaliar a evolução do treino do nosso modelo em 150 rodadas. A métrica rmsle é útil quando não queremos penalizar uma diferença muito grande, no nosso caso temos que prever valores altos, preços de casas, assim, podemos nos deparar com diferenças de ordem elevada. Além do rsmle temos outras métricas possíveis, se você quiser ler mais sobre métricas <a href="https://towardsdatascience.com/how-to-select-the-right-evaluation-metric-for-machine-learning-models-part-2-regression-metrics-d4a1a9ba3d74#b5e6">veja esse artigo</a>.</p><p>Durante o treino do modelo, podemos acompanhar a evolução em cada uma das rodadas, uma parte pode ser conferida a seguir:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/221/1*giH2_sUF7CUB3hnG8zmCkw.png" /><figcaption>Resultado do treinamento do modelo</figcaption></figure><p>Ao finalizar o treino, podemos utilizar o modelo para prever os preços do conjunto de testes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/125/1*8U4i9Lc1bfHfuuzB9DsEWA.png" /><figcaption>Exemplo do resultado da predição de preços</figcaption></figure><p>Assim, podemos utilizar esse modelo para estimar o valor de uma casa que possui as mesmas variáveis do conjunto de dados original.</p><p>Por fim, iremos utilizar a competição do Kaggle para conferir a precisão do nosso modelo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*3gs0Ssmw5M9cujgr-zKskw.png" /><figcaption>Resultado da competição do Kaggle</figcaption></figure><h3>Conclusão</h3><p>Uma aplicação possível para Aprendizado de Máquina no mercado imobiliário, como foi apresentada neste artigo, é a previsão do valor de casas. A solução para predição de preços de casas pode ser utilizada para desenvolvimento de uma ferramenta, que pode requisitar as características do imóvel e retornar o valor aproximado.</p><p>Assim, uma pessoa que tem a intenção de vender ou comprar um imóvel, pode ter mais facilidade ao realizar a pesquisa de preço através da ferramenta, podendo ter o preço aproximado da casa.</p><p>Você pode conferir o código completo no Github.</p><p><a href="https://github.com/Educ71/house-price">Educ71/house-price</a></p><h3>Referências</h3><blockquote>Pandas Profiling: <a href="https://github.com/pandas-profiling/pandas-profiling">https://github.com/pandas-profiling/pandas-profiling</a></blockquote><blockquote>Competition discussion: <a href="https://www.kaggle.com/c/house-prices-advanced-regression-techniques/discussion">https://www.kaggle.com/c/house-prices-advanced-regression-techniques/discussion</a></blockquote><blockquote>Understanding Feature Engineering: <a href="https://towardsdatascience.com/tagged/tds-feature-engineering">https://towardsdatascience.com/tagged/tds-feature-engineering</a></blockquote><blockquote>Surge: <a href="https://surge.sh/">https://surge.sh/</a></blockquote><blockquote>XGBoost: <a href="https://xgboost.readthedocs.io/en/latest/">https://xgboost.readthedocs.io/en/latest/</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee04da21d1b3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/neuronio-br/como-o-aprendizado-de-m%C3%A1quina-pode-ser-aplicado-no-mercado-imobili%C3%A1rio-ee04da21d1b3">Como o Aprendizado de Máquina pode ser aplicado no mercado imobiliário</a> was originally published in <a href="https://medium.com/neuronio-br">Neuronio BR</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Machine Learning can be applied to the real state market]]></title>
            <link>https://medium.com/neuronio/how-machine-learning-can-be-applied-to-the-real-state-market-d047ce22abd5?source=rss-efe8cdb02770------2</link>
            <guid isPermaLink="false">https://medium.com/p/d047ce22abd5</guid>
            <category><![CDATA[prediction-model]]></category>
            <category><![CDATA[house-prices]]></category>
            <category><![CDATA[xgboost]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Luis Eduardo]]></dc:creator>
            <pubDate>Tue, 06 Aug 2019 16:32:58 GMT</pubDate>
            <atom:updated>2019-08-06T16:32:58.170Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>Note</strong>: a Portuguese version of this article is available at “<a href="https://medium.com/neuronio-br/como-criar-um-modelo-de-ml-para-prever-pre%C3%A7os-de-casas-ee04da21d1b3">Como o Aprendizado de Máquina pode ser aplicado ao mercado imobiliário</a>”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gxVQ-IENaBwQz_Zs" /><figcaption>Photo by <a href="https://unsplash.com/@brenoassis?utm_source=medium&amp;utm_medium=referral">Breno Assis</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you have bought or sold anything, you already have the question: What’s the price of this product?</p><p>To answer this question, you probably need to search trying to get a price interval for this product. Maybe you have hired a specialist to see the product and give you some insight about the price.</p><p>With properties is not different, you will need to study the real state market. Maybe you will need help from a real state agent in your study. This is not an easy task, maybe you will spend some time doing a lot of research.</p><p>So, a tool to get insights about houses prices more quickly can help you make a decision whether to buy or sell a house.</p><p>Thus, a possible Machine Learning application is a model to predict the houses prices, and the goal of this article is to create a model to do this job.</p><p>Let’s start the process.</p><h3>The dataset and preprocessing</h3><p>To get better results from our model, we can apply some actions to try to improve the data quality to help the model identify the good features from the data. These actions are what we call data preprocessing.</p><p>In this example we will use the data from a Kaggle competition, available <a href="https://www.kaggle.com/c/house-prices-advanced-regression-techniques/data">here</a>.</p><p>This is a simple dataset with several informations about houses, like the number of bedrooms, number of garages, built year, etc. Moreover, we have the target feature, the price variable which we need to predict.</p><p>So, we will use the competition to evaluate our model when we finish.</p><p>Now, after we got the data we need to see how that are. For that we will use the <a href="https://github.com/pandas-profiling/pandas-profiling"><strong><em>pandas-profiling</em></strong></a> module. This module has tools to prepare an Exploratory Data Analysis (EDA) with all features from our data and we can save an html file too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eB0Jg0djGh32EvXmLuqSMw.png" /><figcaption>Print from result of the pandas-profiling</figcaption></figure><p>You can check result of pandas-profiling <a href="http://house-profiling.surge.sh/">here</a>, hosted by <a href="https://surge.sh/">Surge</a> tool.</p><p>With the result of pandas-profiling we can see this dataset has some missing values and some features are very unbalanced.</p><p>The first step of preprocessing we will do is fill the missing values. Some features we fill with None, or 0, option, others features that don’t accept these options, we will fill with the most common value.</p><h4>Feature Engineering</h4><p>An important step in data preprocessing is called Feature Engineering. This is a process to do changes in feature set, like create new features, modify existing features or drop another features.</p><p>After we filled the missing values, we can apply some feature engineering. First we create some features:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/591c9b45b767f6d54ebb9c536511791b/href">https://medium.com/media/591c9b45b767f6d54ebb9c536511791b/href</a></iframe><ul><li><strong>HasAlleyAccess</strong> is a new feature created from the <em>Alley</em> feature, because Alley is the type of alley and the most frequent is ‘None Alley Access’, so we just create a new feature to represent if a house has or not an alley access;</li><li><strong>TotalPorchSF</strong> is the sum of the others porch square feet features(<em>OpenPorchSF</em>, <em>EnclosedPorch</em>, <em>3SsnPorch</em>, <em>ScreenPorch</em>, <em>WoodDeckSF</em>), because the others features are very unbalanced;</li><li><strong>HasMasVnr</strong> is feature created from <em>MasVnrArea</em>, this featured was created because the data from this featured are unbalanced to and has a lot of 0 values;</li><li><strong>Has2ndFlr</strong> is created from <em>2ndFlrSF</em> and mean if the house has second floor or not;</li><li><strong>TotalHouseSF</strong> is the sum of the total square feet of the house.</li></ul><p>Now we will change some numeric and categorical features. With the pandas-profiling we can see the numerical features distributions and apply some processing. In some features we transform the numerical data in categorical, separating them in categoric intervals.</p><p>The numerical data we will transform are: <em>LotFrontage</em>, <em>LotArea</em>, <em>TotalBsmtSF</em> and <em>1stFlrSF</em>. For that we will use the <em>cut()</em> function from <em>pandas</em> module.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6f003021eab042a1b9207d6982c421e/href">https://medium.com/media/d6f003021eab042a1b9207d6982c421e/href</a></iframe><p>In above example, <em>bins</em> are the numerical intervals and <em>labels</em> are categorical intervals.</p><p>Then we transform the categorical data in numerical to use in the model. Some features we can just map to integer values, because they have ordinal behaviour.</p><p>The features that don’t have ordinal behaviour, we will apply One-Hot encoding, the technique that basically creates a new feature for each unique value from a categorical feature. To apply that we can use the <em>get_dummies()</em> function from pandas module.</p><p>We can remove some unbalanced and correlated features. Also there are features we don’t need anymore. We will remove some features like: <em>Utilities</em>, <em>GarageYrBlt</em>, <em>2ndFlrSF</em>, <em>MasVnrArea</em>, <em>PoolQC</em>, <em>Alley</em>, <em>OpenPorchSF</em>, <em>EnclosedPorch</em>, <em>3SsnPorch</em>, <em>ScreenPorch</em>, <em>Street</em>, <em>MiscFeature</em>, <em>PoolArea</em>, <em>RoofMatl</em>, <em>LowQualFinSF</em>, <em>Heating</em>, <em>MiscVal</em>, <em>WoodDeckSF</em>.</p><p>If you are interested in Feature Engineering, or you have doubts, see that <a href="https://towardsdatascience.com/tagged/tds-feature-engineering">series of article</a>, maybe this will help you understand better this process.</p><h3>The Model</h3><p>Now we can use the data to train our model. We will use the train data and the test data. We have a lot of options to use, but in this example we will use the <a href="https://xgboost.readthedocs.io/en/latest/">XGBoost</a> to make our predictions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ccc8a11f7a6bb4c5e44b2bea566ffbf1/href">https://medium.com/media/ccc8a11f7a6bb4c5e44b2bea566ffbf1/href</a></iframe><p>As baseline we used the Root Mean Squared Logarithmic Error (RMSLE) to see the evolution of the train during 150 rounds. The rmsle metric is good if we don’t want to penalize huge differences, in our case we need to predict huge values, so the differences of our prediction can be large. As rmsle we have another metrics, if you want to read about metrics you can see <a href="https://towardsdatascience.com/how-to-select-the-right-evaluation-metric-for-machine-learning-models-part-2-regression-metrics-d4a1a9ba3d74#b5e6">that article</a>. The results are:</p><p>During the model train, we can see the evolution of our model in each round. You can see a piece of train below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/221/1*giH2_sUF7CUB3hnG8zmCkw.png" /><figcaption>Model train result</figcaption></figure><p>After the train finished, we can use the model to predict the test data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/125/1*8U4i9Lc1bfHfuuzB9DsEWA.png" /><figcaption>Result from model prediction</figcaption></figure><p>So, we can use the model to predict a house price if we have the same features used the training.</p><p>Now, we can use the Kaggle competition to see the accuracy of our model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*3gs0Ssmw5M9cujgr-zKskw.png" /><figcaption>Result on Kaggle competition</figcaption></figure><h3>Conclusion</h3><p>An application to Machine Learning in the real state market, as described in this article, is the house prices prediction. The ML model can be used to develop a tool to give the price of a house given the house features. So, anyone with the intention to buy or sell a house, can use this tool to save time in a house prices search.</p><p>You can check all the code on Github.</p><p><a href="https://github.com/Educ71/house-price">Educ71/house-price</a></p><h3>References</h3><blockquote>Pandas Profiling: <a href="https://github.com/pandas-profiling/pandas-profiling">https://github.com/pandas-profiling/pandas-profiling</a></blockquote><blockquote>Competition discussion: <a href="https://www.kaggle.com/c/house-prices-advanced-regression-techniques/discussion">https://www.kaggle.com/c/house-prices-advanced-regression-techniques/discussion</a></blockquote><blockquote>Understanding Feature Engineering: <a href="https://towardsdatascience.com/tagged/tds-feature-engineering">https://towardsdatascience.com/tagged/tds-feature-engineering</a></blockquote><blockquote>Surge: <a href="https://surge.sh/">https://surge.sh/</a></blockquote><blockquote>XGBoost: <a href="https://xgboost.readthedocs.io/en/latest/">https://xgboost.readthedocs.io/en/latest/</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d047ce22abd5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/neuronio/how-machine-learning-can-be-applied-to-the-real-state-market-d047ce22abd5">How Machine Learning can be applied to the real state market</a> was originally published in <a href="https://medium.com/neuronio">Neuronio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Como criar um modelo para predição de churn]]></title>
            <link>https://medium.com/neuronio-br/como-criar-um-modelo-para-predi%C3%A7%C3%A3o-de-churn-aa11b9feb8a6?source=rss-efe8cdb02770------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa11b9feb8a6</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[churn-prediction]]></category>
            <category><![CDATA[data-preprocessing]]></category>
            <category><![CDATA[feature-engineering]]></category>
            <dc:creator><![CDATA[Luis Eduardo]]></dc:creator>
            <pubDate>Wed, 19 Jun 2019 11:36:11 GMT</pubDate>
            <atom:updated>2019-06-19T11:36:11.056Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Nota: uma versão em inglês deste artigo pode ser encontrado em “<a href="https://medium.com/neuronio/how-to-create-a-churn-prediction-model-9019cb6520b8">How to create a churn prediction model</a>”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dsScSKVyPKV2ZbxcrWxKWA.jpeg" /><figcaption><a href="https://wildreply-ed83.kxcdn.com/wp-content/uploads/2018/12/Featured_Phlox_LeakyBucket.jpg">Fonte da imagem</a></figcaption></figure><p>Perder seus clientes não é bom, e caso pudesse prever quando um cliente irá parar de utilizar o serviço seria uma grande oportunidade para se tomar decisões que irão manter os clientes. Esse é o nosso objetivo nesse artigo, criar e comparar modelos de Machine Learning para prever quando um cliente irá parar de usar um serviço, ou seja, quando ocorrerá churn.</p><p>Em um modelo de Machine Learning, o dado é a coisa mais importante. Um bom modelo não consegue fazer milagre com dados ruins. Por isso é necessário realizar um preparo dos dados para que possam ser utilizados no modelo.</p><p>O conjunto de dados que sera utilizado neste artigo é o Telco Churn Customer disponível no <a href="https://www.kaggle.com/blastchar/telco-customer-churn">Kaggle</a>. E todo o código desse exemplo foi feito em python e está disponível <a href="https://github.com/Educ71/churn-prediction">aqui</a>.</p><p>Vamos iniciar.</p><h3>O conjunto de dados</h3><p>Será utilizada a biblioteca <em>pandas </em>para podermos trabalhar com o conjunto de dados. Primeiramente, vamos ler o arquivo do conjunto de dados.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1244440165eca8f8fdca3f1c2b6cf45/href">https://medium.com/media/c1244440165eca8f8fdca3f1c2b6cf45/href</a></iframe><p>Podemos visualizar algumas informações sobre o conjunto de dados com a função <strong><em>pandas.DataFrame.info().</em></strong> Essa função mostra um resumo sobre o DataFrame, ele apresenta quais as colunas/features, o tipo de cada coluna e a quantidade de valores não nulos das colunas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*tAeZkgloYV-RxHRUiA3KJQ.png" /><figcaption>Informações do conjunto de dados</figcaption></figure><p>Nesse caso nós não precisamos lidar com valores faltantes, e temos poucas features numéricas. Também temos a coluna com os rótulos que queremos prever, a coluna <strong>Churn</strong>, mas, se não estivesse contida no conjunto de dados, precisaríamos gera-las com base na definição do objetivo. Caso o objetivo não esteja definido é necessário defini-lo antes de gerar os valores do rótulo.</p><p>O conjunto de dados é referente a uma empresa de Telecomunicação. Nele há informações dos clientes, como se possui parceiro(a), se possui dependentes, etc, e sobre seus contratos, como serviço de telefone, quantidade paga por mês, etc. Algumas features apresentam relação com o tempo de contratação do serviço, como <em>tenure, TotalCharges e MonthlyCharges, </em>que significam, respectivamente, tempo, em meses, que o cliente possui o serviço e total pago pelo cliente.</p><p>Agora, vamos ver a distribuição do rótulo utilizando a biblioteca seaborn.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J2OLAKxbhR4jKtz2gRhQpA.png" /><figcaption>Distribuição de Churn</figcaption></figure><p>Podemos notar que está desbalanceado. Temos aproximadamente 27% para Churn e 73% para não Churn nesse conjunto de dados. Isso pode ser um problema para se obter o melhor resultado de um modelo.</p><p>Nos podemos utilizar a função <em>head()</em> do pandas para conseguir visualizar as 5 primeiras linhas da tabela pra ter uma noção de como estão os dados.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*DQjoLKV2zNxyto8lXwnLdA.png" /></figure><h3>Pré-processamento de Dados</h3><p>Em alguns problemas de Machine Learning nos temos que realizar algum pré-processamento de dados. Isso é um passo importante para preparar os dados para o modelo de ML para que possamos obter resultados melhores e também conhecimento sobre o dados.</p><p>Vamos aplicar pré-processamento nos dados agora.</p><p>Olhando os dados podemos ver que algumas das colunas/features possuem três valores únicos que são redundantes. Por exemplo, na feature <em>MultipleLines</em> temos o valor <em>“No phone service”</em>, porém já temos a feature <em>PhoneService</em> com essa informação, então, iremos substituir esse valor por apenas “No”, ficando assim com apenas dois valores únicos. Podemos fazer isso também para outras features como <em>OnlineBackup, OnlineSecurity, DeviceProtection, TechSupport, StreamingMovies, StreamingTV.</em></p><p>Nós temos algumas features numéricas, e podemos usar funções como <em>countplot()</em> do seaborn e <em>hist()</em> do pandas para ter uma visão geral da distribuição e da relação das features com o rotulo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J7saa2yAmMP9XCupVlbvHw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rKSr_SZreZ335_oIabSbHA.png" /><figcaption>Contagem de tenure na esquerda e tenure x Churn na direita</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AcQvxBG1-f_3WX6oTt7Leg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l5QMWJRea76SP651qQGGXg.png" /><figcaption>Distribuição de MonthlyCharges na esquerda e MonthlyCharges x Churn na direita</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_jZYnHMyPGvd24MNSgrNuQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s18DzjKJy7y0fNbnIjloUQ.png" /><figcaption>Distribuição de TotalCharges na esquerda e TotalCharges x Churn na direita</figcaption></figure><p>É possível identificar diferentes padrões nas distribuições dessas features. Podemos ver que essas features possuem valores numéricos contínuos e possuem distribuições desbalanceadas, para mudar isso podemos aplicar algumas opções, por exemplo, converter em categorias, como dividir em intervalos predefinidos ou quantis, podemos fazer isso para evitar que as distribuições fiquem muito desbalanceadas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P5I_5y63kRnFDmM3K9aJtw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oesErY9FCpXYG3YKWJppKQ.png" /><figcaption>Contagem de Tenure_cat na esquerda e tenure_cat x Churn na direita</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FQB_X0dl0o7ADYitMvEXpw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hFtct0jmbmritaQ7i8sTLA.png" /><figcaption>Contagem de MonthlyCharges_cat na esquerda e MonthlyCharges_cat x Churn na direita</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*irK-dQNtzQ978BvdFkpAiQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uk5aytLw-Ccvil4-Z9CdRA.png" /><figcaption>Contagem de TotalCharges_cat na esquerda e TotalCharges_cat x Churn na direita</figcaption></figure><p>Agora nós temos todas as features categóricas e podemos usar dessa forma. Contudo, alguns dos algoritmos que serão utilizados aceitam apenas números e por isso precisamos modificar as categorias para valores numéricos. Para fazer isso temos algumas opções como o One-Hot Encoding e o Integer/Label Encoding.</p><p>Integer Encoding é um simples marcador que mapeia as categorias em valores numéricos inteiros com uma relação de ordenação natural. Já o One-Hot Encoding possui uma abordagem diferente, recomendado para features que não seguem uma ordenação natural, nesse método as categorias são mapeadas em colunas e preenchidas com valores binários.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/12d282893c3cfbbfdfc5e55796af4662/href">https://medium.com/media/12d282893c3cfbbfdfc5e55796af4662/href</a></iframe><p>Para aplicar essa mudanças podemos usar o LabelEncoding do sklearn para fazer Integer Encoding e o get_dummies() do pandas para o One-Hot Encoding.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cca17849ae799b907c4216b0164d9049/href">https://medium.com/media/cca17849ae799b907c4216b0164d9049/href</a></iframe><p>Agora podemos ver a relação entre cada feature nos dados numéricos utilizando a função <em>heatmap()</em> do seaborn.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*K7TbvfrMn_IITRfHloEDow.png" /><figcaption>Heatmap da correlação entre as features</figcaption></figure><h3>Os modelos</h3><p>Agora que temos os dados preparados para os modelos, temos que dividir em dados para treinamento e validação do modelo. Para isso vamos utilizar a função <em>train_test_split()</em> do sklearn.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c28a00b856af08941693cc484365e815/href">https://medium.com/media/c28a00b856af08941693cc484365e815/href</a></iframe><p>Agora vamos criar e treinar os modelos com os algoritmos Logistic Regression, Random Forest e Gradient Boosting, vamos utilizar o sklearn para isso.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09d382fb0b3ca2cf5677e2056f2fdb02/href">https://medium.com/media/09d382fb0b3ca2cf5677e2056f2fdb02/href</a></iframe><p>Agora já temos os modelos treinado e podemos valida-los com o método <em>predict() </em>de cada modelo.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/92436add2e607f9778faae85ff0cab23/href">https://medium.com/media/92436add2e607f9778faae85ff0cab23/href</a></iframe><p>Em seguida podemos ver os resultados obtidos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*OFeHwJCzJbJjl7YTi0xZMQ.png" /></figure><p>No nosso caso a Accuracy não é uma métrica muito boa para avaliar nossos modelos, pois ela mede a exatidão geral do modelo, e, como o conjunto de dados está desbalanceado, acarreta em um aumento que não reflete no nosso resultado positivo. Portanto, é bom escolhermos outras métricas que estão disponíveis, como Precision e Recall.</p><p>Precision é a porcentagem de predições corretas para o rótulo dentre o total que foi previsto com esse rótulo, ou seja, quão bem o modelo prevê o rótulo. E o Recall é a porcentagem de predições corretas para o rótulo dentre o total de entradas que realmente possuem esse rótulo, ou seja, quão bem o modelo prevê o rótulo dado que este é o rótulo correto.</p><p>Podemos notar que os modelos de Logistic Regression e Gradient Boost obtiveram resultados parecidos nesse caso, porém, caso o conjunto de dados seja muito grande o Gradient Boost se mostra melhor em performance.</p><h3>Conclusão</h3><p>Para um problema de predição, é necessário gastar um tempo na etapa de Pré-processamento de Dados. Ao analisar o conjunto de dados é possível realizar algumas suposições que possam melhorar o desempenho do modelo. Dependendo do tamanho do conjunto de dados isso pode demorar bastante tempo, porém, é uma etapa muito importante para a qualidade do modelo.</p><p>A escolha do modelo pode acabar não tendo tanto impacto nos resultados como o pré-processamento dos dados. Além disso, casos onde o conjunto de dados está desbalanceado é interessante escolher outras métricas além da Accuracy.</p><p><a href="https://github.com/Educ71/churn-prediction">Educ71/churn-prediction</a></p><h3>Referências</h3><blockquote><a href="https://towardsdatascience.com/tagged/tds-feature-engineering">Tds Feature Engineering</a></blockquote><blockquote><a href="https://towardsdatascience.com/prediction-engineering-how-to-set-up-your-machine-learning-problem-b3b8f622683b">Prediction Engineering: How to Set Up Your Machine Learning Problem</a></blockquote><blockquote><a href="https://machinelearningmastery.com/data-leakage-machine-learning/">Data Leakage in Machine Learning</a></blockquote><blockquote><a href="https://hackernoon.com/choosing-the-right-machine-learning-algorithm-68126944ce1f">Choosing the Right Machine Learning Algorithm</a></blockquote><blockquote><a href="https://machinelearningmastery.com/roc-curves-and-precision-recall-curves-for-classification-in-python/">How and When to Use ROC Curves and Precision-Recall Curves for Classification in Python</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa11b9feb8a6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/neuronio-br/como-criar-um-modelo-para-predi%C3%A7%C3%A3o-de-churn-aa11b9feb8a6">Como criar um modelo para predição de churn</a> was originally published in <a href="https://medium.com/neuronio-br">Neuronio BR</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create a churn prediction model]]></title>
            <link>https://medium.com/neuronio/how-to-create-a-churn-prediction-model-9019cb6520b8?source=rss-efe8cdb02770------2</link>
            <guid isPermaLink="false">https://medium.com/p/9019cb6520b8</guid>
            <category><![CDATA[feature-engineering]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[churn-prediction]]></category>
            <category><![CDATA[data-preprocessing]]></category>
            <dc:creator><![CDATA[Luis Eduardo]]></dc:creator>
            <pubDate>Wed, 19 Jun 2019 11:36:07 GMT</pubDate>
            <atom:updated>2019-06-19T11:36:07.781Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>Note: </strong><em>a Portuguese version of this article is available at “</em><a href="https://medium.com/neuronio-br/como-criar-um-modelo-para-predi%C3%A7%C3%A3o-de-churn-aa11b9feb8a6">Como criar um modelo para predição de churn</a><em>”</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dsScSKVyPKV2ZbxcrWxKWA.jpeg" /><figcaption><a href="https://wildreply-ed83.kxcdn.com/wp-content/uploads/2018/12/Featured_Phlox_LeakyBucket.jpg">Image source</a></figcaption></figure><p>Losing customers is not good, and if you can predict when a customer will stop using the service, you will have an opportunity to make decisions to retain the customer. Our goal in this article is create and compare Churn Prediction Machine Learning models.</p><p>The data is the most important thing in a Machine Learning model. A good model can’t do miracle with poor data, and to solve it is important to prepare the data to the model to get better results.</p><p>This article use the Telco Churn Customer Dataset, available on <a href="https://www.kaggle.com/blastchar/telco-customer-churn">Kaggle</a>. And all the code for this example is in python and is available <a href="https://github.com/Educ71/churn-prediction">here</a>.</p><p>Let’s start.</p><h3><strong>The Dataset</strong></h3><p>To work with the dataset we will use the pandas library. First, let’s read the dataset.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1244440165eca8f8fdca3f1c2b6cf45/href">https://medium.com/media/c1244440165eca8f8fdca3f1c2b6cf45/href</a></iframe><p>We can see some informations about the dataset with the function <strong><em>pandas.DataFrame.info().</em></strong> This function gives us the overall information about the DataFrame like all the columns, the type os columns and the number of non-null values of the columns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*tAeZkgloYV-RxHRUiA3KJQ.png" /><figcaption>The dataset info</figcaption></figure><p>We don’t need to handle missing values and we just have a few numerical features. In this dataset we already have the label we want to predict, the <strong><em>Churn</em></strong> column, but if it’s not included we need to create it based on its definition. If the definition is not available is necessary to define it before labelling.</p><p>The dataset refers to a Telecommunication company. There is information about customers, like <em>Partner, Dependents, etc</em>, and about their contracts, like <em>PhoneService, MonthlyCharges, etc. </em>Some features show how long the customer have been using the service, such as <em>tenure and TotalCharges</em>, respectively, mean/represents time in months that the customer has the service and total amount paid by the customer.</p><p>Now, let’s see the churn distribution with <em>seaborn</em> library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J2OLAKxbhR4jKtz2gRhQpA.png" /></figure><p>The label is unbalanced. We have 27% of Churn and 73% of non-Churn in this dataset. This can be a problem to get the best results from the model.</p><p>We can use the <em>head()</em> function to see the first 5 rows from the table to see its data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*DQjoLKV2zNxyto8lXwnLdA.png" /></figure><h3>Data Preprocessing</h3><p>In some Machine Learning problems we have to do some Data Pre-processing. This is an important step to prepare the data, so the ML model will produce better results. Also you can gather knowledge about the data.</p><p>Let’s apply pre-processing now.</p><p>Looking to the data we can see some features have three unique values redundant values. For example, in feature <em>MultipleLines </em>we have<em> </em>the <em>“No phone service”, </em>however we already have the feature <em>PhoneService </em>with that information, so we can just change it to <em>“No” </em>and stay with two unique values<em>. </em>We can apply this to <em>OnlineBackup, OnlineSecurity, DeviceProtection, TechSupport, StreamingMovies </em>and<em> StreamingTV </em>features.</p><p>We have some numerical features, we can use functions like<em> countplot()</em> from seaborn and <em>hist()</em> from pandas to have an overview about these data distribution and the relation with the label.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J7saa2yAmMP9XCupVlbvHw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rKSr_SZreZ335_oIabSbHA.png" /><figcaption>Tenure count in left and tenure x Churn in right</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AcQvxBG1-f_3WX6oTt7Leg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l5QMWJRea76SP651qQGGXg.png" /><figcaption>MonthlyCharges distribution in left and MonthlyCharges x Churn in right</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_jZYnHMyPGvd24MNSgrNuQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s18DzjKJy7y0fNbnIjloUQ.png" /><figcaption>TotalCharges distribution in left and TotalCharges x Churn in right</figcaption></figure><p>Is possible to see different patterns from the tree features. These features are continuous numerical values and have a little skewed distribution, and to change it we can apply some processes. One option is to convert in categorical values like split the values in intervals predefined or quantiles, we can do that to avoid the skewed distribution from the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P5I_5y63kRnFDmM3K9aJtw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oesErY9FCpXYG3YKWJppKQ.png" /><figcaption>Tenure_cat count in left and tenure_cat x Churn in right</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FQB_X0dl0o7ADYitMvEXpw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hFtct0jmbmritaQ7i8sTLA.png" /><figcaption>MonthlyCharges_cat count in left and MonthlyCharges_cat x Churn in right</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*irK-dQNtzQ978BvdFkpAiQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uk5aytLw-Ccvil4-Z9CdRA.png" /><figcaption>TotalCharges_cat count in left and TotalCharges_cat x Churn in right</figcaption></figure><p>Now we have all the features categorical and we can use this features in that format, but some algorithms accepts just numbers and to try them we need to change to numerical values. To do that we have some options like One-Hot Encoding and Label/Integer Encoding.</p><p>Integer Encoding is a simple category labelling that map the categories to numbers with a natural ordered relationship. The One-Hot Encoding have a different approach for the features that don’t have a natural ordinal relationship. In this method the categories are separated in columns and are filled with binary values.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/12d282893c3cfbbfdfc5e55796af4662/href">https://medium.com/media/12d282893c3cfbbfdfc5e55796af4662/href</a></iframe><p>To apply the changes we can use LabelEncoding from sklearn, to create the Integer Encoding, and we can use <em>get_dummies()</em> from pandas to get the One-Hot Encoding.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cca17849ae799b907c4216b0164d9049/href">https://medium.com/media/cca17849ae799b907c4216b0164d9049/href</a></iframe><p>Now we can see the relationship between the features in our cleaned data with the <em>heatmap()</em> function from seaborn library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*K7TbvfrMn_IITRfHloEDow.png" /><figcaption>Feature correlation heatmap</figcaption></figure><h3>The Models</h3><p>Now we have our data prepared to the model, we just need to split the data to train and validate the model. To do that we have <em>train_test_split()</em> from sklearn.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c28a00b856af08941693cc484365e815/href">https://medium.com/media/c28a00b856af08941693cc484365e815/href</a></iframe><p>Let’s create three models with Logistic Regression, Random Forest and Gradient Boosting algorithms, we will user sklearn library to get the models.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09d382fb0b3ca2cf5677e2056f2fdb02/href">https://medium.com/media/09d382fb0b3ca2cf5677e2056f2fdb02/href</a></iframe><p>Now we have the model trained and we can just validate with the <em>predict()</em> method from models.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/92436add2e607f9778faae85ff0cab23/href">https://medium.com/media/92436add2e607f9778faae85ff0cab23/href</a></iframe><p>And we can see the results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*OFeHwJCzJbJjl7YTi0xZMQ.png" /></figure><p>In our case the Accuracy is not a good metric to evaluate the models, because it measures the overall accuracy of the model, and as the dataset is unbalanced, it causes an increase that does not reflect our positive outcome. So it’s good to choose other metrics that are available, such as Precision and Recall</p><p>Precision is the percentage of correct predictions for the label from the total that was predicted with that label, that is, how well the model predicts the label. And Recall is the percentage of correct predictions for the label from the total entries that actually have that label, that is, how well the model predicts the label when that is the correct label.</p><p>We can see for this example we have very similar results for Logistic Regression and the Gradient Boost algorithms, but if we have big datasets the Gradient Boost has advantages in performance.</p><h3>Conclusion</h3><p>For a prediction problem, we need to spend some time in Data Pre-processing step. When analysing the dataset it’s possible to make some assumptions that can improve the performance of the model.Depending on the size of the dataset this can take a long time, however, it’s a very important step for the quality of the model.</p><p>The choice of the model may end up not having as much impact on the results as the pre-processing of the data. In addition, cases where the dataset is unbalanced is interesting to choose other metrics other than Accuracy.</p><p><a href="https://github.com/Educ71/churn-prediction">Educ71/churn-prediction</a></p><h3>References</h3><blockquote><a href="https://towardsdatascience.com/tagged/tds-feature-engineering">Tds Feature Engineering</a></blockquote><blockquote><a href="https://towardsdatascience.com/prediction-engineering-how-to-set-up-your-machine-learning-problem-b3b8f622683b">Prediction Engineering: How to Set Up Your Machine Learning Problem</a></blockquote><blockquote><a href="https://machinelearningmastery.com/data-leakage-machine-learning/">Data Leakage in Machine Learning</a></blockquote><blockquote><a href="https://hackernoon.com/choosing-the-right-machine-learning-algorithm-68126944ce1f">Choosing the Right Machine Learning Algorithm</a></blockquote><blockquote><a href="https://machinelearningmastery.com/roc-curves-and-precision-recall-curves-for-classification-in-python/">How and When to Use ROC Curves and Precision-Recall Curves for Classification in Python</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9019cb6520b8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/neuronio/how-to-create-a-churn-prediction-model-9019cb6520b8">How to create a churn prediction model</a> was originally published in <a href="https://medium.com/neuronio">Neuronio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>