<?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 Letícia Lang on Medium]]></title>
        <description><![CDATA[Stories by Letícia Lang on Medium]]></description>
        <link>https://medium.com/@leticiaplang?source=rss-ed6e42b6a752------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*XqwIMJpuEot2E5qLQTVPuQ.jpeg</url>
            <title>Stories by Letícia Lang on Medium</title>
            <link>https://medium.com/@leticiaplang?source=rss-ed6e42b6a752------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 00:34:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@leticiaplang/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[Final Project — Data Science]]></title>
            <link>https://medium.com/@leticiaplang/final-project-data-science-4e72bcbd81c0?source=rss-ed6e42b6a752------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e72bcbd81c0</guid>
            <dc:creator><![CDATA[Letícia Lang]]></dc:creator>
            <pubDate>Mon, 14 Feb 2022 14:00:59 GMT</pubDate>
            <atom:updated>2022-02-14T14:00:59.657Z</atom:updated>
            <content:encoded><![CDATA[<h3>Final Project — Data Science</h3><p>The choosen dataset is from [Kaggle](https://www.kaggle.com/prathamtripathi/drug-classification) and it’s about drug classification considering 6 features. It has 200 informations(rows) and the features below:</p><ul><li>Age: 15–74 years</li><li>Sex: F(female), M(male)</li><li>Blood Pressure Levels (BP): normal, low, high</li><li>Cholesterol Levels: normal, high | blood exam</li><li>Na to Potassium Ratio: 6.269–38.247 | urinary exam | a high ratio is an indicator of a higher Na intake and a lower K intake.</li></ul><p>The goal is predict which drug (a, b, c, y, or z) will be used based on patient’s features.</p><p><strong>Preparing the notebook and importing the dataset</strong></p><p>It’s always important install and import all libraries and packages you will need to run the data analysis. After that we can import the dataset.</p><p>In this case, I decided make the download from Kaggle and save the csv document at my google drive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9_P1Vi4TSpjiHQWrp-otYA.png" /></figure><p><strong>Exploratory analysis and data transformations</strong></p><p>The first step I used to take is knowing a little bit of the dataframe. I look for dataframe size and distribution, nulls, duplicated and unique values as well as data types.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_OzcIZaWT1gsAXZfVpBxYQ.png" /></figure><p>After that I can categorize the variables as categorical or continuous. In this dataset the categorical are sex, BP (blood pressure), cholesterol and drug and the continuous variables are age and na_to_k.</p><p>I transform all data to lowercase, because it makes the work more fluid and I take the opportunity to get only the essential information at drug column.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lc_Iyq6On8GVc-hsWdp7uw.png" /></figure><p>I start exploring it with graphs to analyse the distribution of continuous data and the balance of categorical data. After this general idea, I calculate the outliers and analyse them to understand the relationship between them and the target (drug).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CLEAQDUKGoBhNEG1CjTvIw.png" /><figcaption>Imbalance categorical data | Age is more similar to symmetrical distribution and it hasn&#39;t outliers| Na to K has positive skewness and it has outliers.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mTuLnXeI9NBB2mwUBGEerg.png" /><figcaption>The outliers seems have an association with the drug Y. I choose not delete them.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SuBCaQyygv5jVoag9PzgQQ.png" /><figcaption>It evidences an imbalanced data of BP and drug subgroups.</figcaption></figure><p>Now I&#39;m preapared to analyse the dataset looking for insights about which feature can be important to define the drug treatment. First I started with scatter plots analysing all features with drug and age, and I confirmed the informations analysing the features with drug and na to k.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G_En80HaphLey2xgVdcomA.png" /><figcaption>drug A: lower than 50 years old, high BP| drug B: higher than 50 years old, high BP | drug C: low BP, high Cholesterol | drug Y: na to k higher than 18.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*36wPIPnA0W1ZEqOEwZWw_A.png" /><figcaption>Drug Y: na to k higher than 15.</figcaption></figure><p>These plots don&#39;t help to realize some association between drug and age or sex, so I decided plot them individually with the target. It shows imbalanced data and maybe some difference of age at drug B.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NzVeKjr2V6cX8oRLFhPQwQ.png" /><figcaption>Same impression of drug B for people with age higher than 50(?)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LsWzu5kvKK5jPgnwEKTE_A.png" /><figcaption>It’s similar distribution, but still imbalanced.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*m598YUjbNrojgb0VGfo8jg.png" /><figcaption>Insights</figcaption></figure><p>At exploratory phase I could get some insights, but some classification algorithms is needed to predict the kind of drug used.</p><p><strong>Creating and testing some classification algorithms</strong></p><p>Once our goal is predict the drug treatment recommendation and the insights couldn’t define at all which drug will be used based on features, I&#39;ll use classification algorithm to do that.</p><p>First of all we need define which features and target will be used:</p><ul><li>Target: Drug</li><li>Features: Age, Na_to_K, Sex, BP, Cholesterol</li></ul><p>After that we need transform the categorical data from string to numerical data. I’ going transform them with label encoder and I&#39;m going define the order of elements for blood pressure and cholesterol.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d1GFfx83Y7XSmO1qSaW-LA.png" /><figcaption>Transformation with label encoder.</figcaption></figure><p>Now I&#39;m going define two functions, one which create features and transformations scenarios and other to run trasnformation and models functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MOICW97hwfy3Iza-yA7Tfw.png" /><figcaption>Creating the scenarios function.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nuSqBjWTN3WhsEj9joMhwg.png" /><figcaption>Creating the transformations and models functions.</figcaption></figure><p>Now it&#39;s ready to be tested! I&#39;m going define the variables I want test and see how many scenarios I created for it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jdLFd2CCG6pZzKw8lJSUfw.png" /><figcaption>Defining the scenarios which I want test and calling the function to create and return the number of scenarios I&#39;ll test.</figcaption></figure><p>In my model function I defined to run 5000 times the same scenario and to return an array with the metrics results. Now I’m going analyse each one comparing the mean and outliers. For all metrics how bigger the number, better is the prediction. Never forgetting the underfitting or overfitting. 👀</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_tV8GkQuE8Fw0AzXo_c0Ew.png" /><figcaption>Dummy Model(baseline value).</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MDnv7buCRR7JWnRx67eYVQ.png" /><figcaption>Logistic Classification.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JlTSIq_afYoA1iWw6kZXiA.png" /><figcaption>K-Nearest Neighbors.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wKklxGEdPJrr6FPp0wfMBA.png" /><figcaption>Decision Trees Calssification.</figcaption></figure><p><strong>Conclusions and model improvements</strong></p><p>This drug classification algoritihm is a start to improve or support drug treatment decisions in healthcare. The number of medication errors caused by incorrectly prescription is high, and, even with protocols and some prescription system blocks, it remain. Allying machine learning and healthcare can improve the quality and security of care, preventing sentinel events and saving money.</p><p>The baseline choosen was dummy classifier, once it&#39;s the simplest model for this goal. Analysing all graphs we can look for the highest column, which is the median value, meaning the most frequent number. We can define a rank from lowest to highest median: dummy, KNN, logistic classification, decision tree.</p><p>At this scenario, the best model prediction was logistic regression. The decision tree had the median equals to one, which means it predicts 100% correctly. When we have so high prediction score, it has a high probability of overfitting, meaning your model is memorizing the reulsts and not predicting them. It can be fixed by increasing the sample size, testing the hyper-parameters or using techniques as L1 or L2, for example.</p><p>As the project goal is show a first algorithm construction, the best performance for this context was with logistic classification model. It predict correctly 89% of the sample and it identifies less false positives(precision) and a little more of false negatives (recall).</p><p>Now I challenge you to access the <a href="https://github.com/leticiaplang/drug_classification">dataset</a> and look for better results with me 😃</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e72bcbd81c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Analytics — Projeto final]]></title>
            <link>https://medium.com/@leticiaplang/data-analytics-projeto-final-e8f1345716a?source=rss-ed6e42b6a752------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8f1345716a</guid>
            <dc:creator><![CDATA[Letícia Lang]]></dc:creator>
            <pubDate>Wed, 09 Feb 2022 19:09:47 GMT</pubDate>
            <atom:updated>2022-02-09T19:09:47.313Z</atom:updated>
            <content:encoded><![CDATA[<h3>Data Analytics — Projeto final</h3><p><strong>1. Dataset e preparo pré-analise</strong></p><p>Foi escolhido o dataset da Olist, disponível no <a href="https://www.kaggle.com/olistbr/brazilian-ecommerce">Kaggle</a>. Ele é composto por 8 bases de dados inter-relacionadas, compondo 99441 dados no seu total. Sendo assim, essa fonte cumpre as orientações iniciais e permite que aprimore meus conhecimento em dados de marketplace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aXTlOcs3-l0L4Bi_pyiADA.png" /></figure><p>A Olist é uma empresa curitibana que surgiu conectando pequenos e médios lojistas e evoluiu para inclusão deles na venda em grandes marketplaces. Um dos objetivos da empresa é ampliar o faturamento e lucro mensal. Em 2017 foram realizadas diversas melhorias no aplicativo web para que os clientes da empresa pudessem acompanhar a performance das entregas, desenvolvimento de nova API de fretes que resultou no record de menor tempo de entrega, além do novo método de adicionar novos produtos em 1 minuto.</p><p>O objetivo do dashboard é acompanhar o receita durante o ano de 2017 e 2018, identificando:</p><ul><li>Quais as categorias que mais geram receita</li><li>Como se comportou a receita ao longos desses anos</li><li>Houve mudança do comportamento de compra dos clientes</li></ul><p><strong>2. Processo de análise dos dados</strong></p><p><strong>2.1 Importação e análise dos dados no Big Query:</strong></p><p>Para realizar a importação é necessário realizar o download do dataset do Kaggle e importar para o Big Query. Para analisar os objetivos precisarei analisar os seguintes dados:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HbGxDPVi2WfExNEg11ziwA.png" /></figure><p><strong>2.2 Análise geral dos dados de cada dataset na busca de tratamentos</strong></p><p>Para podermos trabalhar com o banco de dados, utilizaremos a plataforma Big Query para trabalhar com a linguagem SQL.</p><p>Primeiramente é preciso realizar a importação dos datasets e analisar o tipo de cada dado:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*bVZgacvdt66uja8XQwHrtA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*mP3zWUZSepZj64AKY9J0lA.png" /></figure><p>A partir disso podemos iniciar uma nova query para descobrirmos mais sobre os dados.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8VVpDKDmoBOxMorjnZ8sxQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qwNK_OiMPehOT3vi9c6bKA.png" /></figure><p><strong>3. Construção do mockup</strong></p><p>É ideal que seja feito um protótipo do painel para validação do usuário que solicitou. Ele pode ser feito na ferramenta firma, power point ou esboço à mão. Esta fase é importante, pois ajustes estruturais serão mais fáceis de corrigir, assim como outras métricas que preferirem dentro do contexto do dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b8x3JLGVCkadqDHLEJtNwQ.png" /></figure><p>O primeiro gráfico escolhido foi o de linhas para podermos analisar o comportamento da receita total ao longo do tempo.</p><p>O segundo foi utilizado um gráfico de pareto para sabermos quais categorias de produtos representam 70% da receita.</p><p>O terceiro foi escolhido um gráfico de barras horizontais para podermos ter a receita de cada categoria já em ordem descendente, facilitando a visualização de todas as categorias.</p><p>O quarto gráfico foi escolhido um treemap para compreendermos visualmente a proporção de cada estado na receita total e para podermos clicar em cada item com possibilidade de filtro. Por este motivo, os valores menores não foram agrupados em um único grupo.</p><p><strong>4. Construção do dashboard</strong></p><p>Após aprovação iremos para construção do dashboard em si. Foi preciso realizar a exportação dos data sets trabalhados com SQL em formato CSV para depois realizar o upload para o PowerBi. Logo na importação dos data sets já realizamos a transformação dos dados, garantindo o tipo de dados de cada coluna e verificando alguma inconsistência não verificada anteriormente.</p><p>Após importar todas as tabelas, precisamos verificar e garantir se a modelagem, ou seja, as conexões entre as tabelas está correta para que os dados possam ser filtrados conforme cliques no dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cfUFOD_6xvdtD8O8fMKdkg.png" /></figure><p>Agora é a hora de revisitar o protótipo do dashboard e ver quais informações serão necessárias para a construção. Eu prefiro ir construindo os gráficos e analisando as necessidades a cada construção, por isso já iniciei as construções conforme segue:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*sD6OaJ5SiyXkndChsnY9DQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*2zG8D4Iv6-ndzlKeXUaP_A.png" /><figcaption><em>Filtros: inserir um filtro contendo o dado Year e outro contendo o dado Month. Quando clicado em cima, ficará preto e está inserindo os dados desses anos/meses selecionados.</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fFYsV6DZnj4sHeJFuuH7FA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*R-vYGQqHyjrY8-0jM0sjQQ.png" /><figcaption><em>Gráfico de linhas: inserir Month e Year para podermos filtrar e em valores Price. Ele irá calcular a soma do total de Price por mês e por ano.</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mIqked9jY0GeC2KIZ-JuLw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*OTH8ZlCRaSmDxpdka8a70A.png" /><figcaption><em>Gráfico de barras horizontais: inserir Product Category Name no axis e Price nos valores. Ele irá calcular a soma dos valores de Price dando o total por categoria.</em></figcaption></figure><p>Para montar o gráfico de Pareto, foi necessário criar uma nova tabela realizando o merge queries, uma vez que para o Pareto necessito das informações dos preços e categorias de produto. Após mantenho categoria e preço e realizo um agrupamento pela categoria, resultando no total income por categoria. Após isso é necessário criar uma nova coluna para cada uma das seguintes funções:</p><ul><li>Coluna Rank utilizando a função RANKX(nova da tabela, nome da tabela[coluna com a receita por categoria];</li><li>Coluna Total de receita utilizando a função SUM(tabela[price])</li><li>Coluna Acumulado com a função CALCULATE(SUM(tabela[coluna total da receita por categoria]), FILTER(ALLSELECTED(tabela), tabela[rank] &lt;= EARLIER(tabela[rank])))</li><li>Coluna Percentual acumulado utilizando como função a divisão do valor total por categoria pelo valor total de receita</li></ul><p>Agora é só criar o gráfico e inserir os dados conforme abaixo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lQ9peuMhWZyqPUQZNAcIWg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*au7HwICv3OWQi-BVxJdiCA.png" /><figcaption><em>Gráfico de Pareto: inserir as categorias no axis, inserir o total income por categoria nas colunas e o percentual dele na linha.</em></figcaption></figure><p>E por último, mas não menos importante o treemap:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*8nhiYK9F4_qMrOJc24NEGg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*9Y4d62hqrbqiuV0LLWvUsw.png" /></figure><p><strong>5. Versão final do dashboard</strong></p><p>O dashboard final ficou nesta disposição:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BYKGjMixTyXUcpj0GIopQA.png" /></figure><p>Se selecionarmos o ano de 2017, podemos identificar alteração dos valores no total income, total income by category e no total income by country.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LmWoBVErkJ_P-JKf3EnQSg.png" /></figure><p>E se selecionarmos uma categoria, podemos identificar destaque de uma categoria e a mudança dos valores nos outros dois gráficos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D_Hp0j1eNrtpncog0fxL7g.png" /></figure><p>E observamos o mesmo se a seleção ocorrer no estado.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gN3ThNjfyZL7QaPbIHrGhw.png" /></figure><p><strong>6. Observações finais</strong></p><ul><li>O dataset possui poucos dados do ano de 2016 e 2018/2, gerando comportamentos muito extremos nesses períodos.</li><li>Tornaria o dashboard mais atrativo se o pareto fosse iterável e a ordem do gráfico de categoria alterasse conforme os filtros.</li><li>Este foi o meu primeiro dashboard em PowerBi e toda sugestão será muito bem-vinda 😃</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8f1345716a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>