<?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 Fabiana Tortorelli on Medium]]></title>
        <description><![CDATA[Stories by Fabiana Tortorelli on Medium]]></description>
        <link>https://medium.com/@fabitortorelli?source=rss-ffa71f50e95b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2nCnoR0kTkHGu_wi4ERuZw.png</url>
            <title>Stories by Fabiana Tortorelli on Medium</title>
            <link>https://medium.com/@fabitortorelli?source=rss-ffa71f50e95b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 08:58:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fabitortorelli/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[Autovalor/Autovetor e Análise de Componentes Principais (PCA)]]></title>
            <link>https://medium.com/@fabitortorelli/autovalor-autovetor-e-an%C3%A1lise-de-componentes-principais-pca-80ec9ee8fefb?source=rss-ffa71f50e95b------2</link>
            <guid isPermaLink="false">https://medium.com/p/80ec9ee8fefb</guid>
            <category><![CDATA[pca-analysis]]></category>
            <category><![CDATA[álgebra-linear]]></category>
            <category><![CDATA[estatistica]]></category>
            <category><![CDATA[eigenvectors]]></category>
            <dc:creator><![CDATA[Fabiana Tortorelli]]></dc:creator>
            <pubDate>Fri, 29 Nov 2024 13:22:50 GMT</pubDate>
            <atom:updated>2024-11-29T13:40:52.753Z</atom:updated>
            <content:encoded><![CDATA[<p>A Análise de Componentes Principais (PCA) é uma técnica estatística que transforma um conjunto de variáveis correlacionadas em um novo conjunto de variáveis linearmente não correlacionadas, conhecidas como componentes principais. É amplamente utilizada para redução de dimensionalidade, especialmente quando lidamos com muitos atributos explicativos em um conjunto de dados, mantendo as informações mais relevantes do conjunto original. Além disso, a PCA é útil para lidar com problemas de colinearidade entre variáveis.</p><p>Neste post, explorarei o conceito de PCA com um exemplo prático. Para isso, considere o seguinte conjunto de dados:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/219/1*vqtGOGK2OW2DtAMUhCgdRQ.png" /></figure><p>Ao representarmos graficamente as observações das variáveis X1 e X2, teremos:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*Eiyw5_99xBIawSh5_hLyLQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*pp8ZBWLJUUOrJkw8RDJZAw.png" /></figure><p>Agora, ao plotarmos as observações de X1 e X2​ em um gráfico de dispersão, com X1 no eixo horizontal e X2​ no eixo vertical, temos:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*KJxlUT1Bcy6KKexw9787lQ.png" /></figure><p>Para aplicar a PCA, precisamos calcular a média de cada variável, pois o método usa as covariâncias das variáveis. No exemplo, a média de X1​ é 2, e a média de X2 é aproximadamente 4,67. Plotando esses valores no gráfico de dispersão (X1 vs X2), temos:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*x9mTvhC-MO2iBhKS3jCv6A.png" /></figure><p>A covariância calcula a variabilidade conjunta das variáveis. Quando calculamos a covariância de uma variável apenas, X1 ou X2, na prática estamos calculando a variância dessa variável.</p><p>O cálculo da covariância começa com a determinação dos desvios das observações em relação às médias (diferenças entre os valores observados e as médias). Para lidar com os sinais opostos dos desvios, elevamos esses valores ao quadrado (ou, no caso da covariância entre duas variáveis, multiplicamos os desvios correspondentes de X1​ e X2​). Por fim, somamos os resultados e dividimos por n−1, obtendo assim uma medida média que reflete a relação entre as variáveis.</p><p>Visualmente, podemos ver que os desvios ao quadrado para X1, X2 e X1 vs X2 são dados por:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gp9_4C8BGzwgaxVLs51w7w.png" /></figure><ul><li><strong>Covariância positiva</strong>: Se a covariância entre duas variáveis é positiva, isso significa que, quando uma variável aumenta, a outra tende a aumentar também. Ou seja, elas possuem uma relação direta.</li><li><strong>Covariância negativa</strong>: Quando a covariância é negativa, significa que, quando uma variável aumenta, a outra tende a diminuir, ou seja, há uma relação inversa entre elas.</li><li><strong>Covariância zero</strong>: Uma covariância próxima de zero indica que não há relação linear aparente entre as variações das duas variáveis.</li></ul><p>No exemplo, as covariâncias resultaram em:</p><ul><li>Cov(X1,X1) = 1</li><li>Cov(X2,X2) = 41,33</li><li>Cov(X1,X2) = Cov(X2,X1) = -6</li></ul><p>Podemos observar que a variável X2 possui uma maior variância e a covariância entre X1 e X2 é negativa.</p><p>Como o objetivo do PCA é encontrar as <strong>direções principais</strong> (componentes principais) que maximizam a variância dos dados, é usado a matriz de covariância, a qual indica quais variáveis têm maior variabilidade e como estão correlacionadas. Para encontrar as direções principais, é preciso identificar os autovetores da matriz de covariância.</p><h4>Uma breve explicação sobre Autovetor e Autovalor</h4><p>Em Álgebra Linear, um autovetor é um vetor que após uma transformação linear, ele não sofre rotação, apenas aumenta ou diminui de tamanho. E cada autovetor está associado à um autovalor, que é um valor (escalar) e indica o quanto esse vetor irá aumentar ou diminuir.</p><p>Visualmente, considere o plano abaixo caracterizado pelos vetores base destacados em preto:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*kNmwjMK2cY7fL5maPk7D1g.png" /></figure><p>Após uma transformação linear, <strong>os vetores base são alterados</strong>, tendo uma característica como abaixo. Lembrando, que quando temos uma alteração de base, as coordenadas dos vetores (sem ser os vetores base) são definidos de acordo com os vetores base:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*brioGcKjOQq9IuHLCIsVgA.png" /></figure><p>Portanto, autovetores são vetores no espaço original (o plano acima) que após a transformação, eles apenas aumentam ou diminuem. Vamos supor que os autovetores são os destacados em azul e em vermelho:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*Vrme8dGSWXqjDgBGZWzbSg.png" /></figure><p>Após a transformação, eles ficam do mesmo jeito, aumentam ou diminuem:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E4nDdkTd0faNpomFVQeMFg.png" /></figure><h4>Identificando as direções principais</h4><p>As <strong>direções de maior variância</strong> são determinadas pelos <strong>autovetores</strong> da matriz de covariância. Os <strong>autovalores</strong> associados a esses autovetores indicam a quantidade de variância explicada em cada direção.</p><p>Portanto, a matriz de covariância é a transformação considerada:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*OviLGRsrtb7vNOPe-ieFHg.png" /></figure><p>Visualmente, os vetores base novos após a transformação são definidos pelos pontos 1 e -6, e -6 e 41.33, respectivamente, conforme a imagem direita. Ainda nesta imagem, as observações originais estão plotadas apenas para a explicação, pois como houve uma transformação linear, elas também são transformadas de acordo com os novos vetores base:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*xpgeSJCtBKKRyjVFQBi1Pg.png" /></figure><p>Para encontrar os autovetores e autovalores da transformação, que é a matriz de covariância, precisamos resolver a seguinte equação:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/191/1*k1OKoQ_Jmhbi6T0HF9OA8g.png" /></figure><p>Em que o vetor V representa a matriz dos autovetores e lambda representa os autovalores.</p><p>Para resolver a equação acima é necessário resolver:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/236/1*jy5oY_PydFt_jRpCDFcuaw.png" /></figure><p>Em que ‘det’ é o determinante de uma matriz e I é a matriz identidade. Para chegar na expressão acima, precisamos fazer a seguintes manipulações:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*IZXKVrJMBr-V5fHCvmwKSg.png" /></figure><p>Como queremos um vetor V não nulo, a equação acima é verdadeira se o determinante acima for igual a zero. Para ficar um pouco mais claro, considere que o determinante seja diferente de zero e portanto a matriz possui inversa e então:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*uG8OYi9poET90V9gfciGNA.png" /></figure><p>Mas como queremos um V não nulo, devemos considerar o determinante igual a zero.</p><h4>Uma breve explicação sobre determinante</h4><p>Em Álgebra Linear, o determinante de uma matriz associada a uma transformação linear indica o <strong>fator de escala</strong> de áreas (ou volumes) após a transformação.</p><ul><li>det(A) = k: A área (ou volume) é escalada por k;</li><li>det(A) &lt; 0: A transformação inverte a orientação (ex.: reflexão);</li><li>det(A) = 0: as linhas ou colunas de uma matriz são <strong>linearmente dependentes</strong>.</li></ul><p>Considerando o espaço definido pelos vetores base como abaixo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/1*7jGefFBOaQin9guxT4u3Og.png" /></figure><p>Temos que a área, ou seja, o determinante é A conforme abaixo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/1*shYZoV1kg4WPVBtIr1uN_w.png" /></figure><p>Se tivermos uma transformação que aumenta em 3 o vetor horizontal e em 2 o vetor vertical, o determinante dessa transformação será 6A:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*kjSv2yrj2rqV0xczjeSp5g.png" /></figure><p>Caso a transformação faça com que os vetores base diminuam em uma escala específica, poderíamos ter o determinante menor que A, no caso 0.1A:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/1*cGhVkIBTm-kBqmTC1tGIxg.png" /></figure><p>Se tivermos uma transformação em que a orientação dos vetores base altera, o determinante será negativo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/1*DlJa2SvU0UA-Mo4xvUMb3g.png" /></figure><p>E por fim, se tivermos uma transformação em que os vetores base são linearmente dependentes, o determinante será zero, pois a área é zero:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/1*HvPbZULKxY2bf_oTE6J4TQ.png" /></figure><h4>Propriedades dos autovetores e autovalores</h4><p>O <strong>primeiro autovetor</strong> (direção da primeira componente principal) aponta na direção de maior variância nos dados. O <strong>segundo autovetor</strong> aponta na segunda maior direção de variância, sendo ortogonal ao primeiro. Assim, a decomposição da matriz de covariância em autovalores e autovetores fornece as componentes principais, ordenadas por importância.</p><p>No exemplo acima, temos que os vetores base são definidos pela matriz de covariância (destacados em preto na figura abaixo) e os autovetores identificados são definidos pelos pares {-0.14,0.99} (em azul) e { -0.99,-0.14} (em vermelho). O autovalor associado ao vetor em azul é 42.20 e o associado ao vetor em vermelho é 0.12:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*IuYWork13MCtBTi73W9iuw.png" /></figure><h4>Redução de dimensionalidade</h4><p>Ao projetar os dados nas direções associadas aos maiores autovalores (componentes principais), podemos reduzir a dimensionalidade mantendo a maior parte da variabilidade dos dados.</p><p>Portanto, o vetor {-0.14,0.99} explica 99% da variância, pois o autovalor é 42.20 e então 42.20/(42.20+0.12) = 42.20/42.32 = 0.99 = 99%.</p><p>Se imaginarmos duas linhas que passam pelos autovetores, conforme as linhas em rosa:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*GRe6VXJ-1kTt7_6x6U-TIw.png" /></figure><p>E rotacionarmos o gráfico deixando a linha que passa pelo autovetor que explica a maior parte da variância na horizontal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/246/1*a4LGvWvoWc1qkVdT4Xt2qQ.png" /></figure><p>E plotarmos as observações originais transformadas:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*Q4i3u4l5qnyJqWgI7XBv0g.png" /></figure><p>Conseguimos visualizar a variação dos dados em cada componente:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*udk-RBB3yYIOeESsp-ddhQ.png" /></figure><p>Portanto, ao aplicar a PCA para reduzir a dimensionalidade dos dados deste exemplo, utilizaríamos a <strong>PC1</strong>, pois ela captura a maior parte da variabilidade presente nos dados, representando as informações mais relevantes de ambas as variáveis.</p><p>Resumidamente, o processo de PCA envolve os seguintes passos:</p><ol><li><strong>Cálculo da matriz de covariância</strong>: Essa matriz representa como as variáveis originais se relacionam entre si e é a base para identificar as direções principais de variação.</li><li><strong>Determinação dos autovalores e autovetores</strong>: Os autovetores definem as direções das componentes principais, enquanto os autovalores indicam a quantidade de variabilidade capturada por cada componente.</li><li><strong>Identificação das componentes principais</strong>: Ordenamos os autovalores em ordem decrescente e selecionamos as componentes principais correspondentes (os autovetores) para reduzir a dimensionalidade dos dados, preservando o máximo de informação possível.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hb6NIa5wX-R6Eaf9LZisAQ.png" /></figure><h4>Interpretação da componente principal</h4><p>Cada componente principal é uma combinação linear das variáveis originais, ou seja:</p><ul><li>CP1 = −0.14X1​ + 0.99X2​</li><li>CP2 = −0.99X1​ + (-0.14)X2​</li></ul><p>Peso −0.14<strong> (de X1​)</strong>: Mostra que X1 tem uma influência negativa e pequena na direção principal da variância.</p><p>Peso 0.99<strong> (de X2​)</strong>: Mostra que X2 domina a primeira componente principal, contribuindo muito mais para a variância nesta direção.</p><p>Portanto, temos que a contribuição da variável X1 é aproximadamente 13.4% e da variável X2 é 87.6%, pois:</p><ul><li>|-0.14|/(|-0.14| + |0.99|) ≈ 0.124</li><li>|0.99|/(|-0.14| + |0.99|) ≈ 0.876</li></ul><h4>Relação entre VIF e PCA</h4><p>O <strong>VIF</strong> (Fator de Inflação da Variância) é uma medida da colinearidade entre uma variável e as demais variáveis independentes no modelo. Ele indica o quanto a variância de um coeficiente de regressão é inflacionada devido à colinearidade com outras variáveis independentes. Um <strong>VIF elevado</strong> indica que uma variável está altamente correlacionada com outras variáveis independentes, o que pode prejudicar a interpretação e a precisão do modelo. Para cada variável Xj, o VIF é dado por:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*4tfAju_jB3lIcb4y_MQVqA.png" /></figure><p>Onde R² é o coeficiente de determinação da regressão Xj em função das outras variáveis. R² é dado por:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/219/1*HwQOZaeqTf2zIXLkyunT1g.png" /></figure><p>Em que SSE é a <strong>Soma dos Quadrados dos Erros </strong>e SST é<strong> Soma Total dos Quadrados</strong>. Pela fórmula, VIF igual a 1 significa que R² é zero, então SSE/SST é 1 e portanto SSE = SST (o modelo ajustado é a própria média). agora se R² é 1, VIF é uma indeterminação, pois fica um dividido por infinito, dando como resultado infinito. Com R² igual a 1 significa que SSE/SST é zero e portanto SSE é igual a zero (a reta ajustada passa pelos os pontos observados).</p><p>Para visualizar, se temos duas variáveis, a idea do VIF é calcular R² considerando:</p><ul><li>X1 = b0 + b1X2</li><li>X2 = b0 + b1X1</li></ul><p>Considere um conjunto de dados com duas variáveis, X1 e X2, dadas por:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/217/1*C-_Zg7HxOuAzc2TKn-462g.png" /></figure><p>Visualmente, notamos que elas são linearmente dependentes, X2 = 2X1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*KdPuaxUJyXSVNSQOHHWsTA.png" /></figure><p>Considerando y_hat = X1 = b0 + b1X2, para calcular R² precisamos calcular a <strong>Soma Total dos Quadrados</strong> (SST) dada por:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*GdgeRaqqaJ_KQUpZlFPBQA.png" /></figure><p>No gráfico abaixo podemos observar as diferenças quadradas de cada ponto yi = X1i da média geral dos dados (média de y = X1):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*IqclMhVMymsjPh6KfYoMaQ.png" /></figure><p>Também precisamos calcular a <strong>Soma dos Quadrados dos Erros</strong> (SSE):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/1*dX2X3C3MNi0yFnMX3NuNYw.png" /></figure><p>Ao ajustar a reta considerando y_hat = X1 = b0 + b1X2, temos que b0 = 0 e b1 = 0.5, portanto a reta ajustada é dada por y_hat = X1 = 0 + 0.5X2 = 0.5X2. Isso significa que a reta ajustada passa exatamente pelos pontos de X1​, resultando em um erro quadrático da soma dos erros (SSE) igual a zero, já que não há discrepância entre os valores observados e os valores ajustados:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*ez8ys0V75fxehF27b13Rog.png" /></figure><p>Como a SSE é igual a zero, isso implica que o modelo ajustado explica 100% da variabilidade dos dados, resultando em um R² = 1. Em termos de multicolinearidade, isso significa que as variáveis X1 e X2 são perfeitamente correlacionadas. Consequentemente, o <strong>Fator de Inflação da Variância (VIF)</strong> se aproxima de infinito, indicando que existe uma <strong>multicolinearidade perfeita</strong> entre as variáveis.</p><p>Agora, considere outras duas variáveis, X1 e X2, em que não sejam linearmente dependente entre si. Ao plotarmos as diferenças quadradas de cada ponto em relação à média geral dos dados, observamos um padrão diferente, como mostrado na imagem abaixo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*M-GwgMkxrMIKRlOCG8QC3A.png" /></figure><p>Ao calcular a <strong>Soma dos Quadrados dos Erros</strong> (SSE), observamos que essa soma não resultará em zero:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*_JapGS_1rXoVflDpcDHPog.png" /></figure><p>Plotando as diferenças quadradas no mesmo gráfico temos:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*Ntr00DDQNQgtbDuDKzKUxQ.png" /></figure><p>Neste exemplo, obtemos um R² igual a 0,42, o que implica que a variação explicada pelo modelo é moderada, e um VIF de 1,75, indicando que a multicolinearidade entre as variáveis é baixa e não representa um problema grave.</p><p>Embora o VIF e a PCA não estejam diretamente relacionados, é importante notar que, quando há multicolinearidade nos dados, a PCA pode ser uma solução eficaz. A PCA ajuda a combinar as variáveis correlacionadas em um conjunto menor de componentes principais, que são não correlacionados, reduzindo assim a multicolinearidade e preservando a maior parte da variabilidade dos dados.</p><p>O objetivo deste post foi apresentar uma visão geral sobre como funciona a Análise de Componentes Principais (PCA). É essencial lembrar que, ao aplicar essa técnica, é importante considerar algumas premissas, como a normalização dos dados, para garantir resultados mais precisos e significativos.</p><p>Caso tenha contribuições que possam enriquecer o entendimento desse tema, sinta-se à vontade para comentar.</p><p>Materiais usados para a construção deste artigo:</p><p>[1] <a href="https://pt.wikipedia.org/wiki/Autovalores_e_autovetores">https://pt.wikipedia.org/wiki/Autovalores_e_autovetores</a></p><p>[2] <a href="https://www.youtube.com/watch?v=FgakZw6K1QQ">https://www.youtube.com/watch?v=FgakZw6K1QQ</a></p><p>[3] <a href="https://www.youtube.com/watch?v=5HNr_j6LmPc">https://www.youtube.com/watch?v=5HNr_j6LmPc</a></p><p>[4] <a href="https://www.youtube.com/watch?v=PFDu9oVAE-g&amp;list=PLZHQObOWTQDPD3MizzM2xVFitgF8hE_ab&amp;index=15">https://www.youtube.com/watch?v=PFDu9oVAE-g&amp;list=PLZHQObOWTQDPD3MizzM2xVFitgF8hE_ab&amp;index=15</a></p><p>[5] <a href="https://www.datacamp.com/tutorial/variance-inflation-factor">https://www.datacamp.com/tutorial/variance-inflation-factor</a></p><p>[6] FÁVERO, L. P.; BELFIORE, P. Manual de Análise de Dados: Estatística e Modelagem Multivariada com Excel®, SPSS® e Stata®. 1. ed. Rio de Janeiro: Elsevier, 2017</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80ec9ee8fefb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Entendendo a Multicolinearidade]]></title>
            <link>https://medium.com/@fabitortorelli/entendendo-a-multicolinearidade-69dff24f7481?source=rss-ffa71f50e95b------2</link>
            <guid isPermaLink="false">https://medium.com/p/69dff24f7481</guid>
            <category><![CDATA[estatistica]]></category>
            <category><![CDATA[multicollinearity]]></category>
            <category><![CDATA[regressão-linear]]></category>
            <category><![CDATA[regressão-logística]]></category>
            <dc:creator><![CDATA[Fabiana Tortorelli]]></dc:creator>
            <pubDate>Thu, 14 Nov 2024 10:13:37 GMT</pubDate>
            <atom:updated>2024-11-14T10:13:37.715Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*AZn4v7WBd47mCYA75cBJxQ.png" /></figure><p>Para desenvolver modelos de Regressão Linear e Regressão Logística é necessário avaliar se há multicolinearidade entre as variáveis preditoras (variáveis independentes), isto é, se as variáveis estão altamente correlacionadas com uma ou mais outras variáveis preditoras.</p><p>Características como <strong>Renda </strong>e <strong>Nível de Educação</strong>, ou <strong>Frequência </strong>e<strong> Tempo Total de Compras</strong>, ou <strong>Peso </strong>e<strong> Índice de Massa Corporal (IMC)</strong>, ou <strong>Índice de Poluição do Ar </strong>e<strong> Qualidade do Ar</strong>, ou <strong>Autoestima</strong> e <strong>Satisfação com a Vida</strong>, geralmente estão altamente correlacionadas.</p><p>Portanto, é importante avaliar se existe multicolinearidade, pois ela pode complicar a interpretação dos modelos, ao tornar difícil separar o efeito das variáveis correlacionadas.</p><h3>Um exemplo de multicolinearidade</h3><p>Vamos considerar uma base de dados com quatro observações contendo três variáveis preditoras binárias, X1, X2 e X3 e uma variável resposta, Y, conforme a tabela abaixo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*8GKNbiiiTC-qa93sB7l_0A.png" /></figure><p>Percebemos que a variável X3 pode ser expressa como uma combinação linear de outras variáveis, ou seja, X3 = X1 + X2. Além disso, poderíamos ter outros casos, como variáveis binárias perfeitamente correlacionadas, por exemplo X1 = X3 ou X1 = 2X3, e variáveis complementares (X2 = 1 — X1).</p><h3>Multicolinearidade na estimação dos coeficientes</h3><h4><strong>1. Regressão Linear</strong></h4><p>Vamos considerar modelo de Regressão Linear para explicar a variável Y do exemplo acima utilizando as três variáveis preditoras (X1, X2 e X3). Desta forma, precisamos encontrar os valores dos coeficientes tal que:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*z25O7vCpPJftdl8u88ir3w.png" /></figure><p>Para estimar os valores dos coeficientes utilizando o método dos mínimos quadrados ordinários, temos que resolver a equação:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*aZQwhHE4OMkXQ6BWXN8lEw.png" /></figure><p>Considerando o exemplo, X, Y e X transposta da equação acima são dados por:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*jD-XKyCLuLYxwcKy2mQJkw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*tolaYdTgfWk7J4D78g4txA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*F637676YkKEc99rm5yTUOg.png" /></figure><p>Calculando o produto da X transposta e X chegamos no resultado abaixo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*uNTowxBhJyVpW44EFnMRSw.png" /></figure><p>Para calcular a inversa deste produto, precisamos calcular o determinante dele e neste caso temos que o determinante é zero (o cálculo foi feito usando python):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/191/1*xoG0NSKzAKi9juCSTopbFw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*ddtWmQGi5YXuKFKWMfkUKg.png" /></figure><p>Como o determinante é igual a zero (ou seja, for singular), não podemos calcular a inversa, pois a inversa de uma matriz singular não existe. Isso levará a um <strong>erro de cálculo</strong> ou ao surgimento de <strong>valores indefinidos</strong> (como NaN ou infinitos).</p><h4><strong>2. Regressão Logística</strong></h4><p>Agora, considerando o modelo de Regressão Logística, temos que:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*KKIEQPE_dsbJHN6rgZE5xg.png" /></figure><p>Em que P(Y = 1 | X) é a probabilidade de Y = 1 dados os valores das variáveis independentes X1, X2 e X3, e b0, b1, b2, b3 são os coeficientes que queremos estimar.</p><p>Para a estimação dos coeficientes, usamos a funçao log-verossimilhança. A funçao verossimilhança L, para n observações, é dada por:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*loI9FaDMSZ8CgyRLKrX5UA.png" /></figure><p>E a função log-verossimilhança, ℓ(b0, b1, b2, b3), é:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*rfP1MZNYms42vqEhuw2cog.png" /></figure><p>Portanto, precisamos das derivadas parciais em relação a cada parâmetro bj. A derivada parcial em relação a bj é:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*O9F4-ZgQha23TeL4-JAouQ.png" /></figure><p>Por fim, para encontrar os valores de b0, b1, b2, e b3, resolvemos o sistema de equações definido por:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/186/1*Nqu1exNCoDOUS3wuO459PA.png" /></figure><p>Aqui conseguimos calcular os coeficientes, conforme a tabela abaixo. Porém, observe que o erro padrão, o z score, p valor e intervalo de confiança resultou em nan. Um motivo para o erro padrão se tornar nan é a multicolinearidade. Quando isso ocorre, a matriz de covariância dos coeficientes torna-se singular ou quase singular (ou seja, seu determinante é muito próximo de zero), levando a um erro padrão indefinido. Como o p valor está relacionado ao erro padrão, também temos nan no resultado.</p><p><strong>Uma nota: </strong>outras situações podem resultar em erro padrão nan, como falta de variabilidade nas variáveis e número insuficiente de dados, mas vamos focar em multicolinearidade.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*uU62UtNrye_6E_OgRfrcLg.png" /></figure><p>E para exemplificar, ao retirar a variável X2 temos a estimativa dos coeficientes, bem como valores para erro padrão e p valor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*8mZbS6y8ihSdN_BuQbIRoQ.png" /></figure><h3>Identificando multicolinearidade</h3><p>Embora muitos acreditem que a <strong>matriz de correlação de Pearson</strong> captura a multicolienaridade entre as variáveis, ela não é a melhor técnica para essa avaliação.</p><p>Considerando o exemplo que estamos usando até agora, para calcular a correlação de Pearson entre as variáveis X1, X2 e X3, usamos a seguinte fórmula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*_KF4hMgW7X9QwZyuP4YsIA.png" /></figure><p>Onde:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*ZmonDhnUCbMVZiwmcghqgg.png" /></figure><p>As diferenças das variáveis em relação às suas médias são:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ncdf4CMlKURwbQWu8JQpSw.png" /></figure><p>Calculando o numerador da correlação rXY :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*p77il51SCSwW5eWV6aAjSg.png" /></figure><p>O denominador da fórmula para rXY é dado por:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*6H-GL6pjVaI5y_9mfWvNGg.png" /></figure><p>Agora, calculamos as correlações, temos que a o valor da correlação entre a variável X1 e X2 é -0.577 (correlação moderada), o valor entre X1 e X3 é +0.577 (correlação moderada) e o valor entre X2 e X3 é +0.333 (correlação fraca):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*d4aB3vc8HBWezQ9SDGBgIQ.png" /></figure><p>Plotando na matriz de correlação em um mapa de calor, temos:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*EzQwwg8qPaLOPrnFLU8Qwg.png" /></figure><p>Olhando para a matriz de correlação acima, apesar de conseguirmos norar correlações fracas e moderadas, não conseguimos concluir que a variável X3 é a combinação linear de X1 e X2.</p><p>Desta forma, o <strong>VIF</strong> (Fator de Inflação da Variância) é uma medida da colinearidade entre uma variável e as demais variáveis independentes no modelo. Ele indica o quanto a variância de um coeficiente de regressão é inflacionada devido à colinearidade com outras variáveis independentes. Um <strong>VIF elevado</strong> indica que uma variável está altamente correlacionada com outras variáveis independentes, o que pode prejudicar a interpretação e a precisão do modelo.</p><p>Para cada variável Xj, o VIF é dado por:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*IfeRC5o8PrgDy18j3Uy4tA.png" /></figure><p>Onde R² é o coeficiente de determinação da regressão Xj em função das outras variáveis. Primeiro, para calcular o Rj², realizamos a regressão de cada variável sobre as outras (para a demonstração do exemplo, vamos considerar o coeficiente b0 igual a zero):</p><ol><li>Regressão de X1 em função de X2 e X3: <strong>X1 = b1 x X2 + b2 x X3</strong></li><li>Regressão de X2 em função de X1 e X3: <strong>X2 = b1 x X1 + b2 x X3</strong></li><li>Regressão de X3 em função de X1 e X2: <strong>X3 = b1 x X1 + b2 x X2</strong></li></ol><p>Portanto, para a regressão de X1 em função de X2 e X3, precisamos estimar os betas e para isso vamos considerar a fórmula abaixo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*U9-RV6Yy1m_3XAPaelZNLQ.png" /></figure><p>O X representa a matriz das variáveis X2 e X3 e o Y é a variável X1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*jkQsScP8FDirLjLbx062aA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*tOyDT0blFU52pSRySD943g.png" /></figure><p>O produto da transposta de X e X é dado por:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*HaGyldTQrNmQ32bQBLZ-gw.png" /></figure><p>Agora, para calcular a invesa do produto acima, precisamos calcular o determinante. Vamos considerar a seguinte fórmula para o cálculo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*6-k_MA_mHnyl5ELt08F83g.png" /></figure><p>Portanto, o valor do determinante do produto de X transposta e X é 2:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*yJ4nVGdtEB7i60HPZxjpWw.png" /></figure><p>Considerando a fórmula para cálculo da inversa, concluímos que a matriz inversa do produto de X transposta e X é:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vk63rzgte1cUSdXCj8qPRw.png" /></figure><p>Finalmente, os coeficientes estimados são b1 = -1 e b2 = 1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8vxy5mZjp6SMuqpBTmRErA.png" /></figure><p>Para calcular R², precisamos calcular a <strong>Soma Total dos Quadrados</strong> (SST) dada por:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/1*fpT4ryBc6nnsFPiPjsyTIg.png" /></figure><p>A média de X1 (representada pelo y barra na fórmula acima) é dada por:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*zuVd-y7tMvsRuadJ-pAPUg.png" /></figure><p>Calculando SST:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*Um0m7bZ_Gkvp19c1B2aJjQ.png" /></figure><p>Também precisamos calcular a <strong>Soma dos Quadrados dos Erros</strong> (SSE):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/1*urDKJthWlb6NW93Jkn1NFw.png" /></figure><p>Usando os betas estimados, verificamos que os valores preditos são {1,0,1,0}, pois:</p><ul><li>-1 x 0 + 1 x 1 = 1</li><li>-1 x 1 + 1 x 1 = 0</li><li>-1 x 0 + 1 x 1 = 1</li><li>-1 x 0 + 1 x 0 = 0</li></ul><p>Portanto, SSE é:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*lIrTMj15OZ8uoJwT69vjPg.png" /></figure><p>Finalmente, o valor de R² e VIF são dados por:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*OrJZIauMfrFGYyrdFeLPiA.png" /></figure><p>Como temos uma divisão por 0 em VIF, o resultado será inf. Para os casos de X2 em função de X1 e X3 e X3 em função de X1 e X2 o resultado para VIF será o mesmo (o cálculo é realizado de forma similar).</p><h3>Tratando a Multicolinearidade</h3><p>Como a multicolinearidade pode complicar a interpretação dos modelos, ao tornar difícil separar o efeito das variáveis correlacionadas. Algumas soluções são propostas para tratá-la:</p><ol><li>Usar correlação de Pearson para remover variáveis altamente correlacionadas;</li><li>Fazer combinação linear entre as variáveis e adicionar essa nova variável ao modelo;</li><li>Usar técnicas de regularização (regressão Lasso e Ridge), as quais adicionam uma penalidade ao erro do modelo;</li></ol><p>O objetivo deste post foi explicar sobre multicolinearidade, qual o impacto dela no desenvolvimento de modelos de Regressão Linear e Logística, como identificá-la e algumas sugestões de tratamento. Abaixo seguem os materiais usados para este artigo.</p><p>Caso tenha alguma contribuição para ajudar no entendimento dos conceitos, fique à vontade para comentar.</p><p>[1] <a href="https://www.universidadedosdados.com/">https://www.universidadedosdados.com/</a></p><p>[2] <a href="https://renatabiaggi.com/eba/">https://renatabiaggi.com/eba/</a></p><p>[3] FÁVERO, L. P.; BELFIORE, P. Manual de Análise de Dados: Estatística e Modelagem Multivariada com Excel®, SPSS® e Stata®. 1. ed. Rio de Janeiro: Elsevier, 2017</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69dff24f7481" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Estatística Descritiva: Explicação intuitiva das principais métricas]]></title>
            <link>https://medium.com/@fabitortorelli/estat%C3%ADstica-descritiva-explica%C3%A7%C3%A3o-intuitiva-das-principais-m%C3%A9tricas-b82aa0d1acd2?source=rss-ffa71f50e95b------2</link>
            <guid isPermaLink="false">https://medium.com/p/b82aa0d1acd2</guid>
            <category><![CDATA[estatística-descritiva]]></category>
            <category><![CDATA[variância]]></category>
            <category><![CDATA[variance]]></category>
            <category><![CDATA[descriptive-statistics]]></category>
            <dc:creator><![CDATA[Fabiana Tortorelli]]></dc:creator>
            <pubDate>Wed, 06 Nov 2024 10:40:26 GMT</pubDate>
            <atom:updated>2024-11-06T10:40:26.905Z</atom:updated>
            <content:encoded><![CDATA[<p>Alguns conceitos importantes da estatística descritiva são: média, mediana, moda, variância, desvio padrão. Eles são fundamentais para entender como os dados são, descobrir padrões, realizar testes de hipóteses e fazer inferências.</p><p>Além disso, entender os dados permite identificar problemas como valores ausentes, outliers, e discrepâncias de escala, entre outros. Para realizar análises mais profundas (como predições e inferências), é essencial que os dados estejam preparados. A estatística descritiva fornece uma visão geral dos dados, facilitando o pré-processamento, que envolve etapas de limpeza, transformação e organização dos dados.</p><p>Neste material, explicarei os conceitos de média, mediana, moda, variância e desvio padrão de uma maneira mais intuitiva possível.</p><h4><strong>Média</strong></h4><p>A média é conhecida como uma métrica de tendência central ou de posição. Ela resume a totalidade dos dados e é definida pela soma de todos os valores da população (ou da amostra) dividida pelo número total de observações na população (ou na amostra).</p><p><strong>Média Populacional:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*vtz6s5jznisAeziomuMkbQ.png" /></figure><p><strong>Média amostral:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*UPOKPAIG8g5N2fPVTHBJlA.png" /></figure><p>Quando leio “tendência central”, imagino algo que converge para o centro, porém muitas vezes não consigo visualizar isso no conjunto de dados. Portanto, para mim é um pouco contraintuitivo.</p><p>Para ficar mais intuitivo, considere a média uma representação do centro, um ponto de equilíbrio (centro de massa) de um conjunto de dados. Desta forma, imagine uma barra contendo dois objetos que precisam estar em equilíbro. O ponto de equilíbrio é o ponto que faz com que esses objetos fiquem parados sem inclinar a barra para uma das direções:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*s9C7nOLRQ3FDKBYK1UfjNg.png" /></figure><p>Se um dos objetos pesa 4 kg e outro 10 kg por exemplo, e se o ponto de equilíbrio for exatamente ao centro da barra, o objeto maior (de 10 kg) irá inclinar a barra para sua direção. Desta forma, o ponto de equilíbrio deve ser deslocado para a direita para manter a barra em linha horizontal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*gUTy-YfP5LG1XuTDWKS9YQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*riZtmicqqdsHJIhTMhfIcQ.png" /></figure><p>Usando a analogia da barra, a média é esse ponto que mantém os valores do conjunto de dados em equilíbrio.</p><p>Considere os seguintes conjuntos de dados:</p><ol><li>{2, 4, 6, 10, 10}</li><li>{1, 2, 3, 10, 10}</li><li>{1, 1, 5, 7, 10}</li><li>{4, 4, 5, 9, 9}</li></ol><p>A média (ponto de equlibrio) dos conjuntos acima pode ser observada na imagem abaixo destacada em vermelho.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*gNpohSaiwlyzOQDpRnPAzA.png" /></figure><p>Para cada conjunto, soma da diferença entre cada valor e a média é igual a zero, dando essa ideia de equilibrio:</p><ol><li>(2–6.4) + (4–6.4) + (6–6.4) + (10–6.4) + (10–6.4) = -4.4 -2.4 -0.4 +3.6 +3.6 = 0</li><li>(1–5.2) + (2–5.2) + (3–5.2) + (10–5.2) + (10–5.2) = -4.2 -3.2 -2.2 +4.8 +4.8 = 0</li><li>(1–4.8) + (1–4.8) + (5–4.8) + (7–4.8) + (10–4.8) = -3.8 -3.8 +0.2 +2.2 +5.2 = 0</li><li>(4–6.2) + (4–6.2) + (5–6.2) + (9–6.2) + (9–6.2) = -2.2 -2.2 -1.2 +2.8 +2.8 = 0</li></ol><p>Quando temos dados <strong>simétricos</strong> e <strong>sem valores extremos</strong>, a média tende a coincidir com o centro dos dados, e a maioria dos valores fica próxima dela. No entanto, em dados <strong>assimétricos</strong> ou com valores extremos (<strong>outliers</strong>), a média pode acabar longe da maioria dos valores e não conseguimos ter essa visualização de centro.</p><p>Em dados com valores extremos, <strong>a média ainda é central</strong>, mas pode não ser uma boa representação visual do valor “típico” ou mais frequente, o que justifica o uso de outras medidas, como a <strong>mediana</strong> e a <strong>moda</strong>, para entender melhor como os dados estão distribuídos.</p><h4>Mediana</h4><p>A mediana também é uma métrica de tendência central ou posição e é mais intuitiva. Ela representa o ponto que divide os dados em duas partes iguais. Portanto, 50% destes dados tem valores menores ou iguais a esse ponto e os outros 50% tem valores maiores ou iguais que esse ponto.</p><p>Para calcular a mediana, é necessário <strong>ordenar os valores</strong> do conjunto de dados em <strong>ordem crescente</strong>.</p><ul><li>Se a quantidade de observações do conjunto de dados for <strong>ímpar</strong>, a mediana é o valor que está <strong>exatamente no meio</strong> da lista ordenada;</li><li>Se a quantidade de observações do conjunto de dados for <strong>par</strong>, a mediana é <strong>a média dos dois valores centrais</strong> da lista ordenada.</li></ul><p>Considere quatro conjuntos de dados:</p><ol><li>{4, 6, 10, 2, 10}</li><li>{4, 6, 10, 2, 100}</li><li>{1, 1, 7, 8, 5, 10}</li><li>{1, 1, 7, 8, 5, 100}</li></ol><p>Ordenando cada um em ordem crescente, podemos ver que a mediana de cada conjunto é 6, mesmo para os conjuntos que possuem valores extremos (conjuntos 2 e 4).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*gLS6vgrA3qdcRLEkPL84gQ.png" /></figure><p>Considerando os dados acima e visualizando a média, percebemos que para os conjuntos com valores extremos, a média fica bem distante da mediana. Isso reforça ainda mais a importância de usar mais de uma métrica para avaliar os dados.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*mgfG13D5o5_Bdm4TqUHv2A.png" /></figure><h4>Moda</h4><p>A moda, ainda sendo uma medida de tendência central, ela representa o valor mais frequente. Dependendo da frequência, os dados podem ser:</p><ul><li><strong>Amodal</strong>: Quando não há moda, ou seja, nenhum valor se repete</li><li><strong>Unimodal</strong>: Quando existe uma única moda, ou seja, um valor aparece com maior frequência do que todos os outros</li><li><strong>Bimodal</strong>: Quando existem duas modas, ou seja, dois valores aparecem com mais frequência</li><li><strong>Multimodal</strong>: Quando existem três ou mais valores que aparecem com a mais frequência</li></ul><p>Considerando os exemplos acima temos:</p><ol><li>O conjunto {4, 6, 10, 2, 10} é unimodal. O valor que aparece com mais frequência é o 10</li><li>O conjunto {4, 6, 10, 2, 100} é amodal, pois nenhum valor se repete</li><li>O conjunto {1, 1, 7, 8, 5, 10} é unimodal. O valor que aparece com mais frequência é o 1</li><li>O conjunto {1, 1, 7, 8, 5, 100} é unimodal. O valor que aparece com mais frequência é o 1</li></ol><h4>Variância</h4><p>A variância é um medida de dispersão, que mede a<strong> variação</strong> dos valores em torno da média. Ela informa o quão longe os valores do conjunto de dados estão da média. Se a variância é zero, todos os valores são exatamente iguais à média, indicando ausência de dispersão. Por outro lado, quanto maior for a variância, mais espalhados estão os dados em torno da média, o que indica maior diversidade ou variabilidade no conjunto.</p><p>Pelo desenho abaixo, temos uma amostra com cinco observações, X1, X2, X3, X4 e X5. A variância é a medida que quantifica o quanto essas observações estão distantes da média amostral. Ela está relacionada com a distância entre os pontos da amostra e a média.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*gC70MbCZG33jYV7hLZRT8w.png" /></figure><p>Considere os seguintes conjuntos de dados:</p><ol><li>{5, 6, 6, 7, 8}</li><li>{2, 4, 6, 10, 10}</li></ol><p>A média do primeiro é 6.4 (5 + 6 + 6 + 7 + 8 = 32 dividido por 5) e a do segundo também é 6.4 (2 + 4 + 6 + 10 + 10 = 32 dividido por 5). Porém, ao plotar as observações e a média em uma linha reta (imagem abaixo), podemos ver que as observações do primeiro conjunto estão mais próximas da média e as do segundo estão mais dispersas da média.</p><p><strong>Distância dos pontos até a média para conjunto um:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*20upsvh-TZR_eg-VgCJ0iw.png" /></figure><p><strong>Distância dos pontos até a média para conjunto dois:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2rJctFwKideznislmEzbwQ.png" /></figure><p>Quando calculamos a média dos dados, estamos avaliando o ponto de equilíbrio deles como um todo e pela definição da média, ao calcularmos a diferença entre cada observação e a média e depois somar cada diferença (a diferença também conhecida como <strong>desvio</strong>), essa soma será zero. Para obter o valor da dispersão, cada desvio é elevado ao quadrado garantindo uma soma maior que zero. Além disso, como queremos avaliar a variabilidade dos dados como um todo, dividimos a soma dos desvios ao quadrado pelo número total de observações.</p><p>Um <strong>ponto de atenção</strong> é que a definição para a dispersão descrita acima é usada quando temos informações da população, ou seja, quando conhecemos a média populacional.</p><p><strong>Fórmula da Variância Populacional:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*ilxLmaTjRnkGcY95265J9Q.png" /></figure><p>Porém, muitas vezes ou quase sempre, nós não temos informação da média populacional, e então usamos a média amostral como uma estimativa para a mesma e a partir dela realizamos a estimativa da variância populacional. Desta forma, para o cálculo da variância, além de usarmos a média da amostra, dividimos a soma dos desvios ao quadrado por <em>n</em>-1 observações, onde <em>n</em> é o tamanho da amostra.</p><p><strong>Fórmula da Variância Amostral:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*OkThygtyvydNYerRvxbn8Q.png" /></figure><p><strong>Mas por que <em>n</em>-1?</strong></p><p>Para ilustrar o motivo de usar <em>n</em>-1 e não <em>n</em> na fórmula da variância amostral, imagine que temos uma população qualquer (os pontos em azul abaixo) com média <strong>μ </strong>(em vermelho), conforme a figura.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*6m1GdnQ0YS7jjHdYuwCWfA.png" /></figure><p>Agora vamos selecionar uma amostra de tamanho três desta população (pontos em verde). Pela imagem, conseguimos observar que a média dessa amostra está mais ou menos próxima da média populacional.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*xV5MBZ_biLmfYln5_Lroig.png" /></figure><p>Porém, pode ser que a amostra de tamanho três que selecionamos contenha os valores próximos dos valores mínimos da população, conforme imagem abaixo. Nesta situação, verificamos que a média amostral está bem distante da média populacional.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*CdOvtxOhTDGR_Q2uJUugfQ.png" /></figure><p>Portanto, ao calcular as distâncias entre cada ponto da amostra e a média amostral e então somar estas distâncias (desvios) elevadas ao quadrado e dividir o total pelo número da amostra (no caso três), teremos uma estimativa da variância bem distante da verdadeira variância.</p><p>Além disso, como não temos informações de toda a população, usamos a média amostral para estimar a variância populacional e ao dividir a soma dos quadrados dos desvios por <em>n</em>, temos uma subestimação da variância populacional.</p><p>Para entender melhor, considere uma população de apenas cinco observações conforme abaixo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*O9caL639fP4QHISBjGGsyw.png" /></figure><p>Vamos selecionar uma amostra de tamanho dois a partir desta população (pontos em verde). A média dessa amostra está destacada em roxo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*LWYyd_NyhFnG5xNi-HCEdg.png" /></figure><p>Para cada ponto, podemos escrever o quadrado da diferença entre seu valor e a média populacional em função da média amostral.</p><p><strong>Desvio ao quadrado do ponto X1 até média populacional:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*584XvQaZF_4dcsiL16cRJw.png" /></figure><p><strong>Desvio ao quadrado do ponto X2 até média populacional:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*BPremJBeGYtSgMUgusPE-g.png" /></figure><p>Colocando todos os desvios em uma imagem temos o seguinte:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*OIu9u2blY-su0PqsAte8nA.png" /></figure><p>Para obter a variância precisamos calcular a soma dos desvios ao quadrado. Pela imagem acima, podemos escrever matematicamente essa soma de acordo com o cálculo abaixo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZWBv8kTRFz43vCViZiJCwQ.png" /></figure><p>Desta forma, podemos ver que a soma dos desvios ao quadrado dividido pelo total de observação considerando a média populacional será sempre maior que a soma dos desvios ao quadrado dividido pelo total de observação considerando a média amostral.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*Gghqi6mBT74EoIQT1F54Gg.png" /></figure><p>Portanto, se considerarmos todas as observações da amostra para estimar a variância populacional a partir da média amostral (usando <em>n</em> e não <em>n</em>-1), estaremos subestimando essa variância. Isso significa que este estimador é enviesado.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*Ca3AUrfRtTJl9hvtRYciHQ.png" /></figure><p>A prova formal da expressão acima pode ser consultada na referência [5]. Para garantir um estimador não enviesado, usamos a fórmula da variância amostral (S²) definida anteriormente, a qual considera <em>n</em> − 1 em vez de <em>n </em>(<strong>correção de Bessel — referência [7]</strong>).</p><h4>Desvio Padrão</h4><p>O desvio padrão também é uma medida de dispersão e ele é definido como a raíz quadrada da variância. Como temos a variância populacional e amostral, também temos desvio padrão populacional e amostral.</p><p><strong>Desvio padrão populacional:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*DD8tYfP2KANon4XAx90Igg.png" /></figure><p><strong>Desvio padrão amostral:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*mjAgq32ervWQ4oqmkMr7jQ.png" /></figure><p>Como tomamos a raiz quadrada da variância, o desvio padrão tem a mesma escala da média. Por exemplo, se minha amostra está relacionada com tamanho de pessoas em metros, então tanto a média quanto o desvio padrão terão escala em metros. Desta forma é mais fácil visualizar os dados considerando tanto a média quanto o desvio padrão.</p><p>Considerando os conjuntos de dados:</p><ol><li>{5, 6, 6, 7, 8}</li><li>{2, 4, 6, 10, 10}</li></ol><p>Temos que o desvio padrão para o conjunto um é 1.14 enquanto para o segundo é 3.58. Isso significa que os dados do conjunto um estão mais próximos da média e os dados do conjunto dois estão mais afastados.</p><p><strong>Conjunto um:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*EMFy8BWkTXypbTKNJd0nAA.png" /></figure><p><strong>Conjunto dois:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*80Gc3_ZwLC50ERSz6oU1FA.png" /></figure><p>O objetivo deste material foi passar uma forma intuitiva das principais métricas envolvidas na estatística descritiva. Os materiais abaixo foram relevantes para a construção deste.</p><p>Caso tenha alguma contribuição para ajudar no entendimento dos conceitos, fique à vontade para comentar.</p><p>[1] <a href="https://blog.proffernandamaciel.com.br/medidas-de-tendencia-central/">https://blog.proffernandamaciel.com.br/medidas-de-tendencia-central/</a></p><p>[2] <a href="https://blog.proffernandamaciel.com.br/medidas_dispersao/">https://blog.proffernandamaciel.com.br/medidas_dispersao/</a></p><p>[3] <a href="https://www.youtube.com/watch?v=bVB4X5CUWTg">https://www.youtube.com/watch?v=bVB4X5CUWTg</a></p><p>[4] <a href="https://www.youtube.com/watch?v=_sdNwY0KKUA">https://www.youtube.com/watch?v=_sdNwY0KKUA</a></p><p>[5] <a href="https://en.wikipedia.org/wiki/Bias_of_an_estimator">https://en.wikipedia.org/wiki/Bias_of_an_estimator</a></p><p>[6] <a href="https://www.youtube.com/watch?v=KkaU2ur3Ymw">https://www.youtube.com/watch?v=KkaU2ur3Ymw</a></p><p>[7] <a href="https://en.wikipedia.org/wiki/Bessel%27s_correction">https://en.wikipedia.org/wiki/Bessel%27s_correction</a></p><p>[8] <a href="https://www.universidadedosdados.com/">https://www.universidadedosdados.com/</a></p><p>[9] <a href="https://renatabiaggi.com/eba/">https://renatabiaggi.com/eba/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b82aa0d1acd2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Do Teorema Central do Limite aos Testes de Hipóteses]]></title>
            <link>https://medium.com/@fabitortorelli/do-teorema-central-do-limite-aos-testes-de-hip%C3%B3teses-a49a8a0b7bf7?source=rss-ffa71f50e95b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a49a8a0b7bf7</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[hypothesis-testing]]></category>
            <category><![CDATA[teorema-central-do-limite]]></category>
            <category><![CDATA[teste-de-hipótese]]></category>
            <category><![CDATA[central-limit-theorem]]></category>
            <dc:creator><![CDATA[Fabiana Tortorelli]]></dc:creator>
            <pubDate>Thu, 31 Oct 2024 14:09:15 GMT</pubDate>
            <atom:updated>2024-11-04T20:50:32.956Z</atom:updated>
            <content:encoded><![CDATA[<h4>Teorema Central do Limite</h4><p>O <strong>Teorema Central do Limite</strong> define que, para um número suficientemente grande de amostras de uma distribuição populacional tendo média μ e desvio padrão finito σ, a distribuição amostral das amostras é aproximadamente uma distribuição normal com média μ e variância reduzida σ²/n. Essa definição vale para população que não seja normalmente distribuída.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Av7n9wVP1pSGMRU9RGIqrw.png" /></figure><p>Considere um exemplo hipotético de duas populações, uma de salários de pessoas do gênero feminino e outra de salários de pessoas do gênero masculino e ainda:</p><p><strong>Para o grupo do gênero feminino</strong>:</p><ul><li>A média do salário é μf=100</li><li>A variância do salário é σ²f=50</li></ul><p><strong>Para o grupo do gênero masculino</strong>:</p><ul><li>A média do salário é μm=200</li><li>A variância do salário é σ²m=70</li></ul><p>Segundo Teorema Central do Limite:</p><ol><li>Se pegarmos n amostras independentes do grupo feminino e calcular a média de salário para cada amostra, a distribuição da média das amostras se aproxima de uma normal com média igual a μ=100 e variância σ²=50/n.</li><li>Se pegarmos n amostras independentes do grupo masculino e calcular a média de salário para cada amostra, a distribuição da média das amostras se aproxima de uma normal com média igual a μ=200 e variância σ²=70/n.</li></ol><p>Assim, ao aumentar o tamanho da amostra n, a variabilidade das médias amostrais de cada grupo diminuirá, permitindo uma aproximação mais precisa das médias populacionais de 100 e 200, respectivamente.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sqY4r7az4bNgiI8GgujkVQ.png" /></figure><p>Importante destacar que o teorema mostra que a <strong>distribuição amostral das médias será aproximadamente normal </strong>ao retirarmos amostras suficientemente grandes (<strong>n≥30</strong>) da população de origem.</p><h4>Teorema Central do Limite e Testes de Hipóteses</h4><p>Em geral, temos interesse em fazer inferências sobre um parâmetro da população (média, variância, proporção, etc) e sabemos que para obter informações de toda a população envolve custo e tempo, portanto é usado amostras para fazer inferências sobre os parâmetros.</p><p>Como a <strong>distribuição amostral das médias é aproximadamente normal</strong> pelo Teorema Central do Limite, é possível estimar os parâmetros da população, por meio de intervalos de confiança e testes de hipóteses baseados nas estatísticas amostrais.</p><p>Voltando para a população de salários do grupo Feminino e Masculino, quando nós realizamos um teste de hipótese para avaliar se há uma diferença significativa entre as médias salariais dos dois grupos, estamos essencialmente:</p><ul><li><strong>Avaliando a diferença entre as médias</strong> dessas duas populações, com base em amostras obtidas de cada grupo</li><li><strong>Testando se a diferença observada nas médias amostrais</strong> é grande o suficiente para sugerir que μf≠μm</li></ul><p>Mesmo que a distribuição de salários individuais de cada grupo não seja normal, o Teorema Central do Limite nos permite supor que a distribuição das médias amostrais de salários para o grupo feminino e para o grupo masculino tenderá a ser normal se o tamanho das amostras for grande o suficiente, conforme exemplificado acima.</p><h4>Teste de Hipótese</h4><p>Para testar se a diferença das médias é significativa, utilizamos as médias amostrais de cada grupo e calculamos a estatística de teste (como o valor de t, por exemplo) para verificar se essa diferença observada entre as médias das amostras reflete uma verdadeira diferença entre as médias das populações ou se essa diferença é devida ao acaso, ou seja, poderia mudar se novas amostras fossem coletadas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*6d6E0hEQJecHpCLEiu9ZNQ.png" /></figure><p>Se você tiver alguma sugestão valiosa para o material, fique à vontade para comentar. Abaixo estão listados os materiais que usei para os estudos.</p><p>[1] Agresti, A., &amp; Kateri, M. (2021). Foundations of Statistics for Data Scientists: With R and Python (1st ed.). Chapman and Hall/CRC. <a href="https://doi.org/10.1201/9781003159834">https://doi.org/10.1201/9781003159834</a></p><p>[2] <a href="https://blog.proffernandamaciel.com.br/teorema_central_limite/">https://blog.proffernandamaciel.com.br/teorema_central_limite/</a></p><p>[3] <a href="https://medium.com/data-hackers/desvendando-o-teorema-central-do-limite-17cbb13beb1a">https://medium.com/data-hackers/desvendando-o-teorema-central-do-limite-17cbb13beb1a</a></p><p>[4] <a href="https://renatabiaggi.com/eba/">https://renatabiaggi.com/eba/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a49a8a0b7bf7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ROC Curve, Gini index, and KS statistic]]></title>
            <link>https://medium.com/@fabitortorelli/roc-curve-gini-index-and-ks-statistic-6ba1e986742b?source=rss-ffa71f50e95b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ba1e986742b</guid>
            <category><![CDATA[statitics]]></category>
            <category><![CDATA[metrics]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[roc]]></category>
            <category><![CDATA[gini-index]]></category>
            <dc:creator><![CDATA[Fabiana Tortorelli]]></dc:creator>
            <pubDate>Mon, 28 Oct 2024 10:49:37 GMT</pubDate>
            <atom:updated>2024-10-28T10:49:37.237Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*9iptE69YEFRK_RdNQD646g.png" /></figure><p>Various approaches can be used to illustrate the performance of a binary classifier model. Here, I will explain the following:</p><ul><li><strong>Receiver-operating characteristic curve</strong></li><li><strong>Gini index</strong></li><li><strong>KS statistic</strong></li></ul><p>First, consider the following hypothetical dataset containing 8 observations and three features. The ‘Id’ feature represents a unique identifier, the ‘Education’ feature is an independent variable with two categories: ‘Higher education’ and ‘Not Higher education,’ and the ‘Target’ feature indicates whether the borrower is good (1) or bad (0):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*UZTp3nnkRaCm3yLTg_A2Jg.png" /></figure><p>To develop a Logistic Regression model based on the historical data above, we need to find a curve that best explains the observations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*UqBVcycleQZTsagcPOa47Q.png" /></figure><p>In my about the Maximum Likelihood Estimation for Logistic Regression, I explained how to estimate the parameters of a Logistic Regression model for the dataset used here. The predicted probability of being a good borrower is shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*424Zu7q07LTLn2pNBSUmiQ.png" /></figure><h3>Receiver-operating characteristic curve</h3><p>The model provides the probability of being a good borrower, so we need to transform it into a classification. To do this, we define a specific threshold (cutoff). If the probability for an observation is greater than the threshold, we classify it as good (1); otherwise, we classify it as bad (0). For example:</p><ol><li>If we set the <strong>threshold at 0.2</strong>, all observations will be classified as good, since the minimum probability in the dataset is 0.25, which is higher than 0.2:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*J5nCtaAzJKcg3rhzPS58WQ.png" /></figure><p>We can use the confusion matrix to visualize and summarize the performance of a classification model. With the threshold mentioned above, we see that four good observations were correctly classified as good (True Positives — denoted in green), while four bad observations were incorrectly classified as good (False Positives — denoted in grey):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*SjpqBGHFoUDqhZDL7xj73w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*jmVlt0isiSTPkWJ6-XSjeA.png" /></figure><p>2. If we set the<strong> threshold at 0.5</strong>, observations 1, 2, 5, and 8 will be classified as good, while observations 3, 4, 6, and 7 will be classified as bad:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*N58yn-kDIr4rsrfkpG4V4Q.png" /></figure><p>From the confusion matrix, we see that three good observations were correctly classified as good (True Positives — denoted in green), and one bad observation was incorrectly classified as good (False Positive — denoted in grey). Additionally, one good observation was incorrectly classified as bad (False Negative — denoted in grey), and three bad observations were correctly classified as bad (True Negatives — denoted in red):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*eVNk3FJgbs8d2_fcoSa_lw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*xkO-uMgSVJUvGHW4Ie3TPg.png" /></figure><p>3. If we set the <strong>threshold at 0.9</strong>, all observations will be classified as bad, since the highest probability in the dataset is 0.75:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*if3dgcb2FqlzIzyijLI1uw.png" /></figure><p>From the confusion matrix, we see that no observations were classified as good (both True Positives and False Positives are zero). Additionally, four good observations were incorrectly classified as bad (False Negatives — denoted in grey), while four bad observations were correctly classified as bad (True Negatives — denoted in red):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*yUCfjKcYnJOza8GtZidWzQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*SHotpngSTxzRsOxOpg9OPA.png" /></figure><p>The Receiver Operating Characteristic (ROC) curve summarizes all the information and helps identify the best cutoff. It is defined by plotting the true positive rate (TPR, or sensitivity) against the false positive rate (FPR, or 1-specificity) at each threshold setting:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*itrGq_uHc-2csyizR_tezg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*7asgRmyPkYSdmbnq7ygBOQ.png" /></figure><p>With a threshold of 0.9, the sensitivity is 0, meaning that the model incorrectly classifies 100% of good observations while correctly classifying 100% of bad observations. In contrast, with a threshold of 0.2, the model correctly classifies 100% of good observations but incorrectly classifies 100% of bad observations.</p><p>The area under the ROC curve (AUC) quantifies the model’s performance in correctly separating the two classes (for example, ‘default’ and ‘non-default’). In our example, the AUC is 75%, meaning that in 75% of cases, the model correctly classifies a positive instance (the good class).</p><p>AUC is also useful for comparing different classifiers. For example, between Logistic Regression and Random Forest models, the one with the greatest area under the ROC curve is considered the better model.</p><h3>Gini index</h3><p>The Gini index is another metric used to evaluate model performance. It is commonly applied in credit score models and measures the effectiveness of discriminating between good and bad observations. The Gini index can be defined based on the area under the ROC curve (AUC):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*HeE9gICytTcKOgbI2bBTVg.png" /></figure><p>The maximum value for AUC is 1, and the minimum is 0.5. Therefore, the Gini index ranges from 0 (Gini = 2 * 0.5–1 = 0) to 1 (Gini = 2 * 1–1 = 1). Since the Gini index uses AUC in its calculation, the interpretation is similar: values close to 1 indicate good performance. However, the Gini index may be easier to explain, as its minimum value is 0, whereas AUC has a minimum of 0.5.</p><p>In our example, the Gini index is 0.5 (2 * 0.75–1), indicating that the model has moderate discrimination power.</p><h3>KS Statistic</h3><p>The Kolmogorov-Smirnov (KS) statistic measures the ability of a model to distinguish between two groups (for example, good — not default and bad — default). If more bad observations have lower probabilities and more good observations have higher probabilities, then the model is effectively predicting outcomes.</p><p>To calculate the KS statistic, let’s sort the ‘Predict’ column from the example above and compute the cumulative distribution of the total population, as well as the cumulative distributions for good and bad observations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*XW3PnLBF63T2t19dKamd4w.png" /></figure><p>Next, we calculate the percentages for the three columns:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kidzvct6F_n6EW55f6k2tQ.png" /></figure><p>If we plot the estimated probability of being a good observation against the cumulative percentages of good and bad observations, we obtain the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*jdc-kNTtFZ75yq8lXJwBzw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*iVia0XaiA1B5DoNF8-BBlg.png" /></figure><p>Finally, we calculate the difference between the cumulative percentage of good observations and the cumulative percentage of bad observations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ItabP5TKZfwi0vHsWNF7Xg.png" /></figure><p>This maximum difference represents the KS statistic. Therefore, our KS value is 0.75:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*PVdc6SXJl8ZJF0OKOlm3_g.png" /></figure><p>The KS statistic ranges from 0 to 1, where 0 indicates no ability to distinguish between good and bad observations, and 1 indicates perfect prediction.</p><p>I welcome any feedback or suggestions on my approach. To support my studies, I utilized the following materials:</p><p>[1] <a href="https://www.youtube.com/watch?v=4jRBRDbJemM">https://www.youtube.com/watch?v=4jRBRDbJemM</a></p><p>[2] <a href="https://medium.com/@kstarun/model-evaluation-metrics-gini-coefficient-db919ed09306">https://medium.com/@kstarun/model-evaluation-metrics-gini-coefficient-db919ed09306</a></p><p>[3] <a href="https://towardsdatascience.com/using-the-gini-coefficient-to-evaluate-the-performance-of-credit-score-models-59fe13ef420">https://towardsdatascience.com/using-the-gini-coefficient-to-evaluate-the-performance-of-credit-score-models-59fe13ef420</a></p><p>[4] <a href="https://www.experian.com/blogs/business-information/2020/11/18/understand-and-use-a-business-credit-risk-score-5-minute-fundamentals/">https://www.experian.com/blogs/business-information/2020/11/18/understand-and-use-a-business-credit-risk-score-5-minute-fundamentals/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ba1e986742b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Maximum Likelihood Estimation for Logistic Regression]]></title>
            <link>https://medium.com/@fabitortorelli/maximum-likelihood-estimation-for-logistic-regression-9449c8312afe?source=rss-ffa71f50e95b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9449c8312afe</guid>
            <category><![CDATA[maximum-likelihood]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[Fabiana Tortorelli]]></dc:creator>
            <pubDate>Sun, 20 Oct 2024 19:38:07 GMT</pubDate>
            <atom:updated>2024-10-20T19:38:07.297Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*uuOeGfi5lMDnrcqfi2ZxJA.png" /></figure><p>Sometimes in predictive analysis, the outcome is not a quantitative value, like house price, graduate grade, or income, but rather a binary variable, such as dead or alive, default or no default, and so on. In such cases, Logistic Regression is a statistical model used to predict the probability of success based on an independent variable X. Success is typically represented by 1, and failure (or non-success) by 0. For example, in healthcare, an observation like ‘alive’ may be represented as 1, while ‘dead’ is represented as 0 in the dataset.</p><p>In this work, I will walk through key concepts related to Logistic Regression, explaining the underlying mathematics for Maximum Likelihood Estimation using a hypothetical example. This will cover:</p><ul><li><strong>Logistic Regression Model</strong></li><li><strong>Likelihood and Log-Likelihood Function</strong></li><li><strong>Parameter Estimation</strong></li><li><strong>Hypothetical Example</strong></li></ul><h3>Logistic Regression Model</h3><p>The logistic regression model can be defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*sMYJYTUBD6RX5-CnFcbQWA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rNXLrzLc8f7iYSOia-Fvbw.png" /></figure><p>In general, Odds are used instead of probability because they provide a better understanding of the relationship between the outcomes and the independent variables. By manipulating Equation (1), we obtain the log of the Odds, which represents a linear relationship:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fOLjW881A_e-7uLtIui-9w.png" /></figure><h3><strong>Likelihood and Log-Likelihood Function</strong></h3><p>The coefficients β0 and β1​ in Equation (2) are unknown and need to be estimated. To estimate them, we use the method of maximum likelihood, which involves finding the parameter values that maximize the probability of the observed data.</p><p>For example, if we are modeling default in a credit loan scenario, for an observation classified as ‘bad’ (defaulted), the maximum likelihood estimation identifies the distribution that maximizes the probability of observing this outcome. Given multiple possible curves, we aim to find the one most likely to have generated the observed data points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*IjWL7yknyRYkETjd9fKeCw.png" /></figure><p>Therefore, given a sample of n observations, the likelihood function L can be expressed as the joint probability distribution of all the observations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*IX-unh00ZFXZDXgEgOMoDw.png" /></figure><p>By taking the logarithm of the likelihood function, we obtain the log-likelihood function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*BDdp5LGVsLZW9AIHDqqOJw.png" /></figure><p>By manipulating the Equation above, we obtain:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*HqrEHHNqQDn4f6przghGiA.png" /></figure><h3>Parameter Estimation</h3><p>To find the best parameter values, we use differentiation, a technique that helps identify the maximum (and minimum) points of functions. This process involves solving the following system of Equations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Va-MN7HIi5KdgNwcTxcStw.png" /></figure><p>Let’s detail the left part of Equation (6):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L6uzP17H-Ommzj6vaJ9SqA.png" /></figure><p>Similarly, for the left part of Equation (7), we have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*v5pH13uJmlIi9o8-5lKGiQ.png" /></figure><h3>Practical Example</h3><p>Consider the hypothetical example of a credit loan below, which is a historical dataset containing 8 observations and three features: <strong>Id</strong>, <strong>Education</strong>, and <strong>Target</strong>. The Id feature serves as a unique identifier, the Education feature is our independent variable and includes two categories: ‘Higher education’ and ‘Not Higher education.’ The Target feature represents our outcome, where the values 1 and 0 indicate that the person did not default (good) and defaulted (bad), respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*YBmxE85xSPFy1ipvoj1Rxw.png" /></figure><p>To develop a predictive model based on the given historical information, we will perform Logistic Regression. First, we need to transform the Education feature into a dummy variable; for observations with ‘Higher education,’ we assign a value of 1, and 0 otherwise. We will create a new variable called ‘Education:Higher education’ to store these values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*uv-0sCYPwIZgVRKgmIG_DQ.png" /></figure><p>For each observation, we have:</p><ul><li>i = 1, Xi = Higher Education (1), Yi = 1</li><li>i = 2, Xi = Higher Education (1), Yi = 1</li><li>i = 3, Xi = Not Higher Education (0), Yi = 0</li><li>i = 4, Xi = Not Higher Education (0), Yi = 0</li><li>i = 5, Xi = Higher Education (1), Yi = 0</li><li>i = 6, Xi = Not Higher Education (0), Yi = 0</li><li>i = 7, Xi = Not Higher Education (0), Yi = 1</li><li>i = 8, Xi = Higher Education (1), Yi = 1</li></ul><p>Considering Equation (9) we have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*ynJZf_AT9untKzPx-F2V4A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/919/1*C0c1Go3XsDyjtdGFHCdLWQ.png" /></figure><p>From (7) we obtain:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*VssVAirhG46JFoJHTh2JbQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*dhalpaYmY1KldexzqJIcqg.png" /></figure><p>Now, considering the Equation (8) we have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*2ac-hu57uuEm27d4lmBF1g.png" /></figure><p>And from (6):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*vNBdNJ4q_N1fQgL1kK2saQ.png" /></figure><p>Replacing (10) into the Equation above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*6_Hc2j5CUooKw4qkbWrz0g.png" /></figure><p>We found that the optimal value for β0 is -1.09:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*bGO-33XG-wuWLJCZgEdOPA.png" /></figure><p>By replacing β0=−1.09 into Equation (10), we find that the optimal value for β1 is 2.19:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*IMpx8w7QJmHDzJGAhmhVAA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*pHY7TkRuk-l8OQCIxvKe_g.png" /></figure><p>Therefore, definition (1) can be expressed as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*o5G-LCeLskUvXap6oiN_2g.png" /></figure><p>Using data that we used to estimate the parameters, the probability of being classified as ‘good’ for each observation is the following:</p><ul><li>i = 1, Xi = Higher Education (1), Yi = 1</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*GET7O8XHMoouuTNsR7u6xA.png" /></figure><ul><li>i = 2, Xi = Higher Education (1), Yi = 1</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*GET7O8XHMoouuTNsR7u6xA.png" /></figure><ul><li>i = 3, Xi = Not Higher Education (0), Yi = 0</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*ELlzgStb7bi06RKnH3Q0kw.png" /></figure><ul><li>i = 4, Xi = Not Higher Education (0), Yi = 0</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*ELlzgStb7bi06RKnH3Q0kw.png" /></figure><ul><li>i = 5, Xi = Higher Education (1), Yi = 0</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*GET7O8XHMoouuTNsR7u6xA.png" /></figure><ul><li>i = 6, Xi = Not Higher Education (0), Yi = 0</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*ELlzgStb7bi06RKnH3Q0kw.png" /></figure><ul><li>i = 7, Xi = Not Higher Education (0), Yi = 1</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*ELlzgStb7bi06RKnH3Q0kw.png" /></figure><ul><li>i = 8, Xi = Higher Education (1), Yi = 1</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*GET7O8XHMoouuTNsR7u6xA.png" /></figure><h3>Conclusion</h3><p>This serves as an example to illustrate the maximum likelihood estimation for Logistic Regression. I welcome any feedback or suggestions on my approach.</p><p>To support my studies, I utilized the following materials:</p><ul><li><a href="https://towardsdatascience.com/probability-concepts-explained-maximum-likelihood-estimation-c7b4342fdbb1">https://towardsdatascience.com/probability-concepts-explained-maximum-likelihood-estimation-c7b4342fdbb1</a></li><li><a href="https://www.youtube.com/watch?v=4KKV9yZCoM4">https://www.youtube.com/watch?v=4KKV9yZCoM4</a></li><li><a href="https://www.youtube.com/watch?v=Dn6b9fCIUpM">https://www.youtube.com/watch?v=Dn6b9fCIUpM</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9449c8312afe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Weight of Evidence (WoE) Explained]]></title>
            <link>https://medium.com/@fabitortorelli/weight-of-evidence-woe-explained-721f213a97d3?source=rss-ffa71f50e95b------2</link>
            <guid isPermaLink="false">https://medium.com/p/721f213a97d3</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[credit-risk]]></category>
            <category><![CDATA[weight-of-evidence]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <dc:creator><![CDATA[Fabiana Tortorelli]]></dc:creator>
            <pubDate>Mon, 14 Oct 2024 09:01:40 GMT</pubDate>
            <atom:updated>2024-10-14T09:01:40.642Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*pi3SBiUuiSce2E30iTg1Mw.png" /></figure><p>Weight of Evidence (WoE) is a method to measure the power of an independent feature to discriminate two events/groups. It is commonly applied in classification analysis, outlier/missing value processing, and the transformation of categorical and numeric data.</p><p>For example, in credit risk analysis, the goal is to determine whether a borrower will default at some point. This is done by studying the borrower’s probability of default, based on historical information about good and bad borrowers. In this analysis, the outcome is a binary variable, where, 1 represents good borrowers and 0 represents bad borrowers.</p><p>WoE helps measure the predictive power of a feature in distinguishing between good and bad outcomes. To illustrate this with a hypothetical example, let’s consider a dataset with 8 observations and a target feature called ‘Target,’ where 1 corresponds to good borrowers and 0 to bad ones. The independent feature is ‘Education,’ which contains two categories: ‘Higher education’ and ‘Not Higher education’:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*2T3lLFVEWuPV_ZbXPk2zDg.png" /></figure><p>If we summarize the information above in a table, we get the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gQIyvlrsc5mqAO8oC2taEg.png" /></figure><p>The table shows that for the ‘Higher education’ category, there are 3 good observations and 1 bad observation, resulting in proportions of 0.75 and 0.25, respectively. Conversely, for the ‘Not Higher education’ category, there is 1 good observation (proportion 0.25) and 3 bad observations (proportion 0.75). If we take a closer look at the proportions for each category, we have the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*-3iQeMsz0A24DCZTRC3Kbw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*jq0fxd5NVvpv1bsEw03PZw.png" /></figure><p>This means that, for the ‘Higher education’ category, for each 1 bad observation, there are 3 good observations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*ee2ZvH7F3GafqcF-YvLLVw.png" /></figure><p>And for the ‘Not Higher education’ category, for each 1 bad observation, there are 0.33 good observations, meaning there are 3 bad observations for each 1 good observation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*FDH7a4g63hTErm1EJKCZLg.png" /></figure><p>Now, the WoE is calculated as the natural logarithm of the ratio between the ‘percentage of good’ and the ‘percentage of bad’:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xf2I7bjL32nWCPej25Kg5Q.png" /></figure><p>The <strong>natural logarithm (ln) </strong>graph can be represented as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*VBFdSTVgvi2bEqeRNd9VEg.png" /></figure><p>Therefore, the Weight of Evidence for each category is calculated, and we can check it here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c-P1AcmJ3Mfx5nhKTaXIeg.png" /></figure><p>The table shows that for the ‘Higher education’ category, the WoE is 1.09. This indicates that, since the WoE is greater than 0, the proportion of good observations relative to the proportion of bad observations is greater than 1. Thus, we have more good than bad in this category, meaning that individuals with ‘Higher education’ are generally more reliable for a credit loan:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*Ly_oFgfya6vDqPFBejL_fg.png" /></figure><p>Now, for the ‘Not Higher education’ category, the WoE is -1.09. This indicates that, since the WoE is less than 0, the proportion of good observations relative to the proportion of bad observations is less than 1. Therefore, there are more bad than good observations in this category, meaning that individuals with ‘Not Higher education’ are generally considered more risky for a credit loan:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*UtGIea97xg-W2s27ONQZCg.png" /></figure><p>If the WoE is 0, this indicates that the proportion of good observations relative to the proportion of bad observations is equal to 1, meaning that the number of good observations is equal to the number of bad observations in that category:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*QgmmiOlBnZTO0144--XIWQ.png" /></figure><p>WoE can also be applied to numeric features, but it is necessary to transform them into bins beforehand, using techniques such as Fine Classing. After this transformation, it is possible to analyze which range/bins are better to separate the groups.</p><p>Furthermore, the Weight of Evidence is a component of the Information Value (IV) measure, which is used to quantify the predictive power of a variable:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HnE-BfgaegPtWEeA5N8qjg.png" /></figure><p>In our example, the IV indicates that the predictive power of the ‘Education’ variable is either suspicious or too good to be true, as its value is 1.09.</p><p>This serves as an example to illustrate the Weight of Evidence. I welcome any feedback or suggestions on my approach. To support my studies, I utilized the following course materials and documentation:</p><ul><li><a href="https://www.udemy.com/course/credit-risk-modeling-in-python/learn/lecture/15585764?start=450#overview">https://www.udemy.com/course/credit-risk-modeling-in-python/learn/lecture/15585764?start=450#overview</a></li><li><a href="https://www.listendata.com/2015/03/weight-of-evidence-woe-and-information.html">https://www.listendata.com/2015/03/weight-of-evidence-woe-and-information.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=721f213a97d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Git: Understanding the Basics]]></title>
            <link>https://medium.com/@fabitortorelli/introduction-to-git-understanding-the-basics-d5f9d7dcbb7a?source=rss-ffa71f50e95b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5f9d7dcbb7a</guid>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Fabiana Tortorelli]]></dc:creator>
            <pubDate>Tue, 03 Sep 2024 06:26:04 GMT</pubDate>
            <atom:updated>2024-09-03T06:26:04.787Z</atom:updated>
            <content:encoded><![CDATA[<p>Git is a technology that helps version code without changing the original, allowing multiple people to work on changes simultaneously.</p><p>It has three main states that your files can occupy:</p><ul><li><strong>Modified:</strong> when you have changed the file but have not committed it</li><li><strong>Staged: </strong>when you add the changes</li><li><strong>Committed: </strong>when you confirm (commit) the changes</li></ul><p>Also, Git has three main sections:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/0*XuTJGDsD8S7VwiXo" /><figcaption><a href="https://git-scm.com/book/en/v2/Getting-Started-What-is-Git%3F"><strong>https://git-scm.com/book/en/v2/Getting-Started-What-is-Git%3F</strong></a></figcaption></figure><ul><li><strong>Working Directory: </strong>where you modify files</li><li><strong>Staging Area:</strong> hold the changes you want to commit</li><li><strong>.git directory:</strong> where the snapshots are stored</li></ul><p>The life circle of the file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/0*tF7leclsRDj_gV6s" /><figcaption><a href="https://git-scm.com/book/en/v2/Git-Basics-Recording-Changes-to-the-Repository"><strong>https://git-scm.com/book/en/v2/Git-Basics-Recording-Changes-to-the-Repository</strong></a></figcaption></figure><ul><li><strong>Untracked: </strong>file you didn’t have commit and which hasn’t yet been staged (add)</li><li><strong>Unmodified:</strong> when you first clone a repository, and you haven’t edited anything</li><li><strong>Modified: </strong>if you change a file that was already tracked</li><li><strong>Staged: </strong>files added to be committed</li></ul><h3>Let’s explain the main idea of Git using an analogy</h3><h4>The situation</h4><p>Imagine that you work in a bakery, where the best-selling cake is displayed on the main shelf. Over time, the owner realizes that the cake no longer meets customers’ expectations, and its sales have declined. Your boss then asks you to create a new version of the cake to attract customers, but until the new cake is ready, the current one must remain on the shelf.</p><p>So, you go to the kitchen, prepare your workspace, and bake a new cake exactly as it is on the shelf using the recipe of the cake. After baking the cake, you start creating a new version: a more colorful and different kind of chocolate cake. With this change, you update the recipe, adding the new ingredients used in the creation of this new version, and note the modifications you made.</p><p>With the new cake ready, you present it to your boss, who will assess whether the new version is suitable for display. After the review, your boss approved the new version, and now the shelf displays the new cake.</p><h4>Translating</h4><p>The shelf represents what we call the <strong>main branch</strong> (or <strong>master</strong>), which is usually the remote repository where the most up-to-date code is stored.</p><p>Going to the kitchen and preparing the workspace is equivalent to <strong>creating a branch in Git (new branch)</strong>. A branch is a separate environment where you can make changes without affecting the original code.</p><p>To make changes, you need the original cake recipe. This is similar to <strong>copying the original code and making changes using a new branch</strong>, from which all modifications will be made without affecting the main code.</p><p>After making changes in the kitchen (<strong>Working Directory</strong>), you add the new ingredients to the recipe (<strong>Staging Area</strong>) and store it (<strong>.git directory</strong>) to show it to your boss later. In Git, this corresponds to adding the changes and creating a commit, where you document the changes made.</p><p>Finally, for the new version of the cake to be displayed, it must be approved by your boss. In Git, this is done through a <strong>pull request</strong>, where the changes are reviewed and, if approved, are integrated into the main branch (<strong>git merge</strong>), becoming the new official version of the code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*zeB7_jaIgQIW7ZiI5IkSTg.png" /></figure><p>This was a simple example to illustrate some concepts of Git and further reading may be necessary to use Git properly. If you have any valuable suggestions for the material, feel free to comment.</p><h4>References and materials</h4><ul><li><a href="https://git-scm.com/">https://git-scm.com/</a></li><li><a href="https://www.canva.com/">https://www.canva.com/</a></li><li><a href="https://chatgpt.com/">https://chatgpt.com/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5f9d7dcbb7a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Some Pandas commands for data analysis]]></title>
            <link>https://medium.com/@fabitortorelli/some-pandas-commands-for-data-analysis-c9e1c1a195ff?source=rss-ffa71f50e95b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9e1c1a195ff</guid>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Fabiana Tortorelli]]></dc:creator>
            <pubDate>Sun, 03 Mar 2024 18:49:01 GMT</pubDate>
            <atom:updated>2024-03-03T18:49:01.921Z</atom:updated>
            <content:encoded><![CDATA[<p>When we get data to make predictions, inferences, or other tasks involving the data, it is important to know how information from a dataset is defined and, if necessary, make transformations to facilitate the analysis.</p><p>Below are topics using Pandas commands that may help you to analyze your data.</p><ol><li><strong>Load Data</strong></li><li><strong>Info and Describe</strong></li><li><strong>Check Missing Data</strong></li><li><strong>Check Duplicates</strong></li><li><strong>Filtering using contains</strong></li><li><strong>Merge</strong></li></ol><p>To demonstrate how these commands work, let’s use a dataset from Kaggle called “Data Science Books: Goodreads,” which can be found at this link: <a href="https://www.kaggle.com/datasets/kanchana1990/data-science-books-goodreads">https://www.kaggle.com/datasets/kanchana1990/data-science-books-goodreads</a>.</p><h4><strong>Load Data</strong></h4><p>We have many formats of datasets that can be loaded and analyzed, such as CSV, XLSX, JSON, PARQUET, HDF for example.</p><ul><li>CSV</li></ul><p>To load a CSV file, you can utilize the ‘read_csv’ function from Pandas. The commonly used parameters in this function include the path of the dataset and the ‘sep’ parameter, which specifies the character or regex pattern to treat as the delimiter:</p><pre>df_csv = pd.read_csv(&#39;goodreads_data_science_books.csv&#39;,sep=&#39;,&#39;)<br>df_csv.head(2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*qcZDrmhjrK8SPMY3CjWo8w.png" /></figure><ul><li>ZIP</li></ul><p>If your CSV file is zipped, you can still utilize the ‘read_csv’ function. The only modification needed is in the path, which should point to the zipped file:</p><pre>df_zip = pd.read_csv(&#39;goodreads_data_science_books.zip&#39;,sep=&#39;,&#39;)<br>df_zip.head(2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*9spho_4aIVsLUUb__an3tw.png" /></figure><p>If your zip file contains only one CSV file, you can still use the ‘read_csv’ function. However, please note that the zip file should only contain one CSV file for this method to work:</p><pre>df_zip = pd.read_csv(&#39;goodreads_data_science_books2.zip&#39;,sep=&#39;,&#39;)<br>df_zip.head(2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*bptLiWBL1xYxcVtQUMfE1g.png" /></figure><ul><li>GZIP</li></ul><p>You can also load a dataset if it is compressed in gzip format. Simply add the ‘compression’ parameter to the ‘read_csv’ function:</p><pre>df_zip = pd.read_csv(&#39;goodreads_data_science_books.csv.gz&#39;,compression=&quot;gzip&quot;, sep=&#39;,&#39;)<br>df_zip.head(2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*ChQnEaj3RqFZPilMMf7eRg.png" /></figure><p><strong>Observation:</strong></p><p>Sometimes, datasets can be excessively large, exceeding the processing capabilities of available resources. In such cases, you can utilize specific parameters to handle this challenge effectively.</p><ol><li>nrows Parameter:<br>The nrows parameter allows you to load only a portion of the dataset, enabling you to examine a subset of the data without overwhelming the processing resources. This parameter specifies the number of rows to read from the dataset.</li><li>usecols Parameter:<br>Similarly, the usecols parameter enables you to load only the columns that are essential for your analysis. By specifying the columns you need, you can significantly reduce the memory footprint and processing time required to handle the dataset.</li></ol><pre>df_zip_few_rows = pd.read_csv(&#39;goodreads_data_science_books.csv.gz&#39;,compression=&quot;gzip&quot;, sep=&#39;,&#39;, nrows=3)<br>df_zip_few_rows</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*zTVQlLXgYf2Y7vvv3wBEyw.png" /></figure><pre>cols = [&#39;publishedDate&#39;,&#39;rating&#39;, &#39;title&#39;]<br>df_zip_few_cols = pd.read_csv(&#39;goodreads_data_science_books.csv.gz&#39;,compression=&quot;gzip&quot;, sep=&#39;,&#39;, usecols=cols)<br>df_zip_few_cols.head(3)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*UXpdDHTRubuWrGSBYNdniw.png" /></figure><h4>Info and Describe</h4><p>Upon loading the dataset, it’s essential to inspect the types and details of the columns. The ‘info()’ command provides a concise summary of the DataFrame, including the data types of each column:</p><pre>df_zip.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*GSl6Enn133JstsJ2uvP-4g.png" /></figure><p>The ‘describe()’ command generates descriptive statistics for the dataset, providing information on central tendency, dispersion, and the shape of the distribution, while excluding NaN (missing) values:</p><pre>df_zip.describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*vJj3TgICDvFXwbDpJtSXYA.png" /></figure><p>By default, the ‘describe()’ command generates descriptive statistics for numeric columns (int64 and float64) in the dataset. However, to include all columns, you can add the parameter include=&#39;all&#39;:</p><pre>df_zip.describe(include=&#39;all&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*SuLIROhOiqoRlGTidPilpQ.png" /></figure><h4>Check Missing Data</h4><p>To examine missing data within the dataset, you can utilize the ‘isna().sum()’ command. This command provides the number of rows with missing values for each column:</p><pre>df_zip.isna().sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/177/1*RDXwsh_j7-tvmoXY9t3huw.png" /></figure><h4>Check Duplicates</h4><p>To identify duplicate rows within the dataset, you can use the ‘duplicated()’ command:</p><pre>(df_zip.duplicated()).value_counts()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/1*u1of0vNyoVv3s_F1yEd7ng.png" /></figure><p>The ‘duplicated()’ command has a default parameter keep=&#39;first&#39;, which marks duplicates as True except for the first occurrence. Additionally, it offers the option keep=&#39;last&#39;, marking duplicates as True except for the last occurrence. Moreover, setting keep=False marks all duplicates as True:</p><pre>(df_zip.duplicated(keep=&#39;last&#39;)).value_counts()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/1*4w19y6FQl_kpzTNGUnqUTQ.png" /></figure><pre>(df_zip.duplicated(keep=False)).value_counts()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/1*_WKc5QmsaxpiqBRbCI-a5A.png" /></figure><p>To check the duplicates details:</p><pre>df_zip[df_zip.duplicated() == True].head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/1*BJgGYxMKLTBL9finWRekWw.png" /></figure><pre>df_zip[df_zip[&#39;bookId&#39;] == 56751800]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/1*-NeJ5uyMMaH7Rg3QGIkwtQ.png" /></figure><h4><strong>Filtering using contains</strong></h4><p>To find titles from the dataset that contain a specific word or phrase, you can utilize the contains method. This allows you to filter the dataset based on whether a certain substring is present in the title column:</p><pre>df_zip[df_zip[&#39;title&#39;].str.upper().str.contains(&#39;GUIDE&#39;)][[&#39;authorName&#39;,&#39;bookId&#39;,&#39;bookFormat&#39;, &#39;publishedBy&#39;, &#39;publishedDate&#39;,&#39;rating&#39;, &#39;title&#39;]]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*BE9Hecmx8lgl6KvMgjRhlg.png" /></figure><h4>Merge</h4><p>To combine datasets, you can use the ‘merge’ command. One particularly useful parameter is ‘indicator’, which provides information on the source of each row by adding a column called ‘_merge’:</p><p>Let’s create a column called ‘id’ in the used dataset:</p><pre>df_zip[&#39;id&#39;] = [x for x in range(0,df_zip.shape[0])]<br>df_zip.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*UvOnmNzd8SC7qlrPHQmQuw.png" /></figure><p>And another dataset, called fake_df, to merge with the dataset:</p><pre>import numpy as np<br>d = {&#39;id&#39;: np.random.choice(range(0,df_zip.shape[0]), size=df_zip.shape[0]), &#39;like&#39;: np.random.choice([&#39;yes&#39;,&#39;no&#39;], size=df_zip.shape[0])}<br>fake_df = pd.DataFrame(data=d)<br>fake_df_nodup = fake_df.drop_duplicates()<br>fake_df_nodup.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/112/1*CEU6nr6CyPIRB_AbUVQdGw.png" /></figure><p>Now merge the two datasets:</p><pre>df_merge = df_zip.merge(fake_df_nodup, how=&#39;left&#39;, on=&#39;id&#39;, indicator = True)<br>df_merge.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*6rnAFkYh67_LBFRnfxMviw.png" /></figure><pre>df_merge[&#39;_merge&#39;].value_counts()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/218/1*VwcXhVJ132Ya8jTID0IzkQ.png" /></figure><p>[1]: <a href="https://pandas.pydata.org/pandas-docs/stable/index.html">https://pandas.pydata.org/pandas-docs/stable/index.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9e1c1a195ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Web Scraping — a way to collect data]]></title>
            <link>https://medium.com/@fabitortorelli/web-scraping-a-way-to-collect-data-8ca2ee4af1cf?source=rss-ffa71f50e95b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ca2ee4af1cf</guid>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Fabiana Tortorelli]]></dc:creator>
            <pubDate>Wed, 21 Feb 2024 10:25:12 GMT</pubDate>
            <atom:updated>2024-02-21T10:29:41.280Z</atom:updated>
            <content:encoded><![CDATA[<h3>Web Scraping — a way to collect data</h3><p>Web scraping is the process of extracting data from websites. This process involves sending an HTTP request to the target website and extracting the desired data.</p><p>I use the website <a href="https://books.toscrape.com/index.html">https://books.toscrape.com/index.html</a> to practice and improve my understanding of web scraping.</p><p>Two things are important when it comes to web scraping. First, it’s essential to check the website’s terms of service and any legal restrictions. Second, it’s necessary to have a solid understanding of HTML concepts.</p><p><strong>Task Definition:</strong></p><p>I want to extract data from all categories of books (highlighted in red rectangles below) on the website. Specifically, I intend to gather information on all titles and star ratings (highlighted in two different colors of blue rectangles below).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vrg-2E9bepCKauuLmvu4Fw.png" /><figcaption>Screenshot from <a href="https://books.toscrape.com/index.html">https://books.toscrape.com/index.html</a></figcaption></figure><p><strong>Importing Packages and Making the Request:</strong></p><p>Following the task definition, the initial step involved importing packages necessary for web scraping, such as:</p><pre>import requests<br>import lxml<br>import bs4</pre><p>With the requests package, we can initiate the request to access the website using the requests.get command:</p><pre>result = requests.get(&quot;https://books.toscrape.com/index.html&quot;)</pre><p>When applying the BeautifulSoup command to the request step, the information is represented as a nested HTML data structure:</p><pre>soup = bs4.BeautifulSoup(result.text,&quot;lxml&quot;)</pre><pre>&lt;!DOCTYPE html&gt;<br>&lt;!--[if lt IE 7]&gt;      &lt;html lang=&quot;en-us&quot; class=&quot;no-js lt-ie9 lt-ie8 lt-ie7&quot;&gt; &lt;![endif]--&gt;&lt;!--[if IE 7]&gt;         &lt;html lang=&quot;en-us&quot; class=&quot;no-js lt-ie9 lt-ie8&quot;&gt; &lt;![endif]--&gt;&lt;!--[if IE 8]&gt;         &lt;html lang=&quot;en-us&quot; class=&quot;no-js lt-ie9&quot;&gt; &lt;![endif]--&gt;&lt;!--[if gt IE 8]&gt;&lt;!--&gt;&lt;html class=&quot;no-js&quot; lang=&quot;en-us&quot;&gt; &lt;!--&lt;![endif]--&gt;<br>&lt;head&gt;<br>&lt;title&gt;<br>    All products | Books to Scrape - Sandbox<br>&lt;/title&gt;<br>&lt;meta content=&quot;text/html; charset=utf-8&quot; http-equiv=&quot;content-type&quot;/&gt;<br>&lt;meta content=&quot;24th Jun 2016 09:29&quot; name=&quot;created&quot;/&gt;<br>&lt;meta content=&quot;&quot; name=&quot;description&quot;/&gt;<br>&lt;meta content=&quot;width=device-width&quot; name=&quot;viewport&quot;/&gt;<br>&lt;meta content=&quot;NOARCHIVE,NOCACHE&quot; name=&quot;robots&quot;/&gt;<br>&lt;!-- Le HTML5 shim, for IE6-8 support of HTML elements --&gt;<br>&lt;!--[if lt IE 9]&gt;<br>        &lt;script src=&quot;//html5shim.googlecode.com/svn/trunk/html5.js&quot;&gt;&lt;/script&gt;<br>        &lt;![endif]--&gt;</pre><p><strong>Searching links for each book category:</strong></p><p>To extract the URLs related to the book categories, we need to select the appropriate data structure.</p><p>It’s observed that each category is associated with a URL. For instance, clicking on the “Travel” category opens another URL with the following link path: <a href="https://books.toscrape.com/catalogue/category/books/travel_2/index.html">https://books.toscrape.com/catalogue/category/books/travel_2/index.html</a>.</p><p>Hence, the task is to find all URLs related to the book categories. To do this, I started by selecting all URLs within the &lt;a&gt; tags on a page.</p><pre>lhref = []<br>for a in soup.find_all(&#39;a&#39;, href=True):<br>    print(&quot;Found the URL:&quot;, a[&#39;href&#39;])<br>    lhref.append(a[&#39;href&#39;])</pre><p>Running the command above, I got all URLs inside the website as you can see in some examples below:</p><pre>Found the URL: index.html<br>Found the URL: index.html<br>Found the URL: catalogue/category/books_1/index.html<br>Found the URL: catalogue/category/books/travel_2/index.html<br>Found the URL: catalogue/category/books/mystery_3/index.html<br>Found the URL: catalogue/category/books/historical-fiction_4/index.html<br>Found the URL: catalogue/category/books/sequential-art_5/index.html<br>Found the URL: catalogue/category/books/classics_6/index.html<br>Found the URL: catalogue/category/books/philosophy_7/index.html<br>Found the URL: catalogue/category/books/romance_8/index.html<br>Found the URL: catalogue/category/books/womens-fiction_9/index.html<br>Found the URL: catalogue/category/books/fiction_10/index.html<br>Found the URL: catalogue/category/books/childrens_11/index.html<br>Found the URL: catalogue/category/books/religion_12/index.html<br>Found the URL: catalogue/category/books/nonfiction_13/index.html</pre><p>I was specifically interested in URLs related to book categories. Therefore, I filtered out only those URLs that contain <em>‘catalogue/category/books/’ </em>in their path. Subsequently, I stored these filtered URLs in a list named ‘base_url’:</p><pre>base_url = []<br>for i in lhref:<br>    if &#39;catalogue/category/books/&#39; in i:<br>        base_url_aux = &#39;https://books.toscrape.com/&#39; + i<br>        base_url.append(base_url_aux)<br>base_url</pre><p>Here is some example of the output for the command above:</p><pre>[&#39;https://books.toscrape.com/catalogue/category/books/travel_2/index.html&#39;,<br> &#39;https://books.toscrape.com/catalogue/category/books/mystery_3/index.html&#39;,<br> &#39;https://books.toscrape.com/catalogue/category/books/historical-fiction_4/index.html&#39;,<br> &#39;https://books.toscrape.com/catalogue/category/books/sequential-art_5/index.html&#39;,<br> &#39;https://books.toscrape.com/catalogue/category/books/classics_6/index.html&#39;,<br> &#39;https://books.toscrape.com/catalogue/category/books/philosophy_7/index.html&#39;,<br> &#39;https://books.toscrape.com/catalogue/category/books/romance_8/index.html&#39;,<br> &#39;https://books.toscrape.com/catalogue/category/books/womens-fiction_9/index.html&#39;,<br> &#39;https://books.toscrape.com/catalogue/category/books/fiction_10/index.html&#39;,<br> &#39;https://books.toscrape.com/catalogue/category/books/childrens_11/index.html&#39;,<br> &#39;https://books.toscrape.com/catalogue/category/books/religion_12/index.html&#39;,<br> &#39;https://books.toscrape.com/catalogue/category/books/nonfiction_13/index.html&#39;,</pre><p><strong>Code to grab all titles and star ratings from each book category:</strong></p><p>To extract all titles and star ratings from each book category, I iterated through each URL (representing a book category) that I have collected. To achieve this, it’s crucial to identify the appropriate data structure from which to extract this information. This can be done by inspecting the webpage. For instance, when inspecting the page and right-clicking on the title of the first book in a category (e.g., Travel), I observed that both the title and star rating are contained within the class ‘product_pod’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MITBemKZJ1S2eMbZGdVXQw.png" /><figcaption>Inspect page from <a href="https://books.toscrape.com/index.html">https://books.toscrape.com/index.html</a></figcaption></figure><p>I’ve implemented a function named tableBooks to extract the title and star rating from each instance of the &#39;product_pod&#39; class. Additionally, I observed that certain book categories had multiple pages, so I had to loop all pages to get the information (that is on commands at <em>#Next pages </em>step):</p><pre>dict_1 = {}<br><br>def tableBooks(soup_1, dict_cat):<br>    if not &#39;title&#39; in dict_cat:<br>        dict_cat[&#39;title&#39;] = []<br>    if not &#39;rate&#39; in dict_cat:     <br>        dict_cat[&#39;rate&#39;] = []<br>    for j in range(0, len(soup_1.select(&quot;.product_pod&quot;))):<br>        title_aux = soup_1.select(&quot;.product_pod&quot;)[j].select(&quot;a&quot;)[1][&quot;title&quot;]<br>        rating_aux = soup_1.select(&quot;.product_pod&quot;)[j].select(&quot;.star-rating&quot;)[0][&#39;class&#39;][1]<br>        dict_cat[&#39;title&#39;].append(title_aux)<br>        dict_cat[&#39;rate&#39;].append(rating_aux)    <br>  <br>for i in range(0,len(base_url)):<br>    req_1 = requests.get(base_url[i])<br>    soup_1 = bs4.BeautifulSoup(req_1.text,&quot;lxml&quot;)<br>    category = base_url[i].split(&#39;/&#39;)[-2].split(&#39;_&#39;)[0]  <br>    print(&#39;Category:&#39;, category)<br>    <br>    #First page<br>    dict_1[category] = {}<br>    tableBooks(soup_1, dict_1[category])<br><br>    #Next pages<br>    while not [] == soup_1.select(&quot;.pager &gt; .next &gt; a&quot;):<br>        print(&quot;Página:&quot;, soup_1.select(&quot;.pager &gt; .next &gt; a&quot;)[0][&#39;href&#39;])<br>        req_1 = requests.get(base_url[i][0:-10] + soup_1.select(&quot;.pager &gt; .next &gt; a&quot;)[0][&#39;href&#39;])<br>        soup_1 = bs4.BeautifulSoup(req_1.text,&quot;lxml&quot;)<br>        tableBooks(soup_1, dict_1[category]) </pre><p><strong>Saving the information:</strong></p><p>After extracting all the information, I proceeded to save it for further analysis. I saved the collected data as a JSON file using the following command:</p><pre>import json<br># Convert the dictionary to a JSON string<br>json_string = json.dumps(dict_1, indent=4)<br><br># Save the output data   <br>save_file = open(&quot;ScrapBook.json&quot;, &quot;w&quot;)  <br>json.dump(json_string, save_file)  <br>save_file.close()   </pre><p>Here is a piece of the data saved:</p><pre>{<br>    &quot;travel&quot;: {<br>        &quot;title&quot;: [<br>            &quot;It&#39;s Only the Himalayas&quot;,<br>            &quot;Full Moon over Noah\u00e2\u0080\u0099s Ark: An Odyssey to Mount Ararat and Beyond&quot;,<br>            &quot;See America: A Celebration of Our National Parks &amp; Treasured Sites&quot;,<br>            &quot;Vagabonding: An Uncommon Guide to the Art of Long-Term World Travel&quot;,<br>            &quot;Under the Tuscan Sun&quot;,<br>            &quot;A Summer In Europe&quot;,<br>            &quot;The Great Railway Bazaar&quot;,<br>            &quot;A Year in Provence (Provence #1)&quot;,<br>            &quot;The Road to Little Dribbling: Adventures of an American in Britain (Notes From a Small Island #2)&quot;,<br>            &quot;Neither Here nor There: Travels in Europe&quot;,<br>            &quot;1,000 Places to See Before You Die&quot;<br>        ],<br>        &quot;rate&quot;: [<br>            &quot;Two&quot;,<br>            &quot;Four&quot;,<br>            &quot;Three&quot;,<br>            &quot;Two&quot;,<br>            &quot;Three&quot;,<br>            &quot;Two&quot;,<br>            &quot;One&quot;,<br>            &quot;Four&quot;,<br>            &quot;One&quot;,<br>            &quot;Three&quot;,<br>            &quot;Five&quot;<br>        ]<br>    },<br>    &quot;mystery&quot;: {<br>        &quot;title&quot;: [<br>            &quot;Sharp Objects&quot;,<br>            &quot;In a Dark, Dark Wood&quot;,<br>            &quot;The Past Never Ends&quot;,<br>            &quot;A Murder in Time&quot;,<br>            &quot;The Murder of Roger Ackroyd (Hercule Poirot #4)&quot;,<br>            &quot;The Last Mile (Amos Decker #2)&quot;,<br>            &quot;That Darkness (Gardiner and Renner #1)&quot;,<br>            &quot;Tastes Like Fear (DI Marnie Rome #3)&quot;,<br>            &quot;A Time of Torment (Charlie Parker #14)&quot;,<br>            &quot;A Study in Scarlet (Sherlock Holmes #1)&quot;,<br>            &quot;Poisonous (Max Revere Novels #3)&quot;,<br>            &quot;Murder at the 42nd Street Library (Raymond Ambler #1)&quot;,<br>            &quot;Most Wanted&quot;,<br>            &quot;Hide Away (Eve Duncan #20)&quot;,<br>            &quot;Boar Island (Anna Pigeon #19)&quot;,<br>            &quot;The Widow&quot;,<br>            &quot;Playing with Fire&quot;,<br>            &quot;What Happened on Beale Street (Secrets of the South Mysteries #2)&quot;,<br>            &quot;The Bachelor Girl&#39;s Guide to Murder (Herringford and Watts Mysteries #1)&quot;,<br>            &quot;Delivering the Truth (Quaker Midwife Mystery #1)&quot;,<br>            &quot;The Mysterious Affair at Styles (Hercule Poirot #1)&quot;,<br>            &quot;In the Woods (Dublin Murder Squad #1)&quot;,<br>            &quot;The Silkworm (Cormoran Strike #2)&quot;,<br>            &quot;The Exiled&quot;,<br>            &quot;The Cuckoo&#39;s Calling (Cormoran Strike #1)&quot;,<br>            &quot;Extreme Prey (Lucas Davenport #26)&quot;,<br>            &quot;Career of Evil (Cormoran Strike #3)&quot;,<br>            &quot;The No. 1 Ladies&#39; Detective Agency (No. 1 Ladies&#39; Detective Agency #1)&quot;,<br>            &quot;The Girl You Lost&quot;,<br>            &quot;The Girl In The Ice (DCI Erika Foster #1)&quot;,<br>            &quot;Blood Defense (Samantha Brinkman #1)&quot;,<br>            &quot;1st to Die (Women&#39;s Murder Club #1)&quot;<br>        ],<br>        &quot;rate&quot;: [<br>            &quot;Four&quot;,<br>            &quot;One&quot;,<br>            &quot;Four&quot;,<br>            &quot;One&quot;,<br>            &quot;Four&quot;,<br>            &quot;Two&quot;,<br>            &quot;One&quot;,<br>            &quot;One&quot;,<br>            &quot;Five&quot;,<br>            &quot;Two&quot;,<br>            &quot;Three&quot;,<br>            &quot;Four&quot;,<br>            &quot;Three&quot;,<br>            &quot;One&quot;,<br>            &quot;Three&quot;,<br>            &quot;Two&quot;,<br>            &quot;Three&quot;,<br>            &quot;Five&quot;,<br>            &quot;Five&quot;,<br>            &quot;Four&quot;,<br>            &quot;Four&quot;,<br>            &quot;Two&quot;,<br>            &quot;Five&quot;,<br>            &quot;Three&quot;,<br>            &quot;One&quot;,<br>            &quot;Three&quot;,<br>            &quot;Two&quot;,<br>            &quot;Four&quot;,<br>            &quot;Five&quot;,<br>            &quot;Three&quot;,<br>            &quot;Three&quot;,<br>            &quot;One&quot;<br>        ]<br>    },</pre><p><strong>Description analysis of extracted data:</strong></p><p>Now that I have obtained the data, I can conduct some analysis. First, I imported the necessary packages and proceeded to read the JSON file containing the extracted data:</p><pre>import pandas as pd<br>import json<br>import matplotlib.pyplot as plt<br>import numpy as np</pre><pre>with open(&#39;ScrapBook.json&#39;, &#39;r&#39;) as j_data:<br>    j_data = json.load(j_data)<br>parsed_json = json.loads(j_data)<br>parsed_json.keys()</pre><p>Examining the keys of the file, I can observe all the book categories that I scraped:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o4jzNNIIwfhInWl0XLfjFw.png" /></figure><p>To utilize the Pandas package, I transformed the JSON file into a format compatible with Pandas:</p><pre>df_final = pd.DataFrame()<br>for key in parsed_json.keys():<br>    df = pd.DataFrame()<br>    df[&#39;title&#39;] = pd.json_normalize(parsed_json[key], record_path=&#39;title&#39;)<br>    df[&#39;rate&#39;] = pd.json_normalize(parsed_json[key], record_path=&#39;rate&#39;)<br>    df[&#39;Category&#39;] = key<br>    df_final = pd.concat([df_final,df])</pre><p>Here I could see two situations: first, there are some special characters present in the title column. However, since my analysis didn’t involve the written titles, this didn’t affect my process. Second, the rate column was represented as strings, which need to be converted to numerical values to facilitate further analysis:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/1*XL3bP2NnnMGOCDiJ8AMZSQ.png" /></figure><ul><li><strong>Default verifications:</strong></li></ul><p>I performed some default checks including examining its shape, identifying null values, checking for duplicates, and reviewing data types:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BhyUxTZCp6OyPnEXODLjiA.png" /></figure><p>As observed, the <em>DataFrame</em> consists of 1000 rows and it indicated the absence of null values. However, one duplicate entry was identified. Getting closer examination, it was found that the “Fantasy” category contains a duplicated value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n3VIsrjZ7Lvf6LCWdyLv-Q.png" /></figure><p>Reviewing the website, it appears that there are indeed two books with the title “The Star-Touched Queen”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*OxiIC0FR_8N-4bcz0bTGjQ.png" /></figure><ul><li><strong>Pre-processing the data:</strong></li></ul><p>For preprocessing the data, I removed the duplicated values and converted the “rate” column into numeric values:</p><pre>df_final = df_final.drop_duplicates()<br>def transRate(x):<br>    rateDict = {&#39;One&#39;:1, &#39;Two&#39;: 2, &#39;Three&#39;: 3, &#39;Four&#39;: 4, &#39;Five&#39;: 5}<br>    return rateDict[x]<br>df_final[&#39;rateNumeric&#39;] = df_final[&#39;rate&#39;].apply(transRate)<br>df_final.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*JBDoV_zlMExgAtW3vutXBQ.png" /></figure><ul><li><strong>Taking some numbers:</strong></li></ul><p>I conducted an analysis to determine the number of books in each category. It was found that the “default” category has the highest number, with a total of 152 books.</p><pre># Draw plot<br>plt.figure(figsize=(10,6))<br>plot=df_final[&#39;Category&#39;].value_counts().plot(kind=&#39;bar&#39;, alpha=0.7, linewidth=20)<br><br># Annotate Text<br>for i, cty in enumerate(df_final[&#39;Category&#39;].value_counts()):<br>    plt.text(i, cty+1.5, cty, horizontalalignment=&#39;center&#39;)<br><br># Title, Label<br>plot.set_title(&#39;Bar Chart for Categories&#39;, fontdict={&#39;size&#39;:22})<br>plot.set(ylabel=&#39;Number of books&#39;, ylim=(0, 160))<br><br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E0ZgjFXGXe2afY_KWSbdIw.png" /></figure><p>I also examined the distribution of ratings. The most frequent rating is one, while the least frequent is four.</p><pre># Draw plot<br>plt.figure(figsize=(10,6))<br>plot=df_final[&#39;rateNumeric&#39;].value_counts().plot(kind=&#39;bar&#39;, alpha=0.7, linewidth=20)<br><br># Annotate Text<br>for i, cty in enumerate(df_final[&#39;rateNumeric&#39;].value_counts()):<br>    plt.text(i, cty+5, cty, horizontalalignment=&#39;center&#39;)<br><br># Title, Label<br>plot.set_title(&#39;Bar Chart for Rating&#39;, fontdict={&#39;size&#39;:22})<br>plot.set(ylabel=&#39;Frequency of rating&#39;, ylim=(0, 250))<br>plot.set(xlabel=&#39;Rating&#39;)<br><br><br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kB_Lc8BuBIxenQU_EYCnTQ.png" /></figure><p>Finally, I determined which category has the highest mean rating. To achieve this, I grouped the data and calculated the mean rating for each category. Categories such as “novels”, “erotica”, and “adult-fiction” have a mean rating of 5, but these categories contain only one book each. For categories with 30 books or more, the highest mean rating is observed in the “young-adult” category.</p><pre>df_group = df_final.groupby(&#39;Category&#39;).aggregate({&#39;title&#39;:&#39;count&#39;, &#39;rateNumeric&#39;:[&#39;min&#39;,&#39;max&#39;,&#39;mean&#39;,&#39;median&#39;]}).reset_index()<br>df_group2 = df_group.sort_values(by=[(      &#39;title&#39;,  &#39;count&#39;)],ascending=False)<br>df_group2.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*hHI5pRnBkzq8N_gxXSo91w.png" /></figure><pre># Draw plot<br>fig, ax = plt.subplots(figsize=(16,10), dpi= 80)<br>ax.vlines(x=df_group2[(   &#39;Category&#39;,       &#39;&#39;)], ymin=0, ymax=df_group2[(&#39;rateNumeric&#39;,   &#39;mean&#39;)], color=&#39;firebrick&#39;, alpha=0.7, linewidth=2)<br>ax.scatter(df_group2[(   &#39;Category&#39;,       &#39;&#39;)], df_group2[(&#39;rateNumeric&#39;,   &#39;mean&#39;)], s=75, color=&#39;firebrick&#39;, alpha=0.7)<br><br># Title, Label, Ticks and Ylim<br>ax.set_title(&#39;Lollipop Chart for Mean Rating&#39;, fontdict={&#39;size&#39;:22})<br>ax.set_ylabel(&#39;Mean Rating&#39;)<br>ax.set_xticks(df_group2[(   &#39;Category&#39;,       &#39;&#39;)])<br>ax.set_xticklabels(df_group2[(   &#39;Category&#39;,       &#39;&#39;)].str.upper(), rotation=60, fontdict={&#39;horizontalalignment&#39;: &#39;right&#39;, &#39;size&#39;:12})<br>ax.set_ylim(0, 5.5)<br><br># Annotate<br>i=0<br>for row in df_group2.itertuples():<br>    ax.text(i, row._5+0.05, s=round(row._5,2), horizontalalignment= &#39;center&#39;, verticalalignment=&#39;bottom&#39;, fontsize=14)<br>    i=i+1<br><br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hbxRJOuOhDZTJWWqnWJOTA.png" /></figure><p>This serves as an example of how I performed web scraping on a website and subsequently extracted some numbers of the collected data.</p><p>One of the main challenges was inspecting the webpage to identify the appropriate HTML tags necessary for extracting the desired information.</p><p>I welcome any feedback or suggestions on my approach. To support my studies, I utilized the following course materials and documentation:</p><ul><li><a href="https://www.udemy.com/course/complete-python-bootcamp/learn/lecture/20345257#overview">https://www.udemy.com/course/complete-python-bootcamp/learn/lecture/20345257#overview</a></li><li><a href="https://beautiful-soup-4.readthedocs.io/en/latest/">https://beautiful-soup-4.readthedocs.io/en/latest/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ca2ee4af1cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>