<?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 Gabriel Ghellere on Medium]]></title>
        <description><![CDATA[Stories by Gabriel Ghellere on Medium]]></description>
        <link>https://medium.com/@gabrielghellere?source=rss-3a236877c979------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*sor8OZRFdkZ6lK21.</url>
            <title>Stories by Gabriel Ghellere on Medium</title>
            <link>https://medium.com/@gabrielghellere?source=rss-3a236877c979------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 14:00:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gabrielghellere/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[Aprendendo regressão linear em python utilizando dados de desmatamento do Brasil.]]></title>
            <link>https://medium.com/@gabrielghellere/aprendendo-regress%C3%A3o-linear-em-python-utilizando-dados-de-desmatamento-do-brasil-1906bb216a95?source=rss-3a236877c979------2</link>
            <guid isPermaLink="false">https://medium.com/p/1906bb216a95</guid>
            <dc:creator><![CDATA[Gabriel Ghellere]]></dc:creator>
            <pubDate>Thu, 21 Nov 2019 19:51:52 GMT</pubDate>
            <atom:updated>2019-11-21T20:31:51.887Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/460/0*W54swd8amInl913E" /><figcaption>Área devastada em Rondônia, o quarto estado que mais devastou a floresta em 12 meses Foto: DW / Deutsche Welle</figcaption></figure><p>O Brasil vem sofrendo duras críticas ambientais devido ao crescimento da devastação na Amazônia, entre agosto 2018 de julho de 2019 a floresta perdeu uma área de 9.762 km², segundo dados do INPE. Entre agosto de 2018 e julho de 2019, o desmatamento da Floresta Amazônica cresceu 29,5% em comparação com os 12 meses anteriores [1].</p><p>O aumento percentual de 29,5% também foi o terceiro maior da história, ficando atrás apenas das altas de 1995 (95%) e 1998 (31%). O ministro de Meio Ambiente, Ricardo Salles, tentou relativizar os dados com a seguinte hipótese:</p><blockquote><strong>“O número está seguindo uma tendência de aumento desde 2012”</strong></blockquote><p>que foi dita por Salles, após o diretor interino do INPE, Darcton Policarpo Damião, anunciar os dados em uma coletiva de imprensa [1] [2] [3].</p><p>O objetivo desse blogpost não é discutir política e sim praticar estatística realizando um teste simples em python para tentar validar a hipótese do Ministro Salles e verificando se realmente o desmatamento segue a tendência de 2012.</p><h3>Dados</h3><p>O primeiro passo para realizar o teste é a obtenção dos dados, o sistema terrabrasilis é uma plataforma do INPE que dá acesso a dados geoespaciais brasileiros públicos para análise. O sistema terrabrasilis utiliza monitoramentos de programas como PRODES e DETER [4].</p><p>Nesse link pode-se visualizar os dados de desmatamento e também fazer o download que é o que realmente interessa:</p><p><a href="http://terrabrasilis.dpi.inpe.br/app/dashboard/deforestation/dashboard/deforestation/biomes/legal_amazon/rates">TerraBrasilis</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Mi14KMGFvU5GL-Q-" /><figcaption>Página de download terrabrasilis</figcaption></figure><p>Após realizar o download carrega-se os dados no python, para tal análise utiliza-se as bibliotecas pandas, seaborn, scipy e matplotlib. Realiza-se um pré processamento simples nos dados substituindo &#39;.&#39; por &#39;,&#39; para ter uma notação padrão e também são definidos os tipos de dados:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/0*TjAjn_p3H66FTNiI" /><figcaption>Carregamento das bibliotecas, dados e pre processamento</figcaption></figure><p>Plota-se os dados para verificar se estão coerentes com o gráfico do terrabrasilis:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/0*ZnBWFb8bDaZwgoDw" /><figcaption>Serie temporal de desmatamento</figcaption></figure><h3>Selecionar uma técnica para realizar o teste:</h3><p>Para testar essa hipótese é válido utilizar o método de regressão linear com objetivo de identificar a tendência, para tal utiliza-se a equação da reta:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/126/0*QDbyAdV0hB7h7H1h" /><figcaption>Equação da reta</figcaption></figure><p>Onde m representa o <strong>coeficiente angular da reta</strong> e b o <strong>coeficiente linear</strong>, esses dados representam a tendência [5].</p><p>Para testar a hipótese segue o seguinte passo a passo:</p><ol><li>Isole o espaço amostral da hipótese (após 2012)</li><li>Calcule uma reta interpolando os dados eliminando o último ano (2019) com os coeficientes calcule o valor de desmatamento previsto para 2019 seguindo a tendência.</li><li>Calcule uma reta interpolando os dados com o ano de 2019.</li><li>Compare os resultados da interpolação dos passos 2 e 3, também compare o erro com o valor previsto em 2 com o valor real de desmatamento.</li></ol><h3>Análise</h3><p>Seguindo o passo a passo descrito acima:</p><p>Isolando os dados a partir de 2012:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/0*__NnQIAQI2UlXGke" /><figcaption>Dados de desmatamento a partir de 2012</figcaption></figure><p>Remove-se o ano de 2019 e calcula-se a tendência de 2012 até 2018, os parâmetros m e b são respectivamente ‘slope’ e ‘intercept’:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*jw4BuU3v73VS1CujfZRqpQ.png" /></figure><p>Com o valor de m e b calcula-se o valor de desmatamento para 2019 na tendência que inicia em 2012 e termina em 2018 utilizando a equação da reta:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*tDwwRhEHZVOCEcPaYTYZeA.png" /><figcaption>Resultados sem 2019</figcaption></figure><p>Pode-se observar que como calculado caso o desmatamento seguisse a mesma tendência desde 2012 o valor de desmatamento para 2019 seria próximo a 8280 kmˆ2.</p><p>Realiza-se o mesmo para a serie de valores incluindo 2019 verifica-se os coeficientes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*38NBXITtL2Fkm5FhHaRbgA.png" /><figcaption>Resultados com 2019</figcaption></figure><p>Observa-se que como a inclinação não é a mesma isso dá uma pista que a hipótese não é válida, caso fosse válida o valor de inclinação deveria ser o mesmo ou pelo menos próximo nos dois casos.</p><p>Para quantificar o erro da maneira mais simples possível verifica-se a diferença entre os valores (com e sem 2019) chegando em:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/0*YKAjq02QozqE9xTX" /><figcaption>Resultados</figcaption></figure><p>Pode-se observar que o valor esperado de desmatamento caso seguisse a tendência criada a partir de 2012 seria próximo a 8277 kmˆ2, porém o valor real é superior em aproximadamente 1484 kmˆ2, o que invalida a hipótese do ministro Salles.</p><p>Gostaria de lembrar que esse artigo tem como objetivo aprendizado e segue uma metodologia muito simples portanto esse dado não deve ser levado em consideração se comparado a uma pesquisa séria.</p><p>Obrigado a todos pela leitura!!!!!!</p><p>Fontes:</p><p>[1] <a href="https://www.terra.com.br/noticias/brasil/desmatamento-na-amazonia-atinge-maior-nivel-desde-2008,226eda410317b99f3fb5eb5704427bedpzhod2q5.html">https://www.terra.com.br/noticias/brasil/desmatamento-na-amazonia-atinge-maior-nivel-desde-2008,226eda410317b99f3fb5eb5704427bedpzhod2q5.html</a></p><p>[2] <a href="https://www.dw.com/pt-br/bolsonaro-diz-que-desmatamento-na-amaz%C3%B4nia-%C3%A9-quest%C3%A3o-cultural/a-51334649">https://www.dw.com/pt-br/bolsonaro-diz-que-desmatamento-na-amaz%C3%B4nia-%C3%A9-quest%C3%A3o-cultural/a-51334649</a></p><p>[3] <a href="https://amazoniareal.com.br/a-realidade-devastadora/">https://amazoniareal.com.br/a-realidade-devastadora/</a></p><p>[4] <a href="http://terrabrasilis.dpi.inpe.br/en/about/">http://terrabrasilis.dpi.inpe.br/en/about/</a></p><p>[5]<a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.linregress.html">https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.linregress.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1906bb216a95" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Recommender systems with collaborative filters]]></title>
            <link>https://medium.com/playkids-tech-blog/recommender-systems-with-collaborative-filters-531e8315ba58?source=rss-3a236877c979------2</link>
            <guid isPermaLink="false">https://medium.com/p/531e8315ba58</guid>
            <category><![CDATA[collaborative-filtering]]></category>
            <category><![CDATA[recommender-systems]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[content-based]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Gabriel Ghellere]]></dc:creator>
            <pubDate>Tue, 10 Sep 2019 18:20:22 GMT</pubDate>
            <atom:updated>2019-09-10T18:20:22.415Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*fCVClrqoc7oLP5H0jvpGTA.jpeg" /><figcaption>Image from Pixabay</figcaption></figure><h3><strong>Intro</strong></h3><p>A recommender system (or recommendation system) is a very important tool for a data scientist, because such systems are widely used by small and large companies for a variety of purposes. Their main mission is to predict the “rating” or “preference” of a user given an item. Amazon, for example, uses recommendation systems to recommend books for their customers based on previous purchases. <a href="https://towardsdatascience.com/how-youtube-recommends-videos-b6e003a5ab2f">YouTube</a> and <a href="https://help.netflix.com/pt/node/100639">Netflix</a> use recommendation systems for recommending new content to their customers.</p><h3>Recommender systems goals</h3><p>Recommender systems promise a lot of benefits to business, such as:</p><ul><li><a href="https://econsultancy.com/retail-case-study-personalisation-recommendation/">Increased conversion rate</a>;</li><li><a href="https://cseweb.ucsd.edu/~daricket/papers/recsys.pdf">Higher profit margin</a>;</li><li><a href="https://link.springer.com/article/10.1007/s11257-011-9118-4">The user will like your platform better</a>;</li><li><a href="https://link.springer.com/article/10.1007/s11257-011-9118-4">Improves User Experience</a>;</li><li><a href="https://pdfs.semanticscholar.org/1e10/bb91d12bee7f35f75013104b01748150c418.pdf">Increases your LTV and decreases Churn rate.</a></li></ul><h3>Common approaches</h3><p>There are several ways to build a recommendation system, using complex machine learning algorithms or just basic math, the most popular approaches being collaborative filters and content-based filter.</p><p><strong>Collaborative filters</strong><br>In this class of algorithms, for each user an item is indicated based on another user with “similar behavior”. For example, Alice and Bob are two people with similar interests in TV shows. Alice recently watched and liked Game of Thrones, but Bob has not watched it yet. The recommendation system will automatically recommend Game of Thrones to Bob, since his interests are similar to Alice’s.</p><p><strong>Content-based filters</strong><br>When the company knows its products in detail, it is possible to implement a content-based filter system. To implement it, it is necessary to classify all products with tags or similar properties. For example, if I watch the Supernatural TV show, it contains the ‘terror’ and ‘comedy’ tags, so the algorithm will recommend similar tagged content, like the TV show Lucifer.</p><h3>End-to-end collaborative filter</h3><p>Some steps are required to implement a basic collaborative filter system:</p><ul><li>Get similarity between users or objects;</li><li>Understand the mathematical concept of similarity;</li><li>Implement the recommender model.</li></ul><p><strong>Measuring similarity</strong><br>The concept of similarity is a complement to distance. The distance between two points can be easily obtained using the Euclidean distance, by calculating the length of a straight line connecting two points. When we talk about similarity, instead of finding out how far two points are, our goal is to find out “how close” the points are. The similarity value is usually expressed as a number between 0 and 1, where 0 means a low similarity, and 1 a high similarity.</p><p><strong>Cosine similarity</strong><br>With two vectors U and V, where U=(3, 5) and V=(1, 5), the distance between U and V can be easily calculated by using Euclidean distance. But how <em>similar</em> are these vectors? A common way to measure similarity is called <em>cosine similarity</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*le_zBpXjmL8WFVc7RbnWVw.png" /><figcaption>U (1,5) red and V (3,5) black. Image from author</figcaption></figure><p>To measure similarity, we need to calculate the angle between the vectors.<br>The smaller the angle, the greater the similarity. To verify, just remember the properties of the cosine function:</p><ul><li>cos(0º) = 1</li><li>cos(90º) = 0</li><li>cos(180º) = -1</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*43ai3bVQ18_xpjHaF2hcRQ.png" /><figcaption>Theta angle between the vectors. In this case 19.65°, similarity = 0.69</figcaption></figure><p>That is, using cosine similarity, when the angle between the vectors approaches 0º, the vectors are very similar (parallel with the same direction), so the similarity is 1. When the angle reaches 90º, the vectors are orthogonal and the similarity is 0º. Finally, with an angle of 180º, the vectors are opposite with similarity -1. Considering only non-negative vectors (in the first quadrant of the Cartesian plane) the similarity varies only between 0 and 1.<br>With this concept in mind, the similarity can be calculated with the following equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*aHuWqack1Rw8xFW7mrMhwg.png" /><figcaption>Similarity Equation</figcaption></figure><p>This formula exists in every Linear Algebra book and should be familiar to engineering, physics and mathematics students.</p><p><strong>Collaborative filter algorithm</strong><br>The next step after learning how to calculate similarity, is to implement the concept in a collaborative filter algorithm. The process uses similarity between users of a fictional platform.</p><p>Defining the problem:</p><ul><li>Our problem is movie recommendation. Given an [<em>i, j</em>] matrix, consider the rating of<em> i</em> users for <em>j</em> movies with the user rating represented by an integer ranging from 1 to 5. If the movie was not rated, its rating is 0;</li><li>For each user, the goal is to recommend a series of movies they have not watched (rating = 0);</li><li>For each movie <em>j</em> and user <em>i</em> who did not watch the movie, we try to find a user from a group U that is similar to user<em> i</em> who has watched the movie <em>j</em>;</li><li>For each similar user <em>u</em> get the rating for the movie <em>j</em> and multiply by the cosine similarity of the user <em>i</em> with <em>u</em>. Dividing the result by the number of users in the U set, we have the weighted average rating for the movie <em>j</em>;</li><li>Now sort the movies by the average obtained for each user and use this value to estimate the user’s rating of the movie, then recommend the first N movies in the ranking for each user.</li></ul><p>This technique is so similar to the KNN algorithm that, with some adaptations, it can be used to solve the recommendation problem (which will be explained later).</p><p>For example: imagine that I did not watch the movie Forrest Gump, but I watched and rated many other movies. All you have to do is to find a group of users who watched movies that I also watched, and also watched Forrest Gump.</p><p>In this example, let’s suppose that we find 2 users with preferences similar to mine. Let’s assume that the first one has a 90% similarity to me and has given 5 stars to the movie, and the second one has an 80% similarity to me and has given 3 stars to the movie. To estimate my rating, the weighted average (0.9×5 + 0.8×3) / 2 = 3.45 is calculated.</p><p><strong>Surprise</strong></p><p><a href="http://surpriselib.com/">Surprise</a> is a Python library for building and analysing recommender systems. There is also a built-in MovieLens Dataset with 100,000 movie ratings, from 1,000 users and 1,700 movies. The main purpose of Surprise is to give their users the perfect control over their experiments, provide several ready-to-use prediction algorithms - such as SVD - neighbourhood methods, similarity measures and tools to analyse and compare algorithm performance.</p><p>Let&#39;s explore Surprise.</p><p>Load the MovieLens 100k dataset and import it in Python:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe6396e8b663e220c2bc28fc003a8960/href">https://medium.com/media/fe6396e8b663e220c2bc28fc003a8960/href</a></iframe><p>The next step is to select an estimator and similarity measure. In this implementation, the idea is to use a collaborative item-item filtering approach. The estimator selected is KnnBasic with cosine similarity:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b7c70cab9245cb855b4724cc98282ae/href">https://medium.com/media/0b7c70cab9245cb855b4724cc98282ae/href</a></iframe><p>The method <em>build_anti_testset</em> allows us to make recommendations to new users, finding all the user-movie pairs in the training set where the user has not watched the movie, and creates a “test suite” from these entries. From its result, we sort and retrieve the top 3 recommendations for each user:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41358aad89f4061809236ab6a6fd34ca/href">https://medium.com/media/41358aad89f4061809236ab6a6fd34ca/href</a></iframe><p>To see the output, just map the movie ID with their name to each user. In the surprise Github dataset you can find this code and others.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8daf1d16f1c0a690e88697ab877ed8a4/href">https://medium.com/media/8daf1d16f1c0a690e88697ab877ed8a4/href</a></iframe><p><strong>The result:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e96294b06e03a55ff528732c8e9a2e17/href">https://medium.com/media/e96294b06e03a55ff528732c8e9a2e17/href</a></iframe><p>As you can see, each user receives personalised recommendations based on past ratings. A weakness of collaborative filtering is called “cold start” which is characterised by the question:</p><blockquote>How will we make recommendations to new users?</blockquote><p>Netflix gives its new users a list to select some content that they like. I believe that from that moment on it makes the recommendations.</p><p><strong>Conclusion</strong><br>In this post we saw how to implement a collaborative filter from end to end, from the beginnings of linear algebra, cosine similarity, recommendation system types to a “hello world” of the surprise library with KNN algorithm. It is highly recommended to explore the most out of the surprise library, test other estimators from the surprise lib, and the next step is to use deep learning to make our recommender algorithm, like <a href="https://www.cs.toronto.edu/~hinton/csc321/readings/boltz321.pdf">Boltzmann Machines</a>.</p><p><strong>References</strong></p><p>[1] C. Mathieu A. Das and D. Ricketts. Maximizing profit using recommender systems. WWW, 2010.</p><p>[2] H. Anton. Elementary Linear Algebra. John Wiley Sons, Incorporated,1993.</p><p>[3] Z. Gantner H. S. C. Newell B. P. Knijnenburg, M. C. Willemsen. Explaining the user experience of recommender systems, user modeling and user-adapted interaction,. 2012.</p><p>[4] T.Keenan. What is content-based filtering?https://www.upwork.com/hiring/data/what-is-content-based-filtering/. Last accessed 18 August 2019.</p><p>[5] S.Luo. Introduction to recommender system. https://towardsdatascience.com/intro-to-recommender-systemcollaborative-filtering-64a238194a26, 2018. Last accessed 18 August 2019.</p><p>[6] M. Nadeem. How youtube recommends videos. <a href="https://towardsdatascience.com/how-youtube-recommends-videos-b6e003a5ab2f">https://towardsdatascience.com/how-youtube-recommends-videos-b6e003a5ab2f</a> , 2018. Last accessed 18 August 2019.</p><p>[7] Netflix. How the Netflix recommendation system works. https://help.netflix.com/pt/node/100639. Last accessed 18 August 2019.</p><p>[8] R. Sentance. How to boost conversion rates by 32%: a recommendation engine case study. https://econsultancy.com/retail-case-study-personalisation-recommendation/, 2018. Last accessed 18 August 2019.</p><p>[9] Surprise. Surprise overview. <a href="http://surpriselib.com/">http://surpriselib.com/.</a> Last accessed 18 August 2019.</p><p>[10] Z. Tabaei and M. Fathian. Using customer lifetime value model for product recommendation: An electronic retailing case study. IJEEEE, 2012.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=531e8315ba58" width="1" height="1" alt=""><hr><p><a href="https://medium.com/playkids-tech-blog/recommender-systems-with-collaborative-filters-531e8315ba58">Recommender systems with collaborative filters</a> was originally published in <a href="https://medium.com/playkids-tech-blog">PlayKids Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sistemas de recomendação com filtros colaborativos]]></title>
            <link>https://medium.com/@gabrielghellere/sistemas-de-recomenda%C3%A7%C3%A3o-com-filtros-colaborativos-58fe77844886?source=rss-3a236877c979------2</link>
            <guid isPermaLink="false">https://medium.com/p/58fe77844886</guid>
            <category><![CDATA[recomendação]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[matemática]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Gabriel Ghellere]]></dc:creator>
            <pubDate>Mon, 15 Apr 2019 18:38:39 GMT</pubDate>
            <atom:updated>2019-04-16T02:25:13.779Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Dry17pMX6cvDNs40Z4MqA.jpeg" /></figure><p>U m dos tópicos de estudo que sempre me chamou atenção na área de Data Science são os sistemas de recomendação, tais sistemas são amplamente utilizados por pequenas e grandes empresas para diversos fins, por exemplo a Amazon recomendando livros para seus clientes baseado em compras anteriores ou o <a href="https://towardsdatascience.com/how-youtube-recommends-videos-b6e003a5ab2f">YouTube</a> e <a href="https://help.netflix.com/en/node/100639">Netflix</a> recomendando conteúdos novos a seus usuários antigos.</p><h4>Porque usar?</h4><ul><li><a href="https://blog.conversionfanatics.com/product-recommendations-4-ways-increase-sales-conversion-rates/">Aumenta sua taxa de conversão</a>.</li><li>Maior margem de lucro.</li><li>O usuário vai gostar mais da sua plataforma.</li><li>Melhora a User Experience.</li><li>Aumenta seu <a href="https://en.wikipedia.org/wiki/Customer_lifetime_value">LTV</a> e diminui a taxa de <a href="https://en.wikipedia.org/wiki/Churn_rate">Churn</a>.</li></ul><h4>Soluções populares</h4><p>Existem inúmeras maneiras de criar um sistema de recomendação com algoritmos complexos de Machine Learning ou simplesmente com matemática básica, as duas abordagens mais populares são Filtros Colaborativos e filtros baseados em conteúdo.</p><ol><li><a href="https://en.wikipedia.org/wiki/Collaborative_filtering">Filtros colaborativos</a>: Nesse tipo de filtro para cada usuário é indicado um item baseado em outro usuário com um &quot;gosto similar&quot;. Um exemplo fácil de entender para esclarecer melhor, seria duas pessoas, no qual chamaremos de Alice e Bob, ambas tem interesses semelhantes em séries em séries e Alice recentemente assistiu e gostou de Game of Thrones, porém Bob ainda não assistiu, logo que o sistema de recomendação aprendeu que Alice e Bob tem uma similaridade em seu perfil o algoritmo se encarrega de recomendar Game of Thrones para Bob.</li><li><a href="https://www.upwork.com/hiring/data/what-is-content-based-filtering/">Filtros baseados em conteúdo</a>: Se a empresa tem características muito detalhadas sobre seus produtos o filtro pode agir recomendando itens com características (tags) semelhantes. Por exemplo se eu assisto o seriado Supernatural esse conteúdo pode conter as tags &#39;terror&#39;, &#39;comedia&#39; e &#39;teen&#39; então o algoritmo vai me recomendar um conteúdo com tags semelhantes como a serie Lucifer por exemplo.</li></ol><h4>Filtros Colaborativos</h4><p>Nesse artigo vamos se aprofundar em Filtros colaborativos nos seguintes tópicos:</p><ol><li>Como obter a similaridade entre usuários ou objetos.</li><li>Entender o conceito matemático de similaridade com vetores.</li><li>Como usar um modelo de filtro colaborativo.</li><li>Implementar um sistema de recomendação básico com a biblioteca <a href="http://surpriselib.com/">Surprise</a> em Python.</li></ol><h4>Medindo similaridade</h4><p>O conceito de similaridade é um complemento a distância. A distância entre dois pontos pode ser facilmente obtida utilizando a distância <a href="https://en.wikipedia.org/wiki/Euclidean_distance">euclidiana</a> calculando o comprimento de uma linha reta que liga os dois pontos. Quando falamos de similaridade ao invés de descobrir o quão longe dois pontos estão (distancia euclidiana) nosso objetivo é descobrir &quot;quão perto&quot; os pontos estão, por isso a similaridade também é chamada de &quot;anti-distância&quot;. O valor de similaridade geralmente é expresso em um número entre 0 e 1, onde quando o 0 é obtido significa que os objetos não apresentam similaridade e 1 significa similaridade total.</p><h4>Similaridade de Cosseno</h4><p>Agora vamos falar sobre a forma mais comum de medir a similaridade, a similaridade de cosseno. Se eu te der dois vetores U e V, onde U = 3,5) e V = (1,5) você pode me dizer facilmente o quão perto esses vetores estão usando a distância euclidiana. Mas se eu perguntar, quão similares são esses dois vetores?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rwZVPQ0xQ8TIiS2Hy3rk2Q.png" /><figcaption>Vetores U e V</figcaption></figure><p>Para medir a similaridade basta calcular o ângulo entre os vetores, quanto menor o ângulo maior a similaridade, para verificar basta lembrar das propriedades da função cosseno:</p><ol><li>Cos(0°) = 1</li><li>Cos(90°) = 0</li><li>Cos(180°) = -1</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fQCc48h3UwzxwBkuOLmPXg.png" /></figure><p>Ou seja, usando a similaridade de cosseno quando o ângulo entre os vetores se aproxima de 0° os vetores são muito similares (paralelos com mesmo sentido), portanto a similaridade é 1. Quando o ângulo chega a 90° os vetores são ortogonais e a similaridade é 0, por fim com um angulo de 180° os vetores são opostos com similaridade -1. Considerando somente vetores não negativos (no primeiro quadrante do plano cartesiano) a similaridade varia somente entre 0 e 1.</p><p>Agora que entendemos o conceito, para calcular a similaridade basta usar a fórmula abaixo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*VuBiLiZC-8nyqbbM8A-O9Q.png" /></figure><p>Essa fórmula é uma velha conhecida de quem cursou Álgebra Linear e Geometria Analítica, ela nos fala que o cosseno do angulo entre dois vetores é igual ao produto escalar dos vetores dividido pelo produto do módulo deles.</p><h4>Modelo de filtro Colaborativo</h4><p>Agora que sabemos medir a similaridade entre dois vetores podemos usar esse mesmo método para medir a similaridade entre usuários de uma plataforma x, para tal é proposto o seguinte problema:</p><ol><li>Nosso problema consiste na recomendação de filmes, dada uma matriz i x j considerando as avaliações (rating) de i usuários para j filmes com o rating representado por um inteiro que varia de 1 a 5, quando o filme não foi classificado o rating é 0.</li><li>Pra cada usuário o objetivo é recomendar uma série de filmes que ele não assistiu (rating = 0).</li><li>Para cada filme j e usuário i que não assistiu o filme encontramos um grupo de usuários U que é similar com o usuário i que já assistiu o filme j. Para cada usuário similar u pegue a classificação do usuário para o filme j e multiplique pela semelhança de cosseno do usuário i com o u. Dividindo o resultado pelo numero de usuários no conjunto U temos a classificação média ponderada para o filme j.</li><li>Agora basta ordenar os filmes pela média obtida para cada usuário e usar esse valor como estimativa para a avaliação que o usuário fará do filme, então recomenda-se os N primeiros filmes do ranking para cada usuário.</li></ol><p>Essa técnica é muito semelhante com o algoritmo KNN tanto que com algumas adaptações ele pode ser usado para resolver o problema de recomendação (que é o caso do Surprise que será explicado em breve).</p><p>Para exemplificar imagine que eu não assisti o filme <a href="https://www.imdb.com/title/tt0109830/">Forest Gump</a>, porém eu assisti e avaliei muitos outros filmes. Com isso basta encontrar um grupo de usuários que assistiram filmes que eu também assisti porém que tenham assistido Forest Gump. No caso encontramos 2 usuários com um gosto parecido com o meu, vamos supor que o primeiro tem uma semelhança de 90% comigo e tenha atribuído 5 estrelas ao filme, o segundo tem uma semelhança de 80% comigo e atribuiu 3 estrelas ao filme. Para estimar a minha classificação calcula-se a média ponderada (0.9 * 5 + 0.8 * 3) /2 = 3.45.</p><h4>Surprise</h4><p>Para não implementar tudo isso na mão existe uma biblioteca para python chamada <a href="http://surpriselib.com/">Surprise</a> que foi arquitetada para executar um modelo simples de sistema de recomendação. Existe também o <a href="https://grouplens.org/datasets/movielens/">MovieLens Dataset</a> integrado com o surprise onde temos 100000 ratings de filmes com 1000 usuários e 1700 filmes.</p><p>Então, mão na massa, primeiro carregamos o dataset e importamos o surprise no python.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe6396e8b663e220c2bc28fc003a8960/href">https://medium.com/media/fe6396e8b663e220c2bc28fc003a8960/href</a></iframe><p>O próximo passo é calcular a semelhança de cosseno entre os filmes para realizar as recomendações usando a abordagem de filtragem colaborativa item-item, apesar de não ser a abordagem usuário-usuário explicada anteriormente o modelo é facilmente adaptável e a metodologia é a mesma, esse método é mais fácil de implementar no MovieLens dataset, pois cada filme contém um vetor de todas as suas classificações, assim se calcula a semelhança de cosseno entre os vetores de cada filme e treinamos o modelo.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b7c70cab9245cb855b4724cc98282ae/href">https://medium.com/media/0b7c70cab9245cb855b4724cc98282ae/href</a></iframe><p>Agora para fazer as recomendações aos novos usuários, usando o método build_anti_testset, podemos encontrar todos os pares de filmes do usuário no conjunto de treinamento em que o usuário não viu o filme e criar um “conjunto de testes” a partir dessas entradas. Em seguida ordenamos e pegamos as 3 principais recomendações para cada usuário:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41358aad89f4061809236ab6a6fd34ca/href">https://medium.com/media/41358aad89f4061809236ab6a6fd34ca/href</a></iframe><p>Para ver a saída basta mapear o ID do filme com seu respectivo nome para cada usuário, no dataset no <a href="https://github.com/NicolasHug/Surprise/blob/master/examples/k_nearest_neighbors.py">github do surprise</a> pode-se encontrar esse código e outros que podem vir a ajudar.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e17f6aa4ecfe735874bfee006d62321/href">https://medium.com/media/0e17f6aa4ecfe735874bfee006d62321/href</a></iframe><p>Obtendo:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e96294b06e03a55ff528732c8e9a2e17/href">https://medium.com/media/e96294b06e03a55ff528732c8e9a2e17/href</a></iframe><p>Como pode-se observar cada usuário recebe recomendações personalizadas com base nas classificações passadas. Um ponto fraco da filtragem colaborativa é chamado de &quot;could start&quot; que é caracterizado pela pergunta:</p><blockquote>Como vamos realizar recomendações a novos usuários da base?</blockquote><p>O netflix mostra uma lista de catálogo e pede para o novo usuário escolher 3 filmes/séries do seu gosto (3 é o total, pode ser 1 filme e 2 séries por exemplo). Acredito que a partir desse momento ele passa a fazer as recomendações.</p><h4>Conclusão</h4><p>Nesse artigo vimos como implementar um filtro colaborativo do início ao fim, passando pelos primórdios da álgebra linear e similaridade de cosseno até um hello world da biblioteca Surprise com o algoritmo KNN. Logo pode-se perceber que filtros colaborativos são ótimas ferramentas para Cientistas de Dados realizarem recomendações de produtos a usuários em uma base potencializando a empresa como um todo e aumentando a afinidade do cliente com os conteúdos/produtos da empresa.</p><p>Este artigo foi baseado nas seguintes fontes (são ótimas leituras pra quem quiser se aprofundar no tema.):</p><p><a href="https://blog.dominodatalab.com/recommender-systems-collaborative-filtering/">Recommender Systems through Collaborative Filtering by Manojit Nandi</a></p><p><a href="http://surpriselib.com/">Surprise Documentation</a></p><p><a href="http://infolab.stanford.edu/~ullman/mmds/ch9.pdf">Recommendation Systems</a></p><p><a href="http://www.mmds.org/">MMD Book</a></p><p><a href="https://eusoudev.com.br/similaridade-entre-comentarios/">Similaridade entre comentários by Octavio Santana</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58fe77844886" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Como usar Data Science para estudar pokemons!]]></title>
            <link>https://medium.com/introdu%C3%A7%C3%A3o-ao-jupyter-pandas-e-pokemons/como-usar-data-science-para-estudar-pokemons-d2ea294f713b?source=rss-3a236877c979------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2ea294f713b</guid>
            <dc:creator><![CDATA[Gabriel Ghellere]]></dc:creator>
            <pubDate>Wed, 15 Aug 2018 13:50:44 GMT</pubDate>
            <atom:updated>2018-08-15T13:50:44.100Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1291ec7614b2f3090c3e8ba3fdf032c3/href">https://medium.com/media/1291ec7614b2f3090c3e8ba3fdf032c3/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2ea294f713b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/introdu%C3%A7%C3%A3o-ao-jupyter-pandas-e-pokemons/como-usar-data-science-para-estudar-pokemons-d2ea294f713b">Como usar Data Science para estudar pokemons!</a> was originally published in <a href="https://medium.com/introdu%C3%A7%C3%A3o-ao-jupyter-pandas-e-pokemons">Introdução ao jupyter, pandas e pokemons.</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>