<?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 André Barbosa on Medium]]></title>
        <description><![CDATA[Stories by André Barbosa on Medium]]></description>
        <link>https://medium.com/@abarbosa94?source=rss-235e625cbc72------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*VvulT0ocwpRZ3fKZ.jpg</url>
            <title>Stories by André Barbosa on Medium</title>
            <link>https://medium.com/@abarbosa94?source=rss-235e625cbc72------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 10:49:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abarbosa94/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[Árvores de Decisão]]></title>
            <link>https://abarbosa94.medium.com/%C3%A1rvores-de-decis%C3%A3o-42a879c30122?source=rss-235e625cbc72------2</link>
            <guid isPermaLink="false">https://medium.com/p/42a879c30122</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[decision-tree]]></category>
            <category><![CDATA[supervised-learning]]></category>
            <dc:creator><![CDATA[André Barbosa]]></dc:creator>
            <pubDate>Mon, 08 Feb 2021 18:24:58 GMT</pubDate>
            <atom:updated>2021-02-08T18:49:57.126Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Material construído para a Tera</em></p><p>Olá! Parabéns por terem chego até aqui! No bloco de estudos de hoje, vamos aprender sobre o que são <em>árvores de decisão</em>! :)</p><h3>Entendendo problemas lineares e não-lineares</h3><p>Quando aprendemos, no começo do curso, sobre regressão linear vimos que esse modelo funciona muito bem quando temos uma certa linearidade dos nossos dados.</p><p>Por exemplo, suponha que você trabalha em um restaurante e quer estimar quanto de <em>gorjeta</em> os seus garçons vão receber com base na conta final do restaurante. <strong>Logo, quanto maior a conta do restaurante, maior a gorjeta</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*3FZ13Q8wVab4DZ1hpTDSAQ.png" /><figcaption>Uma relação entre o preço da conta e a gorjeta</figcaption></figure><p>É claro que tem uma relação linear entre as variáveis. Podemos confirmar isso ao computar a correlação linear entre as variáveis :)</p><pre>from scipy.stats import pearsonr</pre><pre>corr, _ = pearsonr(data1, data2)<br>print(&quot;Correlação de Pearson: %.3f&quot; % corr)</pre><pre>Correlação de Pearson: 0.887</pre><p>Relembrando um pouco, correlação é um valor que varia entre −1 até 1, em que 1 é uma correlação positiva perfeita e -1 é uma correlação negativa perfeita. Geralmente, um valor acima de 0.50 está associado com uma alta correlação positiva.</p><p>Vamos treinar um modelo de regressão para esse caso :)</p><pre>from sklearn.model_selection import train_test_split<br>from sklearn.linear_model import LinearRegression<br>from sklearn.metrics import r2_score</pre><pre>X_train, X_test, y_train, y_test = train_test_split(<br>    data1.reshape(-1, 1), data2.reshape(-1, 1), test_size=0.1<br>)</pre><pre>model = LinearRegression()<br>model.fit(X_train, y_train)<br>r2_score(y_test, model.predict(X_test))</pre><pre>0.7238562525812482</pre><p>Conseguimos um modelo de regressão com o r² muito bom :)</p><p>Podemos até fazer um plot da reta em relação aos dados :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*n-uBvIKJn2IJwC4izCVe8A.png" /><figcaption>Plot da reta aprendida pelo modelo</figcaption></figure><p>Contudo, vamos supor que <strong>aconteceu uma doidera no restaurante por um tempo</strong> e a relação das variáveis mudaram um pouco, seguindo o gráfico abaixo!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*p4Vbm5Ju7gnh2ZadjZpozg.png" /><figcaption>Uma <strong>nova </strong>relação entre o preço da conta e a gorjeta</figcaption></figure><p>Ou seja, a relação claramente deixou de ser claramente linear. Vamos computar a correlação de Pearson.</p><pre>corr, _ = pearsonr(data1, data2)<br>print(&quot;Correlação de Pearson: %.3f&quot; % corr)</pre><pre>Correlação de Pearson: 0.738</pre><p>A correlação ainda é forte, mas é claramente menor do que a que calculamos inicialmente. Vamos ver o comportamento da regressão nesse caso?</p><pre>X_train, X_test, y_train, y_test = train_test_split(<br>    data1.reshape(-1, 1), data2.reshape(-1, 1), test_size=0.1<br>)</pre><pre>model = LinearRegression()<br>model.fit(X_train, y_train)<br>r2_score(y_test, model.predict(X_test))</pre><pre>0.44411006406707687</pre><p>Ou, seja, <strong>claramente</strong> a regressão não foi muito boa. Vamos plotar a reta para esse caso:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*Hy_bFt24f_OJANSLxTeCGA.png" /><figcaption>Regressão linear aplicada para o novo conjunto de dados</figcaption></figure><p>Como a <strong>regressão linear</strong> resulta em uma <strong>reta</strong>, será que conseguimos fazer melhor?</p><h3>Introduzindo árvores de decisão</h3><p><strong>Árvores de Decisão</strong> são modelos não lineares e que, portanto, conseguem encontrar padrões que possuem esse tipo de relação entre as variáveis. Mas como ela funciona?</p><p>A ideia é relativamente simples. Uma árvore de decisão é construida ao <strong>repartir</strong> os dados seguindo regras de decisão. Cada dado, uma vez repartido, resulta em um subgrupo, definido como nó. Por exemplo:</p><pre>- Se o valor da conta for maior que 20 reais e menor do que 60, então o valor a gorjeta deve ser 1.</pre><h4>O algoritmo das árvores de decisão</h4><p>Podemos definir um algoritmo de árvore de decisão seguindo o seguinte o código, inspirado no <a href="https://mlcourse.ai/articles/topic3-dt-knn/#2.-Decision-Tree">link</a>:</p><pre>def monta_arvore(L):<br>    cria um nó t<br>    se o critério de parada é True:<br>        defina um modelo preditivo para t<br>    else:<br>        encontre o melhor split binário L = L_left + L_right<br>        t.left = monta_arvore(L_left)<br>        t.right = monta_arvore(L_right)<br>    return t</pre><p>Mas como que essas regras são definidas?</p><h4>Regression Trees</h4><p>No caso de árvores de decisão aplicadas a problemas de regressão, o modelo busca <strong>partir os dados</strong> seguindo um critério de quebra. No caso, queremos agrupar os nossos dados de forma que esses dados resultem em um <strong>grupo que minimizem o erro quadrático médio</strong>. Relembrando a métrica, MSE, é definida por:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/158/0*pz8CTg_RGX2TwuYC" /><figcaption>Métrica MSE</figcaption></figure><ul><li>Ou seja, queremos <strong>minimizar a média dos erros elavado ao quadrado</strong></li></ul><p>Vamos ao código para ilustrar isso.</p><pre>from sklearn.tree import DecisionTreeRegressor</pre><pre>model = DecisionTreeRegressor(criterion=&quot;mse&quot;, max_depth=4, min_samples_leaf = 20)<br>model.fit(X_train, y_train)<br>r2_score(y_test, model.predict(X_test))</pre><pre>0.5566920750334438</pre><p>Fazendo o plot da “reta”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*ciVgOfO1cfw6vAqmZCEoXA.png" /><figcaption>Plot da curva pela árvore de decisão</figcaption></figure><p>Ou seja, <strong>claramente</strong> o valor aprendido <strong>não segue uma reta</strong>, mas sim regras mais “secas” de corte dos nossos dados.</p><pre>import cv2<br>from pydotplus.graphviz import graph_from_dot_data<br>from sklearn.tree import export_graphviz</pre><pre>dot_data = export_graphviz(<br>    model, filled=True, rounded=True,<br>    out_file=None<br>)<br>graph = graph_from_dot_data(dot_data) <br>graph.write_png(&#39;tree.png&#39;)</pre><pre>img = cv2.imread(&#39;tree.png&#39;)<br>plt.figure(figsize = (20, 20))<br>_ = plt.imshow(img)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OzxhZFy2xbEVFywc24jJWg.png" /><figcaption>Plot da árvore no caso de regressão</figcaption></figure><p>Nós podemos interpretar o valor acima da seguinte forma:</p><ul><li>Se o valor do preço da conta for <strong>menor</strong> que 21.98, <strong>maior</strong> que 15.96, <strong>então</strong> o preço da gorjeta, baseado na média de 39 amostras, deve ser 0.88</li><li>Se o valor do preço da conta for <strong>maior</strong> que 21.98, <strong>maior</strong> que 60.0 e <strong>menor que</strong> 79.6, <strong>menor do que</strong> 65.18, <strong>então</strong> o preço da gorjeta, baseado na média de 21 amostras, deve ser 1.646</li></ul><h4>Desafios de árvores de decisão</h4><p>Claramente, poderíamos construir uma árvore de decisão em que os <strong>nós</strong> possuissem <strong>apenas</strong> uma <strong>única amostra</strong>. Contudo, isso <strong>claramente</strong> resultaria em árvore <em>overfitada</em> e <em>esse</em> é o maior problema das árvores de decisão: <strong>elas overfittam</strong> muito fácil e por conta disso eu coloquei alguns <strong>hiperparâmetros</strong> quando instanciei as classe <em>DecisionTreeRegressor</em>. Além do critério da árvore, os principais hiperparâmetros das árvores de Decisão são:</p><ul><li>max_depth- a profundidade máxima da árvore (no nosso exemplo, usamos 3)</li><li>max_features — o número <strong>máximo</strong> de features que o modelo olha para escolher a melhor regra de decisão</li><li>min_samples_leaf — o número mínimo de amostras que queremos ter na árvore. No caso, usamos 20</li></ul><h3>Classification Trees</h3><p><em>Inspirado fortemente no </em><a href="https://mlcourse.ai/articles/topic3-dt-knn/#2.-Decision-Tree"><em>link</em></a></p><p>Como Árvores de Decisão funcionam no caso de problemas de classificação?</p><p>A primeira coisa a se pensar, contudo é que, como <strong>estamos lidando com um problema de classificação</strong>, <strong>não</strong> podemos ter <em>MSE</em> como critério de divisão. Para definirmos o critério ideal, vamos pegar o seguinte problema de classificação:</p><p>Suponha que você queira prever a cor de uma bola baseada na sua posição</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*VNyCTofALz5fGW9qS-mPOg.png" /><figcaption><a href="https://mlcourse.ai/articles/topic3-dt-knn/#2.-Decision-Tree">fonte</a></figcaption></figure><p>Nesse exemplo, temos 9 bolas azuis e 11 bolas amarelas. Se aleatoriamente pegarmos uma bola, ela será azul com a probabilidade 9/20 e amarela com probabilidade 11/20. Com isso, conseguimos ver que a chance de pegar uma bola de cada cor <em>é mais ou menos</em> a mesma. A partir dessa ideia, precisamos definir um conceito <strong>novo</strong>, chamado <strong>entropia</strong>.</p><h3>Entropia de Shannon</h3><p>A entropia de Shannon é um conceito da <strong>teoria da informação</strong> que define o grau de <strong>caos</strong> de um sistema. Quanto maior a entropia, menos ordenado é um ambiente. Ela é uma métrica que é definida da seguinte forma:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/142/0*NRHMJDqahVslgU1A" /><figcaption>Entropia de Shannon</figcaption></figure><p>O resultado da entropia é medido em <em>bits</em> e pode ser um valor entre 0 e 1, em que 0 seria um sistema bem ordenado, com <em>alto grau de certeza</em> e 1, um <em>alto grau de incerteza</em>. O <strong>log</strong> aqui é na base do <strong>número de classes que estamos usando</strong>. Como no nosso caso, estamos lidando com 2 classes, o log é na base 2.</p><p>Graficamente, ela pode ser ilustrada pelo gráfico abaixo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*8OzcCxHDPVdKsfh_Ag_ugA.png" /><figcaption><a href="https://towardsdatascience.com/entropy-how-decision-trees-make-decisions-2946b9c18c8">fonte</a></figcaption></figure><p>Ou seja, segundo o exemplo, quando a probabilidade de pertencer a classe positva é 1 (apenas exemplos positivos), ou 0 (apenas exemplos negativos), a entropia resultante é 0, porquê <strong>existe uma alta certeza da organização do ambiente</strong>.</p><p>Disso, conseguimos derivar outra métrica, que é o ganho de informação:</p><p>𝐼𝐺(𝑌,𝑋)=𝐸(𝑋)−𝐸(𝑌|𝑋)</p><p>O ganho de informação de Y para X é dado pela Entropia de X menos a Entropia de Y dado X. <strong>Na prática, quanto maior redução de incertezas, maior o ganho de informação possível</strong>. Ou seja, existe uma relação <strong>inversa</strong> entre a entropia e o ganho de informação.</p><p>No caso, a entropia do sistema que estamos lidando é dado por:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/0*ujMI9wUQ3j-ZS_nV" /><figcaption>Entropia de Shannon para o exemplo</figcaption></figure><p>Esse valor não quer dizer muita coisa nesse primeiro momento, mas vamos entender como que esse valor se altera se quebrarmos por diferentes regras de decisão. Por exemplo, se a posição é menor que 12 ou maior que 12</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*E6Jm-p1KZl7I2sH5-yDGgQ.png" /><figcaption><a href="https://mlcourse.ai/articles/topic3-dt-knn/#2.-Decision-Tree">fonte</a></figcaption></figure><p>Logo, o nosso Y é basicamente dado pelo sistema pela regra de decisão Y ≤ 12. E X é o sistema todo, sem nenhuma regra de quebra até então (E(X)=H_0).</p><p>O grupo da esquerda tem 13 bolas, sendo 8 azuis e 5 amarelas, tendo como entropia H_1 e o grupo da direita tem 7 bolas, sendo 6 amarelas e 1 azul, tendo a entropia H_2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/0*GltCNde4vK91P2R8" /><figcaption>Entropia de cada um dos grupos</figcaption></figure><p>Então, podemos calcular o ganho de informação dessa parte do nosso dataset da seguinte forma:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/0*6B0W3duH7CgKqHtm" /></figure><p>Ou seja, o uso da regra de decisão 𝑋≤12 resulta em um sistema mais ordenado que o anterior, uma vez que existem algum ganho de informação.</p><p>Repetimos, então, o processo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*vZJDVR3ocribu1SfnN-4jg.png" /><figcaption>Montagem inteira da árvore de decisão</figcaption></figure><p>Para o grupo da direita, a gente precisa apenas fazer uma partição a mais, uma vez que temos apenas uma bola na cor azul (basta perguntar se a posição da bola é menor ou igual que 18). Contudo, para o grupo da esquerda, precisamos repetir o processo três vezes. <strong>Além disso, também é valido dizer que a entropia de um grupo onde todas as bolas são da mesma cor é 0</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/0*p9KCZAvs1YiFJOaU" /><figcaption>Exemplo quando da entropia quando a probabilidade é 1</figcaption></figure><h3>Só podemos usar a entropia?</h3><p>Não! Assim como na árvore para regressão, existem outros critérios de definição além da entropia, como o <strong>Indice de Gini</strong> . A idéia é que a relação entre as métricas seja parecida e isso pode ser visto com facilidade pelo gráfico abaixo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*iLwnl476zmPu4eIWgL2Kjg.png" /><figcaption>Comparação entre métricas</figcaption></figure><p>Em que o Gini e o missclassification são computadas, respectivamente por:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/89/0*aWjnIFjMjlWH3CXw" /><figcaption>Como computar, respectivamente o gini e a entropia</figcaption></figure><p>Na prática, as diferentes métricas (tendem a convertir para o mesmo resultado). A única diferença mais “prática” é que o indice de Gini é computacionalmente mais eficiente do que a entropia por não ter o cálculo do log. Além disso, se multiplicarmos o índice de Gini por 2, temos uma curva praticamente identica à entropia.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*km8HIZfNiM_N7ew495-2GQ.png" /><figcaption>Comparação entre o Gini e o Entropy</figcaption></figure><h4>Aplicando um Exemplo</h4><p>Suponha que queremos criar um modelo que separe corretamente as classes abaixo</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*LsQ-uSvdLvcJ60yJ3uO41w.png" /><figcaption>Exemplo de classificação simples</figcaption></figure><pre>from sklearn.tree import DecisionTreeClassifier</pre><pre>clf_tree = DecisionTreeClassifier(criterion=&#39;entropy&#39;, max_depth=3)</pre><pre># training the tree<br>clf_tree.fit(train_data, train_labels)</pre><p>Podemos imprimir a <strong>fronteira de decisão</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*GLlKIzpfR6E6wTitp-Wu0g.png" /><figcaption>Fronteira de decisão</figcaption></figure><pre>dot_data = export_graphviz(<br>    clf_tree, filled=True, rounded=True,<br>    out_file=None<br>)<br>graph = graph_from_dot_data(dot_data) <br>graph.write_png(&#39;tree_classifier.png&#39;)</pre><pre>img = cv2.imread(&#39;tree_classifier.png&#39;)<br>plt.figure(figsize = (20, 20))<br>_ = plt.imshow(img)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*74dp4x7UmJjGaVn8jZEjiQ.png" /><figcaption>Plot da árvore quando no caso de um problema de classificação</figcaption></figure><h3>Um gostinho do que vem por aí</h3><p>O interessante das Árvores de Decisão é que eles são a base para muitos algoritmos populares, como <strong>Random Forests</strong> e <strong>Gradient Boosting</strong>, que, por sua vez, são bastante utilizados na prática.</p><p>O interessante desses algoritmos é que eles são capazes de capturar não linearidades de uma maneira melhor. Pegando o exemplo da gorjeta, que tal compararmos uma árvore de decisão comum (o exemplo no começo do post) e uma random forest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*ciVgOfO1cfw6vAqmZCEoXA.png" /><figcaption>Plot da previsão com uma Árvore de Decisão</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*hsfpAGbyvh7pc1yvDJt8Jg.png" /><figcaption>Plot da previsão com uma Random Forest</figcaption></figure><h3>Conclusão</h3><p>Parabéns! Vocês acabaram de aprender um pouco mais sobre um dos modelos mais clássicos de machine learning, as <strong>Decision Trees</strong> :)</p><h3>Referências</h3><ul><li><a href="https://towardsdatascience.com/https-medium-com-lorrli-classification-and-regression-analysis-with-decision-trees-c43cdbc58054">https://towardsdatascience.com/https-medium-com-lorrli-classification-and-regression-analysis-with-decision-trees-c43cdbc58054</a></li><li><a href="https://mlcourse.ai/articles/topic3-dt-knn/#2.-Decision-Tree">https://mlcourse.ai/articles/topic3-dt-knn/#2.-Decision-Tree</a></li><li><a href="https://towardsdatascience.com/entropy-how-decision-trees-make-decisions-2946b9c18c8">https://towardsdatascience.com/entropy-how-decision-trees-make-decisions-2946b9c18c8</a></li><li><a href="https://scikit-learn.org/stable/modules/tree.html">https://scikit-learn.org/stable/modules/tree.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42a879c30122" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine Learning Pipeline at QuintoAndar]]></title>
            <link>https://medium.com/quintoandar-tech-blog/machine-learning-pipeline-at-quintoandar-e2f24136006b?source=rss-235e625cbc72------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2f24136006b</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[quintoandar]]></category>
            <dc:creator><![CDATA[André Barbosa]]></dc:creator>
            <pubDate>Mon, 26 Aug 2019 20:10:31 GMT</pubDate>
            <atom:updated>2019-08-28T19:48:49.750Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Two strawmen talk, 1 stands on top of Linear Algebra. &quot;You pour data on one side and answers come out&quot; Stir if they&#39;re wrong." src="https://cdn-images-1.medium.com/max/371/1*UKIHA2AHtB9WPG-KrfwSZg.png" /><figcaption><a href="https://xkcd.com/1838/">xkcd is the best place to describe daily activities</a></figcaption></figure><p>Data Science (or DS) is an important hot topic where a considerable number of “best practices” are still being defined. There is no standard about how an ideal process of machine learning development should be stated. We’re sharing in this post how my team and I defined and set up a robust pipeline for Machine Learning to scale up things here at QuintoAndar! 🚀</p><h3>What is a Data Product?</h3><p>At our company, the concern of a Data Product is a product empowered by machine learning 😄</p><p>Let’s give a simple example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*ug4leNmmPyL7UNjH" /><figcaption>The data is kinda fake, so this is why this wide range of values 😅</figcaption></figure><p>Our rent calculator is a simple example of an interesting data product that we have been developing so far, and I am going to use it as a use case example in this blog post 😃</p><p>The idea is simple: our company wants to make rental easy and cool so how could we help owners in a way that it is easier for them to rent their houses? How could we help tenants find an awesome place to live at a fair price?</p><p>How about developing something (a product) that recommends how much a real estate should be rent for? This is the idea behind our rent calculator! 🎉</p><h3>Machine Learning is NOT the first option</h3><blockquote>If you think that machine learning will give you a 100% boost, then a heuristic will get you 50% of the way there.</blockquote><p>Following Rule #1 of <a href="https://developers.google.com/machine-learning/guides/rules-of-ml/">50 rules of Machine Learning from Google</a>, there is no need to rush for the state of the art models when you are dealing with real-world problems. Better than that, a simple heuristic can give you a lot of insights and help you to validate your main hypothesis. For example, you can take the average rent of houses in a similar region as your house of interest.</p><p>Once this is done, your team delivered some value to your company by making your clients happy. Awesome!</p><p>Someday you may want to improve your metrics and for that, you will need to go deeper. As a “second iteration cycle” maybe Machine Learning can be a useful approach 😄</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/0*QKskvYonx4rs4S_T" /><figcaption>We need to iterate quickly through our models</figcaption></figure><p>As an agile culture that we follow here, <strong>we need to respond to business changes and act quickly. </strong>In the context of machine learning, quick iterations are the key to success.</p><p>The best way to achieve this is by learning from data, with baby steps. In other words, create a model that uses simple features that you can generate (by feature engineering or by querying a database), deploy it, measure and improve it.</p><p>Collect the low-hanging fruits, one step at a time until your team’s model achieves better performance, creating a better experience for your users.</p><p>Improving a deployed model is not an easy task. It is done by software engineers and data scientists that team up to achieve new results. These cycles must be prioritized and always will grow in complexity, from putting a simple regression model into production to build a complex ensemble or novel deep learning architecture.</p><p>It is also necessary to take into consideration how data should be ingested and served, how should it be presented to the user (e.g., a single value <em>vs.</em> an interval). The market can also change during this process; business needs can be modified, or even the <strong>data sources can alter their statistical behavior in a short period</strong>.</p><p>As stated, <strong>we need to be prepared to respond to those changes</strong>. Therefore, how can we keep track of all of these challenges, experiments, hypotheses, and models and ensure that we are moving forward in a <strong>fast</strong> and <strong>reproducible</strong> way (you know, “it works on my machine” is not acceptable anymore).</p><h3>Introducing our Machine Learning Pipeline</h3><p>Inspired by <a href="https://image.slidesharecdn.com/4krishnaputtaswamyandrewhoh-180614031004/95/bighead-airbnbs-endtoend-machine-learning-platform-with-krishna-puttaswamy-and-andrew-hoh-12-638.jpg?cb=1528945909">Airbnb’s BigHead</a>, <a href="https://eng.uber.com/michelangelo/">Uber’s Michelangelo</a> and <a href="https://engineering.fb.com/ml-applications/introducing-fblearner-flow-facebook-s-ai-backbone/">Facebook’s FBLearner Flow</a> our team started to think how could we address generic problems that usually shows up when we try to build machine learning products. The diagram shows what we have come up with:</p><figure><img alt="QuintoAndar&#39;s ML pipeline. Describe main sections: Feature Store, Model Management &amp; Model deployment and monitoring" src="https://cdn-images-1.medium.com/max/1024/1*weEWF7rHmi5xFLCzneCTjQ.jpeg" /></figure><p>At the top of the image above (blue rectangle) is what we defined as our <strong>data pipeline</strong>. Data should not come as it is in the production database. Data must be cleaned, aggregated, transformed into something meaningful to a machine learning model.</p><p>Sometimes, creating a feature is as easy as:</p><pre>SELECT area <br>FROM   house <br>WHERE  id = &#39;someid&#39;</pre><p>or as complicated as:</p><pre>WITH base <br>     AS (SELECT neigh.type, <br>                <em>Avg</em>(c.rent / <em>Cast</em>(neigh.area AS <em>DOUBLE</em>)) AS region_avg_m2_rent <br>         FROM   contract AS c <br>                JOIN house AS neigh <br>                  ON neigh.id = c.id_house <br>                JOIN house AS h <br>                  ON h.id_region = neigh.id_region <br>         WHERE  h.id = &#39;someid&#39; <br>         GROUP  BY neigh.type) <br>SELECT <strong>some_10_line_pivot_function</strong>(*) <br>FROM   base</pre><p>Multiple machine learning models can share the same feature. So, other data scientists/engineers may need to do the same transformation to use in their solutions. Another common issue that can arise is that different people can work in similar ideas using slightly different data, leading to redundant features used by different models that make maintenance intractable sometimes. Therefore, we needed a way to “centralize” stuff and make some definitions a little bit canonical.</p><h3>The Feature Store</h3><p>Exposing features for machine learning models, data scientists and analysts and to a whole diversity of services is the role QuintoAndar’s Feature Store plays, which can be described as a place in which anyone can have access to features made before to have the results easier. If some feature is the result of some aggregation, this operation needs to be done only once. People generate these features through Feature Factory and send it to our Feature Store.</p><p><a href="https://eng.uber.com/michelangelo/">The concept of a Feature Store was first described in 2017 by Uber</a>. It is a centralized and shared data layer that contains precomputed model-ready features to be used during training or serving.</p><h3>Model management</h3><p>The red rectangle is described as <strong>model management</strong>, which was designed to improve governance and quality of models being deployed and used in production. We spent some time developing a model ML template, which takes care of <a href="https://fullstackworld.com/post/what-is-boilerplate-code-why-when-to-use-the-boilerplate-code">boilerplate code</a> and helps the data scientists to get straight into model development. We were strongly inspired by the <a href="https://github.com/drivendata/cookiecutter-data-science"><em>cookiecutter data science</em></a><em> project</em>, but we’ve made some modifications to it to make it fit our business needs.</p><p>Since the last quarter, we have been developing an <strong>internal library</strong> that aims to adopts a lot of common DS code (pandas; scikit-learn; deep learning libs) and generates a machine learning pipeline, from feature engineering to model deploy and serving. <strong>This guarantees reproducibility and we can also bring experiments to production in a less painful way.</strong></p><p>Once the model is ready, we run it into <strong>Model Training Service</strong>, a framework also developed by us that automates the full machine learning pipeline and it automates an airflow DAG and goes through the following:</p><ul><li>It retrieves production-level data</li><li>Performs automatic hyperparameter tuning through Bayesian Optimization (provided by Amazon Sagemaker)</li><li>Trains an optimized model</li><li>Performs model validation (by performing overfitting checking and other stuff)</li><li>Deploy it into production by making our serving API to point to the newly released model.</li></ul><h3>Model Deploy</h3><p>The last part of our architecture is defined as model <strong>deployment &amp; monitoring</strong>. As most of our services, we deploy our models to give near-real-time predictions in a Kubernetes cluster. Models should produce logs of their predictions, which are retrieved by our Kibana server. We also plan to dump those logs to our data lake, which will enable metric performance monitoring with Metabase.</p><p>By setting up all of this, as a data scientist, I can say that we can focus on what the coolest part of my job is: machine learning models 😎</p><p>So the hard “setup” work pays off!</p><figure><img alt="QuintoAndar’s ML pipeline. Describe main sections: Feature Store, Model Management &amp; Model deployment and monitoring" src="https://cdn-images-1.medium.com/max/1024/1*LGXunSsVsIlYBF182F2eAg.jpeg" /><figcaption>This is where I need to focus from now on</figcaption></figure><p>Our work is not done yet, and we are constantly improving our process. One thing that we are planning to release in a near future is an experiment journal tool (like <a href="https://github.com/IDSIA/sacred">sacred</a>) so we can keep track easily about <strong>every hypothesis</strong> being tested by different teams in a single source.</p><p>The Machine Learning Pipeline at QuintoAndar was an effort put by several Data Engineers, Data Scientist and Software Engineers 🎉</p><p>If you liked this kind of way that we deal with Machine Learning problems, <a href="https://carreiras.quintoandar.com.br/">join us!</a></p><p><a href="https://carreiras.quintoandar.com.br/">QuintoAndar Carreiras</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2f24136006b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/quintoandar-tech-blog/machine-learning-pipeline-at-quintoandar-e2f24136006b">Machine Learning Pipeline at QuintoAndar</a> was originally published in <a href="https://medium.com/quintoandar-tech-blog">Blog Técnico QuintoAndar</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>