[{"content":"As a Data Scientist at NECTO Systems, I worked on a project for Climatempo, the leading meteorology company in Brazil. The main goal was to build a predictive model to estimate the number of occurrences (failures) in the electrical power grid caused by severe weather events, such as heavy rain, wind gusts, and lightning.\nThe Challenge # The relationship between weather and power grid infrastructure is critical for energy companies. Accurately predicting the volume of failures allows for better resource allocation and faster response times.\nHowever, this presented a significant modeling challenge: the target variable was count data (non-negative integers) with a highly skewed distribution. Most days have zero or very few incidents, while severe storms can cause a sudden spike in failures (extreme values). Standard regression approaches (optimizing for MSE) often failed to capture this behavior, predicting negative values or underestimating the peaks.\nThe Solution # To address this, I developed a complete Machine Learning pipeline using Python. The process involved:\nData Engineering: merging historical meteorological data with occurrence logs, performing extensive cleaning, and handling time-series constraints (ensuring no data leakage from future events). Model Selection: After an extensive screening phase comparing Linear Models, Random Forests, and Gradient Boosting methods, the final solution relied on a LightGBM Regressor configured with a Poisson objective function. Optimization: The Poisson loss function was crucial as it is specifically designed for count data, allowing the model to naturally handle the non-negative nature of the target and its variance. The final model was evaluated using Time Series Cross-Validation, ensuring robustness across different seasons and weather patterns.\nWorkflow of the regression methodology adopted for the final solution, from data processing to model validation Technologies Used # Language: Python Libraries: Pandas, Scikit-learn, LightGBM, XGBoost Techniques: Feature Engineering, Time Series Cross-Validation, Poisson Regression, Hyperparameter Tuning. ","externalUrl":null,"permalink":"/portfolio/2025-climatempo/","section":"Portfolio","summary":"As a Data Scientist at NECTO Systems, I worked on a project for Climatempo, the leading meteorology company in Brazil. The main goal was to build a predictive model to estimate the number of occurrences (failures) in the electrical power grid caused by severe weather events, such as heavy rain, wind gusts, and lightning.","title":"Predicting Power Grid Failures with Weather Data","type":"portfolio"},{"content":"While at NECTO Systems, I had the opportunity to work with Uber facing challenges in their accounting reconciliation for tax purposes. The goal was to reconstruct and reconcile financial reports from their databases, aiming to create an automated pipeline to facilitate this process. As a data analyst, I played a key role in addressing these challenges and delivering effective solutions.\nContext\nUber was granted authorization by the São Paulo city hall starting in 2019 to operate under a special single invoice regime for the collection of fees charged per kilometer driven in the capital. However, it is still necessary for the company to maintain a complete record of which trips and their respective values make up this invoice, for the public oversight agency.\nChallenge\nFigure 1. High-level flow of data from mobile apps and services to data warehouse and consumption surfaces. Source: Uber Blog The client struggled with reconciling their financial information, with many manual interventions during the process, which compromised their efficiency to meet tax obligations and keep accounting practices aligned with global standards. The challenge was to develop an automated process for data retrieval and reconciliation, using data engineering techniques.\nSolution\nAs a data analyst, I developed a customized solution for the client, employing skills and tools such as SQL, Python, Pandas, Hive, and Presto. The approach involved analyzing the client\u0026rsquo;s data, creating an automated pipeline for data retrieval and reconciliation.\nResults\nWith the implementation of the solution proposed, the client successfully reconciled financial reports for their business lines, ensuring the required compliance and adopting accounting practices aligned with global standards. This change provided greater reliability and efficiency in accounting and tax processes, generating significant benefits for the client.\n","externalUrl":null,"permalink":"/portfolio/2023-accounting_reconcilliation_uber/","section":"Portfolio","summary":"As a Data Analyst at NECTO Systems, I played a key role in a project focused on addressing accounting reconciliation challenges for our client, Uber. I developed a customized data engineering solution, leveraging tools such as SQL, Python, Pandas, Hive, and Presto to create an automated pipeline for data retrieval and reconciliation. This project successfully reconciled financial reports for two of the Uber’s business lines, ensuring compliance with global standards and significantly improving the efficiency and reliability of their accounting and tax processes.","title":"Accounting reconcilliation project for Uber","type":"portfolio"},{"content":"Challenge\nWorking with one of the largest online education providers in Brazil, Hashtag Treinamentos, with over 80,000 students trained in their courses, the challenge was to develop video and written materials for Python and Data Science courses to ensure a high-quality learning experience.\nFeatures usually related to Learning Management Systems and e-Learning Solution\nUpon embracing this pivotal role, my initial endeavor was to thoroughly understand the learning objectives and expectations of both the institution and the students. This entailed engaging in discussions with the curriculum development team and analyzing feedback from previous courses. With this foundational understanding, I commenced the development and rigorous review of teaching materials. This meticulous process involved not only crafting the content but ensuring it was pedagogically sound, engaging, and aligned with the latest industry standards.\nA significant portion of the teaching materials was dedicated to covering core Python libraries indispensable for data science pursuits, such as NumPy, Pandas, Matplotlib, Seaborn, Scikit-Learn, TensorFlow, PyTorch, and Plotly. The goal was to demystify complex concepts and provide a hands-on approach to learning through practical examples and real-world applications.\nTo augment the learning experience further, I produced and narrated a series of educational videos on Python. These videos were meticulously designed to break down complex topics into digestible segments, and were disseminated not only on the company\u0026rsquo;s e-learning platform but also on various social media channels, expanding the reach and impact of the educational content.\nResults\nOne of the hallmark initiatives was the integration of real-world projects into the curriculum. This was driven by the aspiration to bridge the gap between theoretical knowledge and practical market scenarios. By doing so, students were endowed with a pragmatic understanding and experience of industry-relevant challenges and solutions, which is quintessential for their career readiness and success.\nFurthermore, the materials I engineered proved to be instrumental in facilitating the learning journey for thousands of students on the company’s educational platform. This significant contribution resonates with the company\u0026rsquo;s overarching mission of delivering high-quality education and has left a lasting impact on the educational trajectory of many aspiring data scientists and programmers.\nThroughout this journey, I continually fostered a stimulating learning environment. By providing continuous support, feedback, and additional resources to students, I ensured their success and comprehension of complex topics. The open channel of communication also allowed for the iterative improvement of the course materials, thereby elevating the overall learning experience.\nThe endeavor at Hashtag Treinamentos not only honed my skills in curriculum development and educational content creation but also enriched my understanding of the diverse learning needs and aspirations of students in the realm of Python and Data Science.\nProject Showcase # In my pursuit to provide a practical, hands-on learning experience, I\u0026rsquo;ve initiated a section dedicated to showcasing the real-world projects integrated into the curriculum. These projects are meticulously designed to emulate real-world scenarios, ensuring students gain pragmatic insights and hands-on experience essential for the modern job market.\nOptimizing Marketing Campaigns Project # Explore the project\nThis project is rooted in a real recruitment challenge posed by iFood, a notable company in Brazil, simulating a scenario from a well-established retail food company. It encompasses a comprehensive exploratory analysis, customer segmentation, and a classification model to predict customer responses to marketing campaigns. The project is structured to mimic a real-world data analyst selection process, offering students a pragmatic insight into data preprocessing, exploratory analysis, and presenting findings to both technical and non-technical audiences. The repository is structured with data, images, notebooks, and reports folders, illustrating a well-organized data science project workflow. Through this project, students also learn good programming practices in Python, utilizing libraries like Scikit-Learn for building and optimizing models.\nCredit Card Fraud Detection Project # Explore the project\nThis project is centered around the detection of fraudulent credit card transactions, which is a critical challenge faced by financial institutions worldwide. The project involves data preprocessing, exploratory data analysis, and the development of a classification model to identify fraudulent transactions. The dataset used in this project is highly imbalanced, reflecting the real-world scenario of credit card fraud detection. By working on this project, students gain a profound understanding of handling imbalanced datasets, feature engineering, and model evaluation techniques. The project is structured with a detailed notebooks and reports, guiding students through the entire data science project lifecycle.\nCustomer Churn Prediction Project # Explore the project\nThis project revolves around predicting customer churn, a critical challenge faced by companies across various industries. The project entails data preprocessing, exploratory data analysis, and the development of a classification model to predict customer churn. The dataset used in this project is sourced from a telecommunications company, providing students with a real-world scenario to work on. By engaging with this project, students gain practical experience dealing with categorical variables and their encoding, feature scaling, and model evaluation techniques. The project is structured with notebooks and reports, guiding students through the entire data science project lifecycle.\nCalifornia Housing Prices Project # chicolucio/california-housing Jupyter Notebook 0 0 This project explores the use of machine learning to predict housing prices in California based on demographic, geographic, and real estate-related features. By combining regression models with geospatial analysis, the goal is to generate accurate, interpretable, and actionable predictions. The dataset comes from the 1990 California census and includes information about population, housing age, income levels, location coordinates, and proximity to the ocean. Although the original data is dated, it offers a rich context for building a complete data science workflow—from preprocessing to deployment. The model is deployed in a simple interactive Streamlit application that allows users to select a county, set demographic and housing parameters, and get real-time price estimates powered by the trained model.\nSome Lecture Notes # While the projects above are designed to provide a hands-on learning experience, the following lecture notes are aimed at enhancing the theoretical understanding of key concepts in Machine Learning and Data Science.\nMetrics for Binary Classification with Imbalanced Datasets Understanding Logistic Regression Coefficients Stay tuned as more projects are in the pipeline, aimed at further bridging the theoretical-practical gap, and will be shared here once finalized.\n","externalUrl":null,"permalink":"/portfolio/2023-hashtag_treinamentos/","section":"Portfolio","summary":"Working with one of the largest online education providers in Brazil, with over 80,000\nstudents trained in their courses, the challenge was to develop video and\nwritten materials for Python and Data Science courses to ensure a high-quality\nlearning experience.","title":"Enhancing Online Education - Python and Data Science Instructor","type":"portfolio"},{"content":" Abstract # Effective marketing relies on targeting the right customers. This project analyzes a retail food company’s direct marketing campaign, which suffered a low response rate (15%) and financial loss. Using data-driven strategies, we optimized future campaigns through customer segmentation, predictive modeling, and profit analysis.\nCustomers were grouped into five segments using RFM analysis, revealing that high-value customers (Valuable \u0026amp; Elite segments) were significantly more likely to convert. A logistic regression model identified key purchase drivers, showing that Elite customers were over 140 times more likely to buy than Dormant customers.\nProfit analysis determined the optimal targeting threshold (0.27), increasing the conversion rate from 15% to 32.5% and turning losses into a projected 3,722 MU gain. This study highlights how data-driven marketing can improve efficiency, reduce costs, and maximize returns, providing actionable insights for businesses looking to optimize their campaigns.\nThe dataset and the project notebooks, with all the code, can be seen on the following GitHub repository:\nchicolucio/marketing-campaign-optimization Turning data into smarter marketing — prediction of customer behavior to maximize profit Jupyter Notebook 2 1 Introduction # Marketing campaigns are a critical component of business growth, but their success hinges on targeting the right customers. The case study presented here focuses on a real-world scenario where a retail food company launched a direct marketing campaign that resulted in a low response rate and financial loss. Leveraging data-driven strategies, we aim to optimize future campaigns by identifying key customer segments, predicting purchase behavior, and maximizing profitability.\nThe methodology involves:\nData cleansing and preprocessing to refine the dataset for analysis. Exploratory data analysis to understand customer behavior and past campaign responses. Customer segmentation based on RFM analysis to identify distinct behavioral patterns. Predictive modeling to forecast customer responses. Profit analysis to determine the optimal targeting strategy for future campaigns. Recommendations for marketing teams to enhance campaign effectiveness. The dataset and the project notebooks, with all the code, can be seen on the following GitHub repository:\nchicolucio/marketing-campaign-optimization Turning data into smarter marketing — prediction of customer behavior to maximize profit Jupyter Notebook 2 1 The company context # The dataset consists of customer information, purchase history, and responses to past marketing campaigns of a retail food company. Let\u0026rsquo;s understand the company context first.\nThey sell products from 5 major categories: wines, rare meat products, exotic fruits, specially prepared fish and sweet products. These can further be divided into gold and regular products. The customers can order and acquire products through 3 sales channels: physical stores, catalogs and company’s website. Globally, the company had solid revenues and a healthy bottom line in the past 3 years, but the profit growth perspectives for the next 3 years are not promising\u0026hellip; For this reason, several strategic initiatives are being considered to invert this situation. One is to improve the performance of marketing activities, with a special focus on marketing campaigns.\nThe marketing department was pressured to spend its annual budget more wisely. The CMO perceives the importance of having a more quantitative approach when taking decisions, reason why a small team of data scientists was hired with a clear objective in mind: to build a predictive model which will support direct marketing initiatives. Desirably, the success of these activities will prove the value of the approach and convince the more skeptical within the company.\nThe aim of the project # The objective of the team is to build a predictive model that will produce the highest profit for the next direct marketing campaign, scheduled for the next month. The new campaign, sixth, aims at selling a new gadget to the Customer Database.\nTo build the model, a pilot campaign involving 2.240 customers was carried out. The customers were selected at random and contacted by phone regarding the acquisition of the gadget. During the following months, customers who bought the offer were properly labeled. The success rate of the campaign was 15%.\nThe objective of the team is to develop a model that predicts customer behavior and to apply it to the rest of the customer base. Hopefully, the model will allow the company to cherry pick the customers who are most likely to purchase the offer while leaving out the non-respondents, making the next campaign highly profitable. Moreover, apart from maximizing the profit of the campaign, the CMO is interested in understanding the characteristic features of those customers who are willing to buy the gadget.\nUnderstanding the Data # The data set contains socio-demographic and firmographic features about 2.240 customers who were contacted. Additionally, it contains a flag for those customers who responded the pilot campaign, by buying the product.\nThe following features were included in the dataset:\nPersonal Data: ID: Unique customer identifier Year_Birth: Customer\u0026rsquo;s year of birth Education: Customer\u0026rsquo;s education level Marital_Status: Customer\u0026rsquo;s marital status Income: Customer\u0026rsquo;s annual family income Kidhome: Number of children in the customer\u0026rsquo;s household Teenhome: Number of teenagers in the customer\u0026rsquo;s household Dt_Customer: Date the customer enrolled with the company Recency: Number of days since the customer\u0026rsquo;s last purchase Complain: 1 if the customer has complained in the last 2 years, 0 otherwise Product Data MntWines: Amount spent on wine in the last 2 years MntFruits: Amount spent on fruits in the last 2 years MntMeatProducts: Amount spent on meat in the last 2 years MntFishProducts: Amount spent on fish in the last 2 years MntSweetProducts: Amount spent on sweets in the last 2 years MntGoldProds: Amount spent on gold products in the last 2 years Campaign Data NumDealsPurchases: Number of purchases made with a discount AcceptedCmp1: 1 if the customer accepted the offer in the 1st campaign, 0 otherwise AcceptedCmp2: 1 if the customer accepted the offer in the 2nd campaign, 0 otherwise AcceptedCmp3: 1 if the customer accepted the offer in the 3rd campaign, 0 otherwise AcceptedCmp4: 1 if the customer accepted the offer in the 4th campaign, 0 otherwise AcceptedCmp5: 1 if the customer accepted the offer in the 5th campaign, 0 otherwise Response: 1 if the customer accepted the offer in the last (pilot) campaign, 0 otherwise (target) Purchase Location Data NumWebPurchases: Number of purchases made through the company\u0026rsquo;s website NumCatalogPurchases: Number of purchases made using a catalog NumStorePurchases: Number of purchases made directly in stores NumWebVisitsMonth: Number of visits to the company\u0026rsquo;s website in the last month Data cleansing and feature engineering # The dataset was available as a CSV file, which was loaded into a Pandas DataFrame for further analysis. The initial exploration revealed a few missing values, which were dropped from the dataset. Additionally, some features were deemed irrelevant for the analysis and were removed. Outliers were identified and treated accordingly to ensure the integrity of the data.\nSome features were transformed to better represent the customer\u0026rsquo;s behavior, such as the Dt_Customer column, which was converted to the number of days and months since the customer enrolled with the company. This transformation allowed for a more meaningful analysis of the recency feature. Also, the age of the customers was calculated based on their year of birth to provide a more intuitive understanding of the data.\nAs described earlier, the company sells products from 5 major categories, which were represented in the dataset as the amount spent on each category in the past 2 years. The values of these features were summed to create a total amount spent feature, which was used to analyze the customer\u0026rsquo;s purchasing behavior in subsequent steps.\nFinally, the features were divided into numerical and categorical groups for further analysis.\nExploratory Data Analysis # After cleaning and preprocessing the data, an exploratory data analysis was conducted to gain insights into customer behavior and past campaign responses. The analysis included descriptive statistics, distribution plots, and correlation matrices to identify patterns and relationships within the data.\nConcerning the numerical features, it was observed that most features have a right-skewed distribution, indicating that a few customers spend significantly more than the rest. The histograms below show the histograms of these features, using the target variable Response to differentiate between customers who accepted the offer and those who did not. A Response value of 1 indicates that the customer accepted the offer in the pilot campaign, while a value of 0 indicates that the customer did not accept the offer.\nWe see that customers who accepted the offer in the last campaign tend to have higher expenses in most product categories, as well as a higher number of purchases and lower recency values. This suggests that customers who are more engaged with the company are more likely to respond positively to marketing campaigns.\nFor the categorical features, the distribution of education levels, marital status, among others, was analyzed to understand the customer profile. The bar plots below show the distribution of these features based on the Response variable.\nThe analysis revealed that customers with higher education levels and income tend to respond more positively to marketing campaigns. Additionally, customers with partners and those with children in the household are less likely to accept the offer. The age does not seem to have a significant impact on the response rate.\nSome of these relationships were further explored through boxplots:\nWe can see that customers with children tend to have lower incomes therefore, they are less likely to accept the offer. The education level seems to have a significant impact on the income of the customers.\nBesides the visual analysis, statistical tests were performed to identify significant differences between the groups of customers who accepted and did not accept the offer. Mann-Whitney U tests were conducted for numerical features, while chi-square tests were used for categorical features. The results of these tests were used to identify the most relevant features to keep in the dataset for further analysis.\nCustomer Segmentation: Identifying Behavioral Patterns # Customer segmentation is a powerful technique that allows businesses to group customers based on their behavior and preferences. In this project, we used the RFM segmentation methodology.\nRFM analysis is a customer segmentation technique that uses past purchase behavior to divide customers into groups. RFM stands for Recency, Frequency, and Monetary Value.\nRecency: How recently a customer has made a purchase. The more recent the purchase, the higher the score. Frequency: How often a customer makes a purchase. The more frequent the purchase, the higher the score. Monetary Value: How much money a customer spends on purchases. The more money spent, the higher the score. RFM score: A score calculated by combining the three RFM values. RFM segment: A segment of customers with similar RFM scores. There are many ways to calculate the RFM score. The number of groups may vary depending on the business needs, the size of the dataset, and the distribution of the RFM values. Similarly, the way to calculate the RFM score may vary depending on the business needs. And, finally, the segment labels may vary depending on the business needs.\nFor small and medium datasets, it is better to calculate the RFM score as a number. This number can be calculated by summing the three RFM values. Considering a scale of 1 to 5 for each RFM value, the RFM score will be between 3 (1 + 1 + 1 = 3) and 15 (5 + 5 + 5 = 15). So, the number of possible RFM scores is 15 - 3 + 1 = 13. This is the approach we are going to use in this project since our dataset is relatively small.\nIrrespective of the way to calculate the RFM score, the RFM segment is calculated by dividing the RFM score into groups. Each group can be labeled with a name, such as \u0026ldquo;Champions\u0026rdquo;, \u0026ldquo;Loyal Customers\u0026rdquo;, \u0026ldquo;Potential Loyalists\u0026rdquo;, \u0026ldquo;New Customers\u0026rdquo;, \u0026ldquo;At Risk\u0026rdquo;, \u0026ldquo;Can\u0026rsquo;t Lose Them\u0026rdquo;, \u0026ldquo;Hibernating\u0026rdquo;, \u0026ldquo;Lost Customers\u0026rdquo;, etc. The number of groups and the labels may vary depending on the business needs and the distribution of the RFM values. The labels try to describe the behavior of the customers in each group.\nFor instance, in this project, we are going to consider the following RFM score calculation:\nEach RFM value is divided into 5 equal groups, with a score of 1 to 5. The RFM score is calculated by the sum of the three RFM values. The RFM score is divided into 5 segments, that may have different marketing strategies, as follows: 1. Dormant (Score: 3 - 5)\nBehavior: These customers have the lowest engagement. They haven\u0026rsquo;t purchased recently, buy infrequently, and spend little. 2. Occasional (Score: 6 - 7)\nBehavior: Customers in this group make occasional purchases but are not highly engaged. They may have made a few transactions but do not shop consistently. 3. Engaged (Score: 8 - 10)\nBehavior: These customers have moderate engagement. They purchase somewhat frequently, and their spending is stable. 4. Valuable (Score: 11 - 12)\nBehavior: These are high-value customers who purchase often and spend significantly. They have shown consistent engagement. 5. Elite (Score: 13 - 15)\nBehavior: The most valuable customers. They buy frequently, spend a lot, and have remained engaged over time. This segmentation allows for targeted marketing strategies to maximize customer retention and revenue growth.\nThis segmentation was applied to the dataset, and the customers were assigned to one of the five segments based on their RFM scores. The distribution of scores and the number of customers in each score is shown below:\nCustomers were then grouped into the five segments based on their RFM scores. The distribution of customers across the segments is shown below:\nConsidering the median values of the normalized RFM scores, we can plot the distribution of the RFM scores for each segment:\nWe can see that the Elite and Valuable segments are the most important in terms of recency, frequency, and monetary value. These segments represent the ones which are most likely to respond positively to marketing campaigns and generate higher revenue for the company.\nProfiling the Customer Segments # It is always important to understand the characteristics of each customer segment to tailor marketing strategies effectively. One way to do this is by analyzing the key features of each segment and how they differ in terms of engagement and spending. We can create profiles, or personas, for each segment to better understand their behavior and preferences.\nIn order to do this, let\u0026rsquo;s analyze how the numerical and categorical features vary across the five segments. First, we will look at the numerical features:\nAs we can see, the Elite and Valuable segments have higher spending, more frequent purchases, and more recent transactions compared to the other segments. Also, they have a higher income. This indicates that these segments are more engaged with the company and are likely to respond positively to marketing campaigns.\nFor the categorical features, we can use each category as a hue to see how the segments differ in terms of education, marital status, and other characteristics:\nIt is clear that the higher the RFM score the lower the tendency to have children. Also, the most valuable segments have older customers (higher percentages for 46-60 and 61+ age groups) and higher percentages of customers with higher education levels (graduation or higher).\nThe marital status is more evenly distributed among the segments, with no clear pattern.\nWe can as well use the segments as a hue:\nThe findings are consistent with the previous analysis. There is a clear pattern in the distribution of the segments for the number of children, age group, and education level. The marital status is more evenly distributed among the segments.\nWe can now describe our personas or customer profiles for each segment:\nDormant\nDescription: These customers have the lowest engagement. They haven\u0026rsquo;t purchased recently, buy infrequently, and spend little. Marketing Strategy: Reactivation campaigns such as discounts or personalized offers may help re-engage them. Customer Profile: Demographics: Customers with children, younger age group, lower education level, and lower income. Behavior: Low recency, low frequency, low monetary value. Tendency to convert: Lowest. Occasional\nDescription: Customers in this group make occasional purchases but are not highly engaged. They may have made a few transactions but do not shop consistently. Marketing Strategy: Encourage more frequent purchases through targeted promotions or loyalty incentives. Customer Profile: Demographics: Customers with children, younger age group, lower education level, and lower income. Behavior: Mid-range recency, low frequency, low monetary value. Tendency to convert: Mid to low. Engaged\nDescription: These customers have moderate engagement. They purchase somewhat frequently, and their spending is stable. Marketing Strategy: Strengthen the relationship by providing personalized recommendations and exclusive offers. Customer Profile: Demographics: Customers with children, mid-age group, at least graduation as education level, and mid-range income. Behavior: Mid-range recency, mid-range frequency, low monetary value. Tendency to convert: Mid-range. Valuable\nDescription: These are high-value customers who purchase often and spend significantly. They have shown consistent engagement. Marketing Strategy: Maintain their loyalty through rewards programs, premium offers, and early access to promotions. Customer Profile: Demographics: Customers may have children or not, older age group, higher education level, and higher income. Behavior: Mid-range recency, high frequency, high monetary value. Tendency to convert: High. Elite\nDescription: The most valuable customers. They buy frequently, spend a lot, and have remained engaged over time. Marketing Strategy: Focus on VIP treatment, premium experiences, and strong retention strategies to ensure long-term loyalty. Customer Profile: Demographics: Customers probably without children, older age group, higher education level, and higher income. Behavior: Low recency, high frequency, high monetary value. Tendency to convert: Highest. Predicting Customer Responses with Machine Learning # The segmentation analysis provided valuable insights into customer behavior, but to maximize the effectiveness of future marketing campaigns, we need to predict customer responses. This is where machine learning comes into play.\nThe segments identified through RFM analysis can be used as input features, along with the existing customer data, to build a predictive model that forecasts the likelihood of a customer accepting the offer in the next campaign.\nThe Sci-Kit Learn library in Python offers a wide range of machine learning algorithms for classification tasks. For this project, an initial evaluation of several models was conducted with the following models:\nDummy Classifier (Baseline) Logistic Regression Decision Tree LightGBM Support Vector Machine K-Nearest Neighbors Since the target variable is imbalanced, with only 15% of customers accepting the offer in the pilot campaign, the parameter class_weight='balanced' was used to account for this imbalance in the models that support it.\nThe preprocessing steps included one-hot encoding and ordinal encoding for the categorical features, and standard and power transformations for the numerical features (only for the non-tree-based models).\nA stratified 5-fold cross-validation was used to evaluate the models\u0026rsquo; performance. The evaluation metrics considered were accuracy, precision, recall, F1-score, AUROC, and AUPRC. The time to train and predict was also considered. The results are summarized in the performance comparison chart below:\nThe choice of the best model should consider some factors:\nThe metrics: which model has the best performance in the metrics that are most important for the business; The time: the model that has the best performance in the metrics and the lowest time should be chosen; The interpretability: some models are more interpretable than others. If interpretability is important, the model that is easier to interpret should be chosen. It happens that the best model in terms of metrics is not always the best model in terms of time or interpretability. So, the choice of the best model should consider all these factors.\nConcerning the metrics, some literature suggests that the area under the precision-recall curve (AUPRC, represented as average_precision on Scikit-Learn) is a better metric for imbalanced datasets than the area under the ROC curve (AUROC, or roc_auc). This is because the ROC curve is not sensitive to changes in the false positive rate when the true positive rate is high. The precision-recall curve, on the other hand, is sensitive to changes in the false positive rate when the true positive rate is high. I\u0026rsquo;ve written an article about this topic, which can be seen here.\nWe can see that the logistic regression model has the best performance in terms of the chosen metric and is also one of the fastest models. Besides, it is a very interpretable model. So, we chose the logistic regression model for this project.\nThe chosen model was then fine-tuned using grid search to optimize the hyperparameters.\nThe final model had the following metrics:\nMetric Mean Std Dev Accuracy 0.819 0.006 Balanced Accuracy 0.817 0.020 F1 0.576 0.019 Precision 0.445 0.009 Recall 0.814 0.042 ROC AUC 0.898 0.011 Average Precision 0.669 0.028 We see that our model highly favors recall in detriment of precision. This is because the model is giving more importance to the conversion class, which is the minority class. It seems fine, as we are more interested in capturing the conversion cases.\nThe coefficients of the logistic regression model can provide insights into which factors influence the likelihood of a customer accepting the offer. The coefficients can be transformed into odds ratios to understand the impact of each feature on the target variable. Below is a chart showing the odds ratios of the features:\nUsing MntMeatProducts as an example for a numerical feature, we see that the odds ratio is ~4.47. This means that a one-unit increase in the MntMeatProducts feature multiplies the odds of the target variable by 4.47. This corresponds to a 347% increase in the odds (i.e., the odds become 4.47 times larger).\nFor HasAcceptedCmp_1, a binary feature, we have to consider that we have set the OneHotEncoder to drop the first category when dealing with binary features. So, the reference category is the category that was dropped. In this case, the reference category is 0, that is why there is not HasAcceptedCmp_0 in the coefficients list. The odds ratio is ~1.42. This means that customers who have accepted at least one previous campaign have 1.42 times the odds of converting compared to customers who have not accepted any campaign.\nFinally, considering now a multi-class feature, Segment. We have set the OneHotEncoder to drop the first category only for binary features. Since Segment has 5 categories, we have 5 coefficients. It is easier to interpret the odds ratio of a multi-class feature by comparing the odds ratio of each category to a reference category. This can be done dividing the odds ratio of each category by the odds ratio of the reference category. Let\u0026rsquo;s consider the Dormant category as the reference category. The odds ratio of the Dormant category is 1.\n$$ \\text{Relative Odds Ratio} = \\frac{\\text{Odds Ratio of Segment}}{\\text{Odds Ratio of Lowest Segment (Dormant)}} $$Applying this to your data:\nSegment Absolute Odds Ratio Adjusted (Relative to Dormant) Dormant 0.0619 1.00 (Baseline) Occasional 0.3161 \\(\\frac{0.3161}{0.0619} = 5.11\\) Engaged 1.2011 \\(\\frac{1.2011}{0.0619} = 19.40\\) Valuable 3.9805 \\(\\frac{3.9805}{0.0619} = 64.28\\) Elite 8.8405 \\(\\frac{8.8405}{0.0619} = 142.76\\) Occasional customers are 5.1 times more likely to convert compared to Dormant customers. Engaged customers are 19.4 times more likely than Dormant customers. Valuable customers are 64.3 times more likely than Dormant customers. Elite customers are 142.8 times more likely than Dormant customers. These are important insights that can help the marketing team to focus on the most valuable customers and improve the conversion rate. The figures are quite impressive, showing that the segmentation of customers is a powerful tool to predict the probability of conversion.\nMaximizing Campaign Profitability # We have already built a model that predicts the probability of a customer buying the gadget. Also, we have already segmented our customers. Now, we will use this model to predict the profit of the campaign, aiming to maximize it.\nThe profit of the campaign is given by the formula:\n$$ \\text{Profit} = \\text{Number of customers} \\times \\text{Probability of buying} \\times \\text{Revenue} - \\text{Number of customers} \\times \\text{Cost} $$Where:\nNumber of customers: the number of customers that we target in the campaign Probability of buying: the probability of a customer buying the gadget Revenue: the revenue that we get from selling the gadget Cost: the cost of the campaign Profit: the profit of the campaign From the problem description, we know that:\nThe revenue from selling the gadget is 11 The cost of the campaign is 3 We can use our model to predict the probability of each customer buying the gadget. Then, we will search for a threshold that maximizes the profit of the campaign. We will try different thresholds and calculate the profit for each one. We will choose the threshold that gives us the highest profit.\nWhat is the threshold? The threshold is the probability above which we will consider a customer as a buyer. For example, if the threshold is 0.5, we will consider that a customer is a buyer if the probability of buying is greater than 0.5. If the threshold is 0.7, we will consider that a customer is a buyer if the probability of buying is greater than 0.7.\nWhy do we need to choose a threshold? Because the model gives us the probability of a customer buying the gadget, not a binary answer. We need to choose a threshold to convert the probability into a binary answer (buyer or not buyer).\nIf our threshold is too low, we will consider many customers as buyers, but many of them will not buy the gadget. Our cost will be high (many customers targeted), but our revenue will be low (few customers buying the gadget).\nIf our threshold is too high, we will consider few customers as buyers (low cost), and even considering that all of them will buy the gadget, our revenue will also be low (few customers buying the gadget).\nWe need to find a balance between these two situations.\nFor each threshold, we are going to calculate:\nthe number of customers that we target in the campaign the expected conversion (probability of buying, we will consider as the sum of the probabilities of the customers that we target) the conversion rate (expected conversion divided by the number of customers that we target) the expected revenue (expected conversion times the revenue) the expected cost (number of customers that we target times the cost) the profit (expected revenue minus expected cost) We can then plot the profit as a function of the threshold. The threshold that gives us the highest profit is the optimal threshold. The chart below shows the profit as a function of the threshold:\nThe optimal threshold is 0.27. This threshold gives us the highest profit for the campaign, with a profit of 3722.18.\nUsing this threshold, we can have a look at the selected customers (those with a probability of buying equal or greater than 0.27) and see the segments they belong to. The table below shows the conversion rates per segment at the optimal threshold:\nSegment Conv. Rate Selected Cust. Cum. % of Total Converted Cust. Cum. % Converted Dormant 0.231 26 1.2 6 0.6 Occasional 0.218 119 6.6 25 3.2 Engaged 0.275 309 20.6 84 11.9 Valuable 0.336 271 32.9 91 21.3 Elite 0.452 239 43.7 108 32.5 We see that this threshold takes 43.7% of the original customers of our dataset. This is good, as we are not targeting too few customers (which would decrease our revenue) or too many customers (which would increase our cost).\nFrom the selected customers, we converted 32.5% of them into buyers. This is a good conversion rate, as it is higher than the conversion rate of pilot campaigns (15 %). So the segmentation and the model are working well. Also, the conversion rate per segment is higher than the conversion rate of the pilot campaign.\nMost of the selected customers are in segments \u0026ldquo;Valuable\u0026rdquo; and \u0026ldquo;Elite\u0026rdquo;. These are the segments that we are most interested in targeting, as they are the most likely to buy the gadget (higher conversion rate).\nWe can plot the conversion rates per segment at the optimal threshold:\nAnother interesting result is that every segment has a higher conversion rate than the pilot campaign. The pilot campaign had a conversion rate of 15%, and all segments have a conversion rate higher than 15%.\nWe can think of this as the following: without the model, if we targeted all customers, randomly, we would have a conversion rate of 15%. With the model, we can target only 43.7% of the customers and have a conversion rate of 32.5%. This is a significant improvement. More, each segment has a conversion rate higher than 15%. So, even segments with lower conversion rates are better than the pilot campaign.\nA formal way of saying the above statement is that the model lifts the conversion rate of the campaign. The lift is the ratio between the conversion rate of the campaign with the model and the conversion rate of the campaign without the model. We can calculate the lift for each segment based on the conversion rate of the pilot campaign and the overall lift:\nWe see that all segments have a lift higher than 1, which means that the model is improving the conversion rate of the campaign. The overall lift is 2.15, which means that the model is improving the conversion rate of the campaign by 115%. The lift is even higher for the segments \u0026ldquo;Valuable\u0026rdquo; and \u0026ldquo;Elite\u0026rdquo;, which are the segments that we are most interested in targeting.\nKey Takeaways and Business Impact # This project demonstrated how data-driven strategies can significantly enhance the effectiveness of marketing campaigns. By leveraging customer segmentation and predictive modeling, we identified high-value customers, optimized targeting strategies, and improved campaign profitability.\nMain Insights from the Analysis # Customer behavior varies significantly by segment\nCustomers were successfully segmented using RFM analysis into Dormant, Occasional, Engaged, Valuable, and Elite groups. Higher-value segments (Valuable \u0026amp; Elite) exhibit more frequent purchases, higher spending, and greater engagement with previous campaigns. Predictive modeling improves campaign efficiency\nA logistic regression model was trained and fine-tuned to predict customer responses. Key factors influencing purchase behavior included past campaign engagement, spending habits, and recency of purchases. The model was able to identify customers up to 142 times more likely to convert compared to the least engaged segment. Data-driven targeting leads to higher profitability\nThe optimal decision threshold (0.27) increased the conversion rate from 15% to 32.5% while reducing the number of customers contacted. The campaign profit, which was negative in the pilot test, was optimized to a projected 3,722 MU gain. Every customer segment performed better than the original pilot campaign when targeted using model predictions. How These Findings Improve Future Campaigns # More precise targeting: By focusing on high-potential customers, marketing teams can reduce costs while increasing conversion rates. Better budget allocation: Resources can be directed towards segments with the highest expected return, maximizing overall profitability. Personalized marketing: Understanding customer segments allows for tailored promotions that align with specific behaviors and preferences. Data-driven decision-making: Predictive analytics can help forecast campaign performance and refine strategies over time. Actionable Recommendations for Marketing Teams # 📌 Leverage customer segmentation\nDevelop targeted messaging and promotions for Valuable and Elite segments, as they have the highest likelihood of conversion. Design reactivation campaigns for Dormant and Occasional customers to increase engagement. 📌 Use predictive modeling to refine campaign targeting\nApply machine learning models to predict customer responses and focus marketing efforts on the most promising prospects. Optimize decision thresholds based on profitability rather than simple conversion rates. 📌 Incorporate profitability analysis into marketing strategy\nRegularly analyze profit vs. targeting threshold to balance reach and expected return. Continuously monitor campaign performance and adjust strategies accordingly. 📌 Experiment with personalized offers\nTailor promotions based on customer purchase history and engagement level to increase response rates. Test different pricing strategies for higher- and lower-engagement customer groups. Final Thoughts # This case study highlights the transformative power of data in marketing decision-making. By combining segmentation, predictive modeling, and profit analysis, businesses can enhance efficiency, improve customer engagement, and maximize returns. Companies that adopt these strategies will gain a competitive advantage in customer retention and revenue growth.\nSee the full project in the GitHub repository.\nLinkedIn GitHub Portfolio ","externalUrl":null,"permalink":"/portfolio/2025-marketing-case/","section":"Portfolio","summary":"Marketing campaigns play a crucial role in business growth, but their success depends\non targeting the right customers. In this project, I analyzed a real-world case where\na retail food company launched a direct marketing campaign that resulted in a low\nresponse rate and financial loss.","title":"Optimizing marketing campaigns with data","type":"portfolio"},{"content":" Introduction: understanding logistic regression coefficients # Logistic regression is one of the most widely used techniques for classification problems. It is particularly useful when the goal is to predict a binary outcome, such as whether a customer will purchase a product, whether a patient has a disease, or whether an email is spam. However, while the mathematical framework behind logistic regression is relatively simple, interpreting its coefficients is not as straightforward as in linear regression.\nUnlike linear regression, where coefficients represent direct changes in the dependent variable, logistic regression operates in the log-odds space. This means that each coefficient describes the effect of an independent variable on the logarithm of the odds of the event occurring, rather than on the probability itself. To derive meaningful insights, we need to understand how these coefficients translate into odds ratios, which provide a more intuitive interpretation of the model’s outputs.\nIn this article, we will break down the meaning of logistic regression coefficients step by step. We will explore key concepts such as odds, log-odds, and odds ratios, and show how to interpret model outputs correctly. We will also illustrate these ideas with examples, making it easier to understand how changes in predictors impact the likelihood of an event.\nBy the end of this article, you will have a clear understanding of:\nWhat logistic regression coefficients represent, How to compute and interpret odds ratios, The difference between odds, probability, and log-odds, Why a unit increase in a predictor does not lead to a linear probability change. Let’s dive into the fundamentals of logistic regression coefficients and their interpretation.\nOdds, Log-Odds, and Odds Ratios in Logistic Regression # The coefficients \\(w_i\\) in logistic regression are not interpreted in the same way as in linear regression. Instead, they represent the logarithm of the odds ratio associated with each predictor variable. This means that a one-unit increase in a variable does not correspond to a linear increase in probability but rather to a multiplicative change in the odds.\nOdds: The ratio between the probability of an event occurring and the probability of it not occurring.\n$$ \\text{Odds} = \\frac{\\text{Probability of Event}}{1 - \\text{Probability of Event}} $$ Odds Ratio (OR): A measure of how much the odds change for a one-unit increase in an independent variable.\nCoefficient (\\(w_i\\)): Represents the change in log-odds of the outcome for each unit increase in \\(X_i\\).\n$$ \\text{Log-Odds} = w_0 + w_1X_1 + w_2X_2 + \\dots + w_nX_n $$ Interpreting the log-odds:\nValue \u0026gt; 0: Increases the log-odds of the event occurring. Value = 0: Does not change the log-odds. Value \u0026lt; 0: Decreases the log-odds of the event occurring. To interpret the coefficients in a more intuitive way, we take the exponential of the coefficient:\n$$ \\text{Odds Ratio} = e^{w_i} $$ Interpreting the Odds Ratio: Value \u0026gt; 1: Increases the odds of the event occurring. Value = 1: Does not change the odds. Value \u0026lt; 1: Decreases the odds of the event occurring. Simple Example: Modeling Disease Probability # Suppose we are modeling the probability of a person having a disease based on their age and smoking status.\n$$ \\text{Log-Odds} = w_0 + w_1 (\\text{Age}) + w_2 (\\text{Smoker}) $$With the following estimated coefficients:\n\\(w_0 = -2\\) \\(w_1 = 0.05\\) \\(w_2 = 1.5\\) Age Coefficient (\\(w_1 = 0.05\\), continuous variable):\nLog-Odds: For each additional year of age, the log-odds of having the disease increase by 0.05. Odds Ratio: \\(e^{0.05} \\approx 1.051\\) Interpretation: Each additional year of age increases the odds of having the disease by approximately 5.1%.\n(This does not mean the probability increases by 5.1%—the effect is nonlinear.) Smoker Coefficient (\\(w_2 = 1.5\\), categorical variable):\nLog-Odds: If a person is a smoker (\\(X_2 = 1\\)), the log-odds of having the disease increase by 1.5 compared to non-smokers (\\(X_2 = 0\\)). Odds Ratio: \\(e^{1.5} \\approx 4.48\\) Interpretation: Smokers have 4.48 times the odds of having the disease compared to non-smokers. Converting Odds to Probability # To make the result more interpretable, we can convert odds to probability:\n$$ P = \\frac{\\text{Odds}}{1 + \\text{Odds}} $$For example, if a non-smoker has an estimated probability of disease \\(P_0\\), a smoker’s probability can be found by multiplying the odds by 4.48 and then applying the formula above.\nLet\u0026rsquo;s calculate the probabilities for a 40-year-old non-smoker and a 40-year-old smoker using the coefficients provided.\nCase 1: A 40-year-old non-smoker (\\(X_2 = 0\\)) # Compute log-odds:\n$$ \\text{Log-Odds} = -2 + (0.05 \\times 40) + (1.5 \\times 0) $$$$ \\text{Log-Odds} = -2 + 2 = 0 $$ Compute odds:\n$$ \\text{Odds} = e^0 = 1 $$ Compute probability:\n$$ P = \\frac{1}{1 + 1} = \\frac{1}{2} = 0.5 $$ Interpretation: A 40-year-old non-smoker has a 50% probability of having the disease.\nCase 2: A 40-year-old smoker (\\(X_2 = 1\\)) # Compute log-odds:\n$$ \\text{Log-Odds} = -2 + (0.05 \\times 40) + (1.5 \\times 1) $$$$ \\text{Log-Odds} = -2 + 2 + 1.5 = 1.5 $$ Compute odds:\n$$ \\text{Odds} = e^{1.5} \\approx 4.48 $$ Compute probability:\n$$ P = \\frac{4.48}{1 + 4.48} = \\frac{4.48}{5.48} \\approx 0.817 $$ Interpretation: A 40-year-old smoker has an 81.7% probability of having the disease.\nSee that the probability in the smoker case is higher than in the non-smoker case, reflecting the higher odds associated with smoking status. The third step in the calculation shows that the odds ratio of 4.48 translates to a probability increase from 50% to 81.7%. A nonlinear change.\nKey Takeaways # The logistic regression model allows probability estimation by converting log-odds into probabilities. The relationship between predictors and probability is nonlinear — increases in age or smoking status multiply the odds rather than adding a fixed percentage to probability. The model outputs a probability between 0 and 1, which makes logistic regression suitable for classification tasks. More advanced example: marketing campaign success prediction # In a more complex scenario, we might model the success of a marketing campaign based on customer demographics, purchase history, and campaign-specific features. The logistic regression model would provide insights into how each feature influences the likelihood of a successful campaign.\nActually, I\u0026rsquo;ve made a project on this topic. You can check it out here. I\u0026rsquo;m going to use the coefficients from that project to illustrate how to interpret the odds ratios in a more realistic setting.\nJust a quick context: the project aimed to predict the success of a marketing campaign based on customer data. The model included features such as age, income, purchase history, and campaign-specific variables. A customer segmentation was performed to understand how different groups responded to the campaign. Five segments were identified: Dormant, Occasional, Engaged, Valuable, and Elite. The features and segments were used to train a regularized logistic regression model. The goal was to understand which factors influence the success of the campaign and predict the likelihood of a customer segment responding positively to the campaign. Conversion was defined as a customer accepting an offer or making a purchase.\nScikit-Learn\u0026rsquo;s LogisticRegression model was used to fit the data. The coefficients from the model are as follows:\nFeature Coefficient one_hot_encoding__Segment_Dormant -2.782 power_transformer__MntWines -1.228 one_hot_encoding__Segment_Occasional -1.152 power_transformer__NumStorePurchases -1.126 power_transformer__MntRegularProds -0.806 one_hot_encoding__HasChildren_1 -0.690 one_hot_encoding__Complain_1 -0.548 power_transformer__MntFishProducts -0.434 ordinal_encoding__AgeGroup -0.043 power_transformer__MntFruits -0.026 power_transformer__MntSweetProducts -0.019 standard_scaling__Income -0.016 power_transformer__MntGoldProds 0.055 one_hot_encoding__Segment_Engaged 0.183 ordinal_encoding__Children 0.212 power_transformer__NumWebPurchases 0.256 one_hot_encoding__HasAcceptedCmp_1 0.352 power_transformer__NumCatalogPurchases 0.446 ordinal_encoding__Education 0.458 standard_scaling__MonthsSinceEnrolled 1.017 one_hot_encoding__Marital_Status_Single 1.142 one_hot_encoding__Segment_Valuable 1.381 power_transformer__MntMeatProducts 1.498 ordinal_encoding__AcceptedCmpTotal 1.573 one_hot_encoding__Segment_Elite 2.179 As can be seen, the categorical features underwent one-hot encoding or ordinal encoding, while the numerical features were scaled or transformed. The coefficients represent the effect of each feature on the log-odds of a customer segment responding positively to the campaign.\nThe coefficients are the weights that the model assigns to each feature. The higher the absolute value of the coefficient, the more important the feature is in predicting the probability of conversion. The sign of the coefficient indicates the direction of the relationship between the feature and the target variable. A positive coefficient means that the feature has a positive impact on the probability of conversion, while a negative coefficient means that the feature has a negative impact on the probability of conversion.\nWe can summarize the coefficients and their impact on the probability of conversion as follows:\n\\(w_i \u003e 0\\): Feature has a positive impact on the probability of conversion. \\(w_i \u003c 0\\): Feature has a negative impact on the probability of conversion. \\(w_i = 0\\): Feature has little or no impact on the probability of conversion. So, we clearly see that:\nElite segment has the highest positive impact on the probability of conversion; The more accepted offers a customer has, the higher the probability of conversion; Customers which expend more on meat products have a higher probability of conversion; Dormant segment has the highest negative impact on the probability of conversion; Customers which expend more on wine products have a lower probability of conversion. Features with zero or near-zero coefficients have little or no impact on the probability of conversion. We are using a regularized logistic regression model, which means that the model is penalized for having too many features. This is why some features have zero or near-zero coefficients. The model is trying to reduce the number of features to make the model simpler and more interpretable. Then, we can see that the following features have little or no impact on the probability of conversion:\ngold products; income; sweet and fruit products; age group; Again, this does not mean that these features are not important. It means that the model is trying to reduce the number of features to make the model simpler and more interpretable. The remaining features are the most important features in predicting the probability of conversion.\nThe odds ratio is a more intuitive measure than the log-odds, as it represents the change in the odds of the target variable for a one-unit change in the feature. An odds ratio greater than 1 means that the feature has a positive impact on the probability of conversion, while an odds ratio less than 1 means that the feature has a negative impact on the probability of conversion.\nHere are the odds ratios for the features in the model:\nFeature Odds Ratio one_hot_encoding__Segment_Dormant 0.062 power_transformer__MntWines 0.293 one_hot_encoding__Segment_Occasional 0.316 power_transformer__NumStorePurchases 0.324 power_transformer__MntRegularProds 0.447 one_hot_encoding__HasChildren_1 0.502 one_hot_encoding__Complain_1 0.578 power_transformer__MntFishProducts 0.648 ordinal_encoding__AgeGroup 0.958 power_transformer__MntFruits 0.975 power_transformer__MntSweetProducts 0.981 standard_scaling__Income 0.984 power_transformer__MntGoldProds 1.056 one_hot_encoding__Segment_Engaged 1.201 ordinal_encoding__Children 1.236 power_transformer__NumWebPurchases 1.292 one_hot_encoding__HasAcceptedCmp_1 1.422 power_transformer__NumCatalogPurchases 1.562 ordinal_encoding__Education 1.582 standard_scaling__MonthsSinceEnrolled 2.765 one_hot_encoding__Marital_Status_Single 3.132 one_hot_encoding__Segment_Valuable 3.980 power_transformer__MntMeatProducts 4.472 ordinal_encoding__AcceptedCmpTotal 4.822 one_hot_encoding__Segment_Elite 8.840 When interpreting the odds ratios, we can say that:\nAn odds ratio greater than 1 means that the feature has a positive impact on the probability of conversion. An odds ratio less than 1 means that the feature has a negative impact on the probability of conversion. An odds ratio equal to 1 means that the feature has no impact on the probability of conversion. Using MntMeatProducts as an example for a numerical feature, we see that the odds ratio is ~4.47. This means that a one-unit increase in the MntMeatProducts feature multiplies the odds of the target variable by 4.47. This corresponds to a 347% increase in the odds (i.e., the odds become 4.47 times larger).\nFor HasAcceptedCmp_1, a binary feature, we have to consider that we have set the OneHotEncoder to drop the first category when dealing with binary features. So, the reference category is the category that was dropped. In this case, the reference category is 0, that is why there is not HasAcceptedCmp_0 in the coefficients list. The odds ratio is ~1.42. This means that customers who have accepted at least one previous campaign have 1.42 times the odds of converting compared to customers who have not accepted any campaign.\nFinally, considering now a multi-class feature, Segment. We have set the OneHotEncoder to drop the first category only for binary features. Since Segment has 5 categories, we have 5 coefficients. It is easier to interpret the odds ratio of a multi-class feature by comparing the odds ratio of each category to a reference category. This can be done dividing the odds ratio of each category by the odds ratio of the reference category. Let\u0026rsquo;s consider the Dormant category as the reference category. The odds ratio of the Dormant category is 1.\n$$ \\text{Relative Odds Ratio} = \\frac{\\text{Odds Ratio of Segment}}{\\text{Odds Ratio of Lowest Segment (Dormant)}} $$Applying this to your data:\nSegment Absolute Odds Ratio Adjusted (Relative to Dormant) Dormant 0.0619 1.00 (Baseline) Occasional 0.3161 \\(\\frac{0.3161}{0.0619} = 5.11\\) Engaged 1.2011 \\(\\frac{1.2011}{0.0619} = 19.40\\) Valuable 3.9805 \\(\\frac{3.9805}{0.0619} = 64.28\\) Elite 8.8405 \\(\\frac{8.8405}{0.0619} = 142.76\\) Occasional customers are 5.1 times more likely to convert compared to Dormant customers. Engaged customers are 19.4 times more likely than Dormant customers. Valuable customers are 64.3 times more likely than Dormant customers. Elite customers are 142.8 times more likely than Dormant customers. Final Thoughts and Takeaways # Understanding logistic regression coefficients is essential for interpreting the results of a logistic regression model. The coefficients represent the effect of each feature on the log-odds of the target variable. By converting the log-odds to odds ratios, we can interpret the impact of each feature on the probability of the target variable.\nKey takeaways from this article include:\nLogistic regression coefficients represent the change in log-odds of the target variable for a one-unit change in the feature. Odds ratios provide a more intuitive interpretation of the coefficients, showing how a one-unit change in the feature affects the odds of the target variable. Odds ratios greater than 1 indicate a positive impact on the probability of the target variable, while odds ratios less than 1 indicate a negative impact. The relationship between features and the target variable is nonlinear in logistic regression, making it important to interpret the coefficients correctly. Regularized logistic regression models can help simplify the model and identify the most important features for predicting the target variable. Comparing the odds ratios of different categories of a multi-class feature to a reference category can help understand the relative impact of each category on the target variable. I hope this article has provided you with a clear understanding of logistic regression coefficients and how to interpret them. Check out the project on marketing campaign success prediction for a practical application of these concepts. If you have any questions or feedback, feel free to reach out. Happy modeling!\nLinkedIn GitHub Portfolio ","externalUrl":null,"permalink":"/portfolio/2025-logistic-regression-coefficients/","section":"Portfolio","summary":"Logistic regression is a widely used classification algorithm that provides interpretable\nresults. In this article, we delve into the coefficients generated by logistic regression\nmodels and their significance. We explore how these coefficients are calculated, their\nrelationship with the odds ratio, and how they can be interpreted to understand the\nimpact of features on the predicted outcome.","title":"Understanding logistic regression coefficients","type":"portfolio"},{"content":" When discussing models, the question of which metrics should be used to evaluate the comparative performance of models in a given context always arises. The Scikit-Learn documentation provides extensive information on the topic, and Wikipedia has an article specifically about binary classification metrics. Here, we will cover the essential concepts needed to understand how imbalanced datasets affect model evaluation.\nConfusion Matrix # Let’s start by recalling a binary confusion matrix and some important terminology:\nThis terminology is used to define other metrics, such as accuracy, precision, recall, among others.\nAccuracy # The most well-known, and perhaps the most misused, metric is accuracy. For binary classification:\n$$ \\text{accuracy} = \\frac{TP + TN}{TP + TN + FP + FN} $$From the definition above, accuracy measures the fraction of correct predictions over the total predictions. If the dataset is highly imbalanced, where one class is significantly more frequent than the other, high accuracy can be achieved easily. Simply predicting that all instances belong to the majority class would already yield a very high accuracy. If this seems unclear, refer to this article on the accuracy paradox, which describes this phenomenon.\nPrecision and Recall # In imbalanced situations, two other metrics are often used instead of accuracy: precision and recall, defined as follows:\n$$ \\text{precision} = \\frac{TP}{TP + FP} \\qquad \\text{recall} = \\frac{TP}{TP + FN} $$Precision is the fraction of true positives out of all predicted positives, indicating how well the model identifies positive instances. Maximizing precision reduces the number of false positives.\nRecall, on the other hand, measures the fraction of true positives out of all actual positives. Since false negatives are actually positives, recall quantifies the proportion of real positives that were correctly identified. Maximizing recall reduces the number of false negatives.\nDepending on the application, one type of error may be more costly than the other. For example, in medical diagnoses, failing to detect a serious disease (false negative) can be much more harmful than incorrectly flagging a healthy patient for further testing (false positive). In contrast, in some security applications, false positives might be more disruptive, causing unnecessary interventions.\nF-measure # There is a trade-off between precision and recall. Increasing one can lead to a decrease in the other. To balance these two metrics, the F-measure (also called the F-score) is used, which is the harmonic mean of precision and recall:\n$$ \\text{F-measure} = \\frac{2 \\times \\text{precision} \\times \\text{recall}}{\\text{precision} + \\text{recall}} $$ AUROC - Area Under the Receiver Operating Characteristics Curve # We can analyze this trade-off using other metrics. Recall is also known as the true positive rate (TPR). Additionally, we define the false positive rate (FPR) as:\n$$ \\text{FPR} = \\frac{FP}{TN + FP} $$With these two definitions, we can construct a Receiver Operating Characteristics (ROC) Curve, which visualizes the trade-off between benefits (true positives) and costs (false positives) for a given binary classification model:\nROC Curve. Image by cmglee and MartinThoma, CC BY-SA 4.0, via Wikimedia Commons. The metric used to compare different models is the area under the curve (AUC), leading to the common acronym AUROC.\nArea Under the Curve (AUC). Source. The animation below illustrates how a model\u0026rsquo;s behavior changes. Notice how increasing the number of true positives also increases the false positive rate, and how reducing false positives leads to fewer true positives.\nAUROC and class distributions. Source (MIT license). The shape of the ROC curve varies depending on how well the model can correctly classify each class. In the following animation, the class distributions start completely overlapping, meaning the model cannot distinguish between them. In this situation, AUC = 0.5, which is equivalent to a random classifier (a coin toss). As the model becomes better at separating the classes, AUC increases until it reaches a perfect classification (AUC = 1), where the curve forms a right angle.\nAUROC and model’s ability to distinguish classes. Source (MIT license). AUPRC - Area Under the Precision-Recall Curve # AUROC is widely used, especially for selecting models that maximize area under the curve. However, studies in the literature indicate that a better metric exists for imbalanced datasets.\nWe have already seen the definitions of precision and recall and how they involve a trade-off. This trade-off can also be visualized graphically by generating a curve and calculating the area under it, known as the AUPRC (area under precision-recall curve). The following animation illustrates how AUROC and AUPRC behave as a model\u0026rsquo;s ability to distinguish between two classes improves:\nAUROC vs. AUPRC and model’s ability to distinguish classes. Source (MIT license). Both curves respond significantly to changes in classification ability.\nNow, observe the following animations:\nAUROC vs. AUPRC in imbalanced datasets. Source (MIT license). These animations demonstrate the effect of severe class imbalance. Notice that AUROC remains almost unchanged because the ROC curve shape does not significantly alter. However, the Precision-Recall Curve (PRC) shape changes substantially, affecting AUPRC. This is why AUPRC is often recommended when dealing with highly imbalanced datasets.\nConclusion # In this article, we discussed some of the metrics used to evaluate binary classification models in the context of imbalanced datasets. We explored the confusion matrix, accuracy, precision, recall, F-measure, AUROC, and AUPRC, providing a comprehensive overview of the metrics and their implications for model evaluation.\nIt was shown why AUPRC is often recommended for imbalanced datasets, as it is more sensitive to changes in the model\u0026rsquo;s ability to distinguish between classes. Understanding these metrics is vital for assessing model performance and selecting the most appropriate evaluation criteria for a given context.\nLinkedIn GitHub Portfolio ","externalUrl":null,"permalink":"/portfolio/2022-auprc/","section":"Portfolio","summary":"Imbalanced datasets are common in real-world scenarios, and they pose a challenge for\nmachine learning models. In this article, we explore the metrics used to evaluate binary\nclassification models in the context of imbalanced datasets. We discuss the confusion\nmatrix, accuracy, precision, recall, F-measure, AUROC, and AUPRC, providing a\ncomprehensive overview of the metrics and their implications for model evaluation.","title":"Metrics for Binary Classification with Imbalanced Datasets","type":"portfolio"},{"content":" Abstract # Churn is a measure of how many customers stop using a service or product, often evaluated for a specific period of time. One of the biggest difficulties in telecommunication industry is to retain the customers and prevent the churn.\nCustomers in the telecom industry can choose from a variety of service providers and actively switch from one to the next. Acquiring new customers is not only more difficult, but also much more costly to companies than maintaining existing customer relationships. Therefore, many Customer Churn Prediction (CCP) models have been implemented.\nIn this study, a churn level prediction process is carried out using machine learning. A dataset with over 7000 customers of a telecom company is used. An action plan for the company is designed based on the results.\nThe complete dataset, code, and auxiliary files can be found in the project repository on GitHub linked below:\nchicolucio/churn-prediction Predicting customer churn with machine learning Jupyter Notebook 4 0 In this article, we will focus on the methodology used to predict churn and the results obtained. The complete code can be found in the project repository.\nContextualization # The telecom industry, while in a consolidation phase in developed markets, is booming in emerging markets [1]. With the increasing variety of service providers, telecom churn has emerged as one of the most important causes of revenue erosion for telecom operators [2]. Then, predicting churners from the demographic and behavioral data of customers has been of great interest. Acquiring new subscribers can cost up to 6 times more than retaining an existing one [3].\nChurn management involves, among many others:\npredicting customers likely to churn preventive actions running marketing campaigns But why do customers churn? [4]\nThere is no unique answer. However, we can think of a few likely causes:\ncustomer no longer values the product motivating factors to use the product no longer exists customer frustrated with product user experience the product lacks a mandatory capability required by the user value to the customer does not justify the expense the customer has switched to an alternative solution damage to product reputation (e.g., cybersecurity issue, performance, etc.) And how can a company reduce churn? [4]\nAgain, there is no silver bullet. But increasing the perceived value proposition of the service to current users is obviously a key point. This can be achieved in several ways, among them:\nmake sure customers get the most out of the product recruit the right kind of customers price based on value continually add value without breaking what already works don\u0026rsquo;t take customers for granted In this study, an IBM dataset will be analyzed. The Telco customer churn data contains information about a telecom company named Telco that provide home phone and internet services to 7043 customers [5]. It indicates which customers have left, stayed, or signed up for their service. Multiple important demographics and services are included for each customer, totaling 20 features. The aim is to predict behavior to retain customers.\nA cross-industry standard process for data mining (CRISP-DM) [6] approach will be used as shown in the figure below.\nProposed methodology flow diagram Each step will be detailed in the appropriate section.\nExploratory Data Analysis (EDA) # As cited before, the dataset contains 7043 entries. There are 21 columns, with 20 features and the target variable Churn. The features are a mix of categorical and numerical data.\nEach row represents a customer, and each column contains the customer\u0026rsquo;s attributes, as described below. The dataset includes information about:\nCustomers who left within the last month: Churn: Yes = the customer left the company within the last month. No = the customer remained with the company. Customers\u0026rsquo; demographic info: gender: customer\u0026rsquo;s gender: Male, Female SeniorCitizen: customer is 65 or older: 1, 0 (meaning Yes and No, respectively) Partner: customer is married: Yes, No Dependents: customer lives with any dependents: Yes, No. Dependents could be children, parents, grandparents, etc. Services that each customer has signed up for: PhoneService: customer subscribes to home phone service with the company: Yes, No MultipleLines: customer subscribes to multiple telephone lines with the company: Yes, No, No internet service InternetService: customer subscribes to Internet service with the company: No, DSL, Fiber Optic OnlineSecurity: customer subscribes to an additional online security service provided by the company: Yes, No, No internet service OnlineBackup: customer subscribes to an additional online backup service provided by the company: Yes, No, No internet service DeviceProtection: customer subscribes to an additional device protection plan for their Internet equipment provided by the company: Yes, No, No internet service TechSupport: customer subscribes to an additional technical support plan from the company with reduced wait times: Yes, No, No internet service StreamingTV: customer uses their Internet service to stream television programming from a third-party provider: Yes, No, No internet service StreamingMovies: customer uses their Internet service to stream movies from a third-party provider: Yes, No, No internet service Customer account information: tenure: total number of months that the customer has been with the company. Contract: customer\u0026rsquo;s current contract type: Month-to-Month, One Year, Two Year. PaperlessBilling: customer has chosen paperless billing: Yes, No PaymentMethod: how the customer pays their bill: Electronic check, Credit Card, Mailed Check, Bank transfer MonthlyCharge: customer\u0026rsquo;s current total monthly charge for all their services from the company TotalCharges: customer\u0026rsquo;s total charges, calculated to the end of the quarter Finally, each customer has a CustomerID, a unique ID that identifies the customer. Let\u0026rsquo;s verify the balance of the target variable Churn:\nClass imbalance A little more than one quarter of the customers left the company in the last month. A high number that we need to understand. The dataset is imbalanced, and this will be considered in the evaluation of the models, since some algorithms may have problems with imbalanced datasets [7].\nNumeric features # It is important to check for outliers in the dataset. We can do this by analyzing the distribution of the features. Using boxplots for each feature, we can identify outliers in the data. We can also check the distribution of the features for each class to see if there are differences between them.\nOutliers in the dataset The boxplots show that the churn rate is higher among customers with low tenure and high monthly charges. In details:\nthe median tenure for customers who have left is around 10 months, while it is around 40 months for those who have stayed with the company. So, customers who have churned spent less time with the company. the median monthly charge for customers who have churned is around 80, while it is around 65 for those who have not churned. Therefore, customers who have churned have higher monthly charges. since most customers who have churned spent less time with the company, they have low median total charges compared with those who have stayed There are some outliers in the total charges boxplot of customers who have churned. This shows that some customers who have churned have high total charges, even though they have spent less time with the company. This could be due to high monthly charges. Since the data is consistent, we will keep these outliers. The shape of the distribution of the features is also important. We can check the distribution of the features for each class to see if there are differences between them. This can help us understand the data better and choose the best algorithm to classify the transactions. Let\u0026rsquo;s check the distribution of the features for each class:\nDistribution of the features for each class The tenure distribution has an interesting shape. Most customers have been with the company for just a few months, but also many have been for about 72 months (maximum value for tenure). This is probably related with different contracts, something that we will check soon. Probably some marketing campaign was ran recently to capture new customers due to the high number of customers with few months.\nWe can see that most customers pay low monthly charges, but there is a great fraction with medium values. Since most customers have been with the company for just a few months, the total charges plot shows most customers with low values.\nLet\u0026rsquo;s check if these features distributions have some kind of relation with the kind of contract:\nHistograms of the features by contract type As can be seen, most of the monthly contracts last for a few months, while the 2-year contracts tend to last for years, with a great increase towards the greater values of tenure in this dataset. This implies that customers with a great commitment at the beginning, like a 2-year contract, tend to stay with the company for a longer period of time. Long-term contracts usually have contractual fines. Therefore, customers have to wait until the end of the contract to churn. It is not clear if it is the case. A time-series data would be better to study this.\nWe can further check the relation between the kind of contract and the monthly and total charges with violin plots:\nViolin plot of the Tenure by Contract type. Hue by Churn Violin plots are a combination of boxplots and KDE plots. They show the distribution of the data and the probability density of the different values. We can see that the most contracts are month-to-month and that customers with this kind of contract tend to churn more (larger density of churned customers). Moreover, the churned customers tend to churn earlier, as we saw in the tenure distribution plot.\nWe can check the relation between the kind of contract and the monthly charges:\nViolin plot of the Monthly Charges by Contract type. Hue by Churn Again, it is clear that the month-to-month contracts have higher churn customers. The shape of the distribution for the churned customers has a broad peak towards the higher values of monthly charges. This implies that customers with higher monthly charges tend to churn more. This is probably because they are not satisfied with the service or they found a better deal.\nWe can now check how the type of internet service affects the churn rate:\nViolin plot of the Monthly Charges by Internet Service. Hue by Churn As expected, fiber optic has a higher monthly charge than DSL. This is probably because fiber optic is faster and more reliable. However, the churn rate for fiber optic is also higher. This is most likely because customers are not satisfied with the service, even though it is faster. We don\u0026rsquo;t know when the data was collected, but some customers perhaps didn\u0026rsquo;t think that the additional speed was worth the additional cost.\nCategorical features # For the categorical features, we can check the proportion of each category:\nProportion of each category Some highlights:\nthe dataset is almost equally distributed in terms of gender 55.0 % of the customers have month-to-month contracts 21.7 % of the customers do not have internet service 90.3 % of the customers have phone service there are only 16.2 % senior customers. Thus, most customers are young people (less than 65 years) 48.3% have a partner, but only 30 % have dependents We see that some categorical features have \u0026lsquo;No\u0026rsquo; and \u0026lsquo;No internet service\u0026rsquo; (or \u0026lsquo;No phone service\u0026rsquo;) as categories. Maybe all of them can be labeled as \u0026lsquo;No\u0026rsquo; if the categories provide no additional information. We can check this, plotting the churn rate by category:\nChurn distribution by category Features that seem to be positively correlated with churn:\nmonth to month contracts absence of online backup, online security, and device protection services absence of tech support being a senior citizen paperless billing pay with electronic check internet service by fiber optic Features that seem to be negatively correlated with churn:\ntwo-year contracts absence of internet service having a partner or dependent We will quantify these correlations soon. First, let\u0026rsquo;s try to interpret the findings.\nBoth genders behave similarly when it comes to migrating to another service provider.\nIt is interesting to see that each service that has the \u0026ldquo;No internet service\u0026rdquo; category has much lower churn rates. Maybe the internet service provided by the company has connectivity problems, particularly the fiber optic one. It could also be that the setup is not easy, so that those who opted not to have tech support may not be able to use the services. And that would be more severe in senior customers. While it appears that there are issues with the fiber optic internet, the DSL one has a much lower churn rate despite being a slower connection.\nSince the \u0026ldquo;No internet service\u0026rdquo; category provided insights, it will not be merged with the \u0026ldquo;No\u0026rdquo; category.\nBesides the visual analysis, statistical tests were performed to identify significant differences between the groups of customers who accepted and did not accept the offer. Mann-Whitney U tests were conducted for numerical features, while chi-square tests were used for categorical features. The results of these tests were used to identify the most relevant features to keep in the dataset for further analysis, performing a feature selection [8].\nConsidering the results of the statistical tests and the visual analysis, the following features were dropped: Gender, PhoneService and MultipleLines. Also, the feature TotalCharges was dropped because it is highly correlated with MonthlyCharges and Tenure.\nEvaluating models # After the exploratory data analysis, some models were trained to classify the transactions as fraudulent or not. The models used were:\nDummy Classifier (as a baseline) Logistic Regression Decision Tree LightGBM K-Nearest Neighbors Support Vector Machine for Classification (SVC) A Scikit-Learn pipeline was used to preprocess the data and train the models. The numeric features were preprocessed using power transformations, while the categorical ones were preprocessed using one-hot encoding. Due to the imbalance in the dataset, a stratified 5-fold cross-validation technique was used to train and evaluate the models. Moreover, the class weight parameter was used in the models (if available) to deal with the imbalance.\nScikit-Learn pipeline used to train the models The following metrics were used to evaluate the models:\naccuracy: the proportion of correctly classified samples; balanced_accuracy: the average of the recall of each class; f1: the harmonic mean of precision and recall; precision: the proportion of correctly classified positive samples; recall: the proportion of positive samples that were correctly classified; roc_auc: the area under the ROC curve; average_precision: the area under the precision-recall curve; neg_brier_score: the Brier score, which is the mean squared difference between the predicted probabilities and the actual outcomes. The lower the Brier score, the better the model; f1_weighted: the weighted average of the f1 score, which is the harmonic mean of precision and recall. The f1 score is weighted by the number of samples in each class. We also have some time metrics regarding the training and prediction times, and the total time. The consolidated metrics for each model are shown below as boxplots:\nConsolidated metrics for each model The choice of the best model should consider some factors:\nThe metrics: which model has the best performance in the metrics that are most important for the business; The time: the model that has the best performance in the metrics and the lowest time should be chosen; The interpretability: some models are more interpretable than others. If interpretability is important, the model that is easier to interpret should be chosen. It happens that the best model in terms of metrics is not always the best model in terms of time or interpretability. So, the choice of the best model should consider all these factors.\nConcerning the metrics, some literature [9] suggests that the area under the precision-recall curve (AUPRC, represented as average_precision on Scikit-Learn) is a better metric for imbalanced datasets than the area under the ROC curve (AUROC, or roc_auc). This is because the ROC curve is not sensitive to changes in the false positive rate when the true positive rate is high. The precision-recall curve, on the other hand, is sensitive to changes in the false positive rate when the true positive rate is high. I already covered this in a previous article.\nThe Scikit-Learn docs [10] state that the average_precision_score function from the package can be used as a AUPRC value, so it was the chosen function in this study.\nWe can see that the logistic regression model has the best performance in terms of the chosen metric and is also one of the fastest models. Besides, it is a very interpretable model. So, was chosen as the best model.\nThe logistic regression model was then fine-tuned using a grid search to maximize the average_precision metric. The best hyperparameters found were: penalty='elasticnet', C=0.1, l1_ratio=0.25, solver='saga', and max_iter=2500.\nThe final model has the following metrics:\nMetric Score Std Dev Accuracy 0.752 0.007 Balanced Accuracy 0.766 0.009 F1 0.630 0.011 Precision 0.521 0.009 Recall 0.795 0.018 ROC AUC 0.846 0.012 Average Precision 0.658 0.020 F1 Weighted 0.764 0.006 We see that our model favors recall in detriment of precision. This is fine, as we are more interested in capturing all the customers that are likely to churn, even if we include some false positives.\nModel Interpretability # Model interpretability is an essential factor when selecting a model. It is important to understand how the model makes its predictions.\nSome models are more interpretable than others. For example, decision trees are very interpretable, as we can see the rules that the model uses to make its predictions. On the other hand, models like SVM are not very interpretable, as we cannot see the rules that the model uses to make its predictions.\nThe coefficients of the logistic regression model can give us some insights into the importance of each feature in predicting the probability of churn. Mathematically, the coefficients represent the change in the log-odds of the target variable for a one-unit change in the feature. In other words, the coefficients represent the impact of the feature on the probability of churn.\nOdds are the ratio of the probability of an event happening to the probability of the event not happening. The log-odds are the natural logarithm of the odds. The logistic regression model uses the log-odds to make predictions.\nI have made an article explaining the interpretation of the coefficients of the logistic regression model. You can check it out here. I will briefly explain the interpretation of the coefficients below, but if you want a more detailed explanation, I recommend reading the article.\nFor a numerical feature, the coefficient represents the change in the log-odds of the target variable for a one-unit change in the feature. For example, if the coefficient of a numerical feature is 0.5, it means that a one-unit increase in the feature is associated with a 0.5 increase in the log-odds of the target variable.\nWhile for a categorical feature, the coefficient represents the change in the log-odds of the target variable for a one-unit change from the reference category to the category represented by the feature. Considering a binary feature, if the coefficient is 0.5, it means that the category represented by the feature is associated with a 0.5 increase in the log-odds of the target variable compared to the reference category. For a multi-class feature, the interpretation is similar.\nInterpreting directly the coefficients of the logistic regression model can be difficult, especially when the features are not scaled, since log-odds is a not intuitive measure. To make the interpretation easier, we can transform the coefficients into odds ratios\n$$ \\text{odds ratio} = e^{w} $$where w is the coefficient of the feature.\nThe odds ratio is a more intuitive measure than the log-odds, as it represents the change in the odds of the target variable for a one-unit change in the feature. An odds ratio greater than 1 means that the feature has a positive impact on the probability of churn, while an odds ratio less than 1 means that the feature has a negative impact on the probability of churn.\nWe can calculate the odds ratios of the coefficients of the logistic regression model and plot them to see which features have the most impact on the probability of churn:\nOdds ratios of the coefficients of the logistic regression model Let\u0026rsquo;s understand our results. We have two numeric features, Tenure and MonthlyCharges. The MonthlyCharges feature has an odds ratio of 1, which means that a one-unit increase in the monthly charges is associated with no change in the odds of churn. Our model is regularized, which means that it tries to reduce the number of features to make the model simpler and more interpretable. The MonthlyCharges feature has, therefore, little or no impact on the probability of churn according to our model.\nThe Tenure feature has an odds ration of 0.45, which means that a one-unit increase in the tenure is associated with a 0.45 decrease in the odds of churn.\nWe also have some categorical features, the main ones being Contract and InternetService according to our model. Both underwent one-hot encoding, so we have multiple coefficients for each feature.\nThe coefficients of the Contract feature represent the change in the log-odds of the target variable for a one-unit change from the reference category to the category represented by the feature.\nThe odds ratios for each category of the Contract feature are as follows:\nMonth-to-month: 1.95 One year: 1 Two year: 0.48 We can divide the odds ratio of each category by the odds ratio of the reference category to see how much the odds of churn change for each category compared to the reference category. The reference category can be any category, but we can choose the category with the lowest odds ratio as the reference category. In this case, the reference category is the two-year contract. The values we get are:\nMonth-to-month: 4.06 One year: 2.08 Two year: 1 This means that customers with month-to-month contracts are 4.06 times more likely to churn than customers with two-year contracts, while customers with one-year contracts are 2.08 times more likely to churn than customers with two-year contracts. This is consistent with the exploratory data analysis we performed in the previous notebooks. We saw that customers with month-to-month contracts are more likely to churn than customers with one-year or two-year contracts. Now we have a quantitative measure of this relationship.\nWe can do the same analysis for the InternetService feature. The odds ratios for each category of the InternetService feature are as follows:\nFiber optic: 1.85 No: 0.93 DSL: 0.80 Dividing the odds ratio of each category by the odds ratio of the reference category (the one with the lowest odds ratio), we get:\nFiber optic: 2.31 No: 1.16 DSL: 1 This means that customers with fiber optic internet service are 2.31 times more likely to churn than customers with DSL internet service, while customers with no internet service are 1.16 times more likely to churn than customers with DSL internet service. It is interesting to note that customers with no internet service are more likely to churn than customers with DSL internet service.\nKey Takeaways and Business Impact # Customer churn is a critical issue that needs to be analyzed and predicted. Therefore, a model that can predict customer churn and deal with a huge amount of data is significant. In this study:\nan extensive EDA was performed detailed insights were gained from the data statistical tests were performed to identify the most relevant features pipelines were used to preprocess, train, and evaluate the models AUPRC was the main metric to compare models due to its literature background in imbalanced datasets the logistic regression model was chosen as the best model due to its performance, time, and interpretability the model was fine-tuned to maximize the AUPRC metric the coefficients of the model were interpreted to understand the impact of each feature on the probability of churn The results suggest that the Telco company should:\ninvest in marketing strategies targeting customers with short-term contracts, trying to move them to long contracts customers without online services, offering these services single customers, since their churn rate is higher than that of those who have partners and dependents improve the fiber optic service give more attention to technical support, especially for senior citizens Final Thoughts # This project underscores the transformative potential of data science in tackling real-world challenges such as churn prediction. By addressing issues like data imbalance and carefully selecting performance metrics, we developed a robust model that balances the trade-off between recall and precision. The integration of interpretability tools further enhances stakeholder trust and aids in continuous model improvement. Overall, this work demonstrates how data-driven strategies can significantly enhance operational efficiency and reduce customer churn rates.\nYou can check the complete code for this project on the GitHub repository.\nReach out to me if you have any questions or would like to discuss how these techniques can be applied to your specific business challenges. Here are some ways to connect with me and learn more about my work:\nLinkedIn GitHub Portfolio References # N. Modani, K. Dey, R. Gupta, and S. Godbole, “CDR Analysis Based Telco Churn Prediction and Customer Behavior Insights: A Case Study,” in Web Information Systems Engineering – WISE 2013, vol. 8181, X. Lin, Y. Manolopoulos, D. Srivastava, and G. Huang, Eds. Berlin, Heidelberg: Springer Berlin Heidelberg, 2013, pp. 256–269. doi: 10.1007/978-3-642-41154-0_19. S. Agrawal, A. Das, A. Gaikwad, and S. Dhage, “Customer Churn Prediction Modelling Based on Behavioural Patterns Analysis using Deep Learning,” in 2018 International Conference on Smart Computing and Electronic Enterprise (ICSCEE), Shah Alam, Jul. 2018, pp. 1–6. doi: 10.1109/ICSCEE.2018.8538420. I. Ullah, B. Raza, A. K. Malik, M. Imran, S. U. Islam, and S. W. Kim, “A Churn Prediction Model Using Random Forest: Analysis of Machine Learning Techniques for Churn Prediction and Factor Identification in Telecom Sector,” IEEE Access, vol. 7, pp. 60134–60149, 2019, doi: 10.1109/ACCESS.2019.2914999. “Churn.” https://www.productplan.com/glossary/churn/ (accessed Jun. 22, 2022). IBM. \u0026ldquo;Telco customer churn\u0026rdquo;. https://www.kaggle.com/datasets/blastchar/telco-customer-churn (accessed Jun. 1, 2022) Shearer C., The CRISP-DM model: the new blueprint for data mining, J Data Warehousing (2000); 5:13—22 J. Burez and D. Van den Poel, “Handling class imbalance in customer churn prediction,” Expert Systems with Applications, vol. 36, no. 3, pp. 4626–4636, Apr. 2009, doi: 10.1016/j.eswa.2008.05.027. Scikit-Learn. \u0026ldquo;Feature selection\u0026rdquo;. https://scikit-learn.org/stable/modules/feature_selection.html T. Saito and M. Rehmsmeier, “The Precision-Recall Plot Is More Informative than the ROC Plot When Evaluating Binary Classifiers on Imbalanced Datasets,” PLoS ONE, vol. 10, no. 3, p. e0118432, Mar. 2015, doi: 10.1371/journal.pone.0118432. Scikit-Learn. \u0026ldquo;Model evaluation\u0026rdquo;. https://scikit-learn.org/stable/modules/model_evaluation.html#precision-recall-f-measure-metrics LinkedIn GitHub Portfolio ","externalUrl":null,"permalink":"/portfolio/2022-06-project_churn_prediction/","section":"Portfolio","summary":"Churn is a measure of how many customers stop using a service or product,\noften evaluated for a specific period of time. In this study, a churn level\nprediction process is carried out using machine learning. A dataset with over\n7000 customers of a telecom company is used. An action plan for the company is\ndesigned based on the results.","title":"Customer churn prediction","type":"portfolio"},{"content":" Abstract # In recent decades, with the constant increase in financial transactions, credit card fraud has become a significant problem. Great computational power is devoted to detecting fraudulent operations, especially with the ever-increasing use of online banking and e-commerce. Several Data Mining and Machine Learning strategies have been employed in this context.\nIn this work, we will use a dataset of credit card transactions and study different algorithms that can be used to classify a given transaction as fraudulent or not.\nContext # Brief Description of a Fraud Detection System # Many types of fraud can be carried out, ranging from the omission of income sources, through money laundering, to card cloning. In an attempt to prevent these, the financial industry makes use of the so-called Rule-Based Systems, also known as Production Systems, which store and manipulate data to infer whether a given operation is fraudulent or not. Currently, such systems use machine learning tools.\nWe can envisage a fraud detection system in a bank as shown in the following figure. There is the institution\u0026rsquo;s database on which algorithm training is performed, generating models that represent the characteristics of the stored transactions.\nFluxogram of a Fraud Detection System. Adapted from literature. The model is then used to decide whether new transactions will be accepted as genuine or rejected as fraudulent. An accepted transaction will be executed and added to the database to improve the model. A rejected one will be set aside for manual evaluation. If it is considered genuine, it will be executed and added to the database as such. If fraud is confirmed, the rejection is confirmed and recorded in the database as an actual fraud.\nAs we can see, a crucial part of the process is to train an effective model. A well-developed model would not only identify fraud but also determine the probability of fraudulent behavior.\nDataset Used in This Study # The dataset used in this work can be downloaded from this Kaggle link. It is a database containing credit card transactions recorded by European card operators over two days in September 2013. There are 284,807 transactions, of which only 492 were recorded as frauds. Note the high number of transactions given that they cover only two days (and considering it was more than 10 years ago, imagine what the volume might be nowadays for the same time interval) and how it is a highly imbalanced dataset, as only 0.172 % of the total records are fraudulent.\nIn the next section, we will provide a more detailed description of the dataset and begin to understand how to train an effective model given this imbalance.\nA cross-industry standard process for data mining (CRISP-DM) will be used to guide the development of the project as shown in the figure below.\nProposed methodology flow diagram In this article, only the results will be shown. If you wish to see the complete code, visit the project\u0026rsquo;s repository:\nchicolucio/credit-card-fraud Jupyter Notebook 1 0 Exploratory Data Analysis (EDA) # Let us examine the dimensions:\nNumber of entries: 284807 Number of variables: 31 As discussed above, we have 284807 entries and 31 variables. In the dataset description on Kaggle, some explanations about the variables are provided:\nDue to confidentiality issues, the identifications of most of the original variables are not provided; The variables represented as V1, V2,\u0026hellip; V28 are the result of a transformation by Principal Component Analysis (PCA), a technique used to condense the information contained in several original variables into a smaller set of statistical variables (components) with minimal loss of information. Later, we will see some consequences of this transformation in our analysis; The variables Time (time) and Amount (transaction value) did not undergo PCA. Time refers to the interval, in seconds, between each transaction and the first one in the dataset. The variable Class is the target variable: The value 0 signifies a genuine, legitimate transaction The value 1 signifies fraud Obviously, Class has many 0 values since this value means a genuine transaction. It was seen that there are 1825 entries of transactions with a value of 0 (variable Amount). It is not clear what this means, whether these are cases of reversals, for example, or something similar. As this is a very small number of cases relative to the total number of entries in the dataset, such entries were not removed.\nWe have already seen in the introduction that the dataset is imbalanced. Let us verify this visually:\nClass imbalance. Logarithmic scale We can check if there is a time dependency in the data by analyzing the distribution of the Time variable for each class. If there is a time dependency, it means that the time at which the transaction occurred can influence the likelihood of fraud.\nTime distribution for each class While legitimate transactions have an increasing trend during the day, keeping a plateau until evening when they start to decrease, frauds have a smoother distribution, being more evenly distributed throughout the day. Then, they are easier to spot on the plot in the early morning hours, when the number of legitimate transactions is lower.\nIt is important to check for outliers in the dataset. We can do this by analyzing the distribution of the features. Using boxplots for each feature, we can identify outliers in the data. We can also check the distribution of the features for each class to see if there are differences between them.\nOutliers in the dataset Some observations:\nFor legitimate transactions, the outliers are more spread out, with some variables having numerous outliers. This may be considered expected, as legitimate transactions are more numerous than frauds. For frauds, the outliers are more concentrated, with fewer variables having a large number of outliers. This is also expected, as frauds are less numerous than legitimate transactions. The Amount variable has a large number of outliers for both classes. This is expected, as the transaction value can vary greatly. But, as we can see, the outliers for legitimate transactions are more spread out, while the outliers for frauds are more concentrated. Since the outliers are more concentrated for frauds, they were not remove, as they may be important for the model to learn the patterns of fraud. Only the outliers for legitimate transactions were removed, as they may be noise in the data. This is not a standard approach, but since we are dealing with a classification problem and a huge class imbalance, we need to keep as much information as possible about the minority class.\nIt was used a quantile-based method to remove the outliers. The method is based on values that are below a certain quantile or above another quantile. The quantiles used were 0.0025 and 0.9975, a very small percentage of the data. This way, we can remove only the most extreme outliers.\nLet\u0026rsquo;s check the boxplots for the features after removing the outliers:\nDistribution after removing outliers with quantile-based method We see that now the range of values for the features is more balanced between the two classes.\nThe shape of the distribution of the features is also important. We can check the distribution of the features for each class to see if there are differences between them. This can help us understand the data better and choose the best algorithm to classify the transactions. Let\u0026rsquo;s check the distribution of the features for each class:\nDistribution of the features for each class We see that some features, like V14 and V16 have a quite different distribution for each class. This is a good sign that they might be useful for a future model. And features like V13 and V15 have a similar distribution for both classes. This is a sign that they might not be useful for a future model.\nEven though the plots show some differences between the classes, some statistical tests were performed to confirm if the differences are statistically significant. Specifically, the Mann-Whitney U test was used to check if the distributions of the features for each class are different. The test was performed for each feature, and the p-values were calculated. This way, it was shown that the features V13, V15, and V22 have a p-value greater than 0.05, the significance level adopted, which means that the distributions of these features for each class are not statistically different.\nWith this information, these three features were removed from the dataset. The other features were kept, as they showed a statistically significant difference between the classes.\nEvaluating models # After the exploratory data analysis, some models were trained to classify the transactions as fraudulent or not. The models used were:\nDummy Classifier (as a baseline) Logistic Regression Decision Tree LightGBM K-Nearest Neighbors Support Vector Machine for Classification (SVC - only after resampling - see below) A Scikit-Learn pipeline was used to preprocess the data and train the models. The features were preprocessed using power transformations (features Time and Amount) and robust scaling (features V1 to V28). Due to the imbalance in the dataset, a stratified 5-fold cross-validation technique was used to train and evaluate the models. Moreover, the class weight parameter was used in the models (if available) to deal with the imbalance.\nScikit-Learn pipeline used to train the models The following metrics were used to evaluate the models:\naccuracy: the proportion of correctly classified samples; balanced_accuracy: the average of the recall of each class; f1: the harmonic mean of precision and recall; precision: the proportion of correctly classified positive samples; recall: the proportion of positive samples that were correctly classified; roc_auc: the area under the ROC curve; average_precision: the area under the precision-recall curve; neg_brier_score: the Brier score, which is the mean squared difference between the predicted probabilities and the actual outcomes. The lower the Brier score, the better the model; f1_weighted: the weighted average of the f1 score, which is the harmonic mean of precision and recall. The f1 score is weighted by the number of samples in each class. We also have some time metrics regarding the training and prediction times, and the total time. The consolidated metrics for each model are shown below as boxplots:\nConsolidated metrics for each model The choice of the best model should consider some factors:\nThe metrics: which model has the best performance in the metrics that are most important for the business; The time: the model that has the best performance in the metrics and the lowest time should be chosen; The interpretability: some models are more interpretable than others. If interpretability is important, the model that is easier to interpret should be chosen. It happens that the best model in terms of metrics is not always the best model in terms of time or interpretability. So, the choice of the best model should consider all these factors.\nConcerning the metrics, some literature suggests that the area under the precision-recall curve (AUPRC, represented as average_precision on Scikit-Learn) is a better metric for imbalanced datasets than the area under the ROC curve (AUROC, or roc_auc). This is because the ROC curve is not sensitive to changes in the false positive rate when the true positive rate is high. The precision-recall curve, on the other hand, is sensitive to changes in the false positive rate when the true positive rate is high. I already covered this in a previous article.\nWe can see that the logistic regression model has the best performance in terms of the chosen metric and is also one of the fastest models. However, we see that although the recall is high, the precision is extremely low. This means that the model is classifying most of the samples as positive, which is not good. We need to find a balance between precision and recall.\nNow, let\u0026rsquo;s check the second-best model concerning average precision, the KNN model. It has a good balance between precision and recall. However, it is one of the slowest models. And here it is not an issue related to fine-tuning and hyperparameters. We have a considerable dataset, and KNN essentially calculates the distance between each sample and all the other samples. This is a very time-consuming process during the scoring phase (you can compare fit and score times in the results dataframe).\nTo deal with the time issue, resampling techniques were explored.\nResampling Techniques # Resampling techniques are used to deal with imbalanced datasets. They can be divided into two categories: oversampling and undersampling. Oversampling techniques increase the number of samples in the minority class, while undersampling techniques decrease the number of samples in the majority class. In this work, the Imbalanced-Learn library was used to apply the resampling technique.\nAn undersampling technique called near miss was implemented. NearMiss is a technique that selects points of the majority class that are going to be removed. This way, we will have a balanced dataset, and we will be able to train the models faster.\nYou can learn more about the near miss technique on the imbalanced-learn documentation.\nAs can be seen in the docs, there are 3 versions of NearMiss: NearMiss-1, NearMiss-2, and NearMiss-3. NearMiss-3 was chosen. It is a 2-steps algorithm. First, for each negative sample, their nearest-neighbors will be kept. Then, the positive samples selected are the one for which the average distance to the nearest-neighbors is the largest.\nThe value 1/2 was set for the parameter sampling_strategy. This value means that we want a final dataset with a proportion of 1:2 between the minority and majority classes. This is still an imbalanced dataset, but it is far less imbalanced than the original dataset so that the models can learn better.\nThe same pipeline used before, with the addition of the nearmiss technique, was used to train the models. The same metrics were used to evaluate the models.\nScikit-Learn pipeline used to train the models after resampling The consolidated metrics for each model are shown below as boxplots:\nConsolidated metrics for each model after resampling It is interesting that the performance of KNN degraded a lot. Since we removed many points from the majority class, and the removal considered the nearest neighbors, the KNN algorithm lost a lot of information.\nHowever, our dataset now is small enough for algorithms like SVC to perform well. Even though it is not the best model concerning our metric of choice (it is the second best), it is the only model to have a good balance between precision and recall. This is important because we want to predict the minority class, and we would rather not have plenty of false positives.\nIt is the slowest model of all, but since we have a small dataset after resampling, it is not a problem now as it was before. Comparing, the SVC training after resampling is almost 10 times faster than the KNN training before resampling.\nThe SVC model was fine-tuned using a grid search. The parameters C, gamma and kernel were tuned. The best parameters found were kernel=rbf, C=1 and gamma=scale.\nThe final model has the following metrics:\nMetric Score Std Dev Accuracy 0.99968 0.00004 Balanced Accuracy 0.91 0.01 F1 0.90 0.01 Precision 1.00 0.00 Recall 0.82 0.02 ROC AUC 0.941 0.008 Average Precision 0.86 0.02 Neg. Brier Score -0.009 0.002 F1 Weighted 0.999665 0.00005 Model Interpretability # Model interpretability is an essential factor when choosing a model. It is important to understand how the model makes its predictions.\nSome models are more interpretable than others. For example, decision trees are very interpretable, as we can see the rules that the model uses to make its predictions. On the other hand, models like SVM are not very interpretable, as we cannot see the rules that the model uses to make its predictions.\nIn this work, the permutation importance technique was used to interpret the models. The permutation importance technique is a model-agnostic technique that can be used to interpret any model. It works by permuting the values of a feature and checking how much the model\u0026rsquo;s performance decreases. The more the performance decreases, the more important the feature is for the model.\nThe figure below shows the permutation importance for the chosen model, SVC:\nPermutation importance for the chosen model We see that features V17 and V14 decrease the average precision the most when they are permuted. This means that these features are the most important for the SVC model. This is consistent with the results of the graphical and statistical feature importance analysis we did previously.\nThe permutation importance may seem a bit abstract for some people. So, other tools can be used to show to stakeholders how the model is making its predictions. Plots are usually easier for stakeholders to understand. Let\u0026rsquo;s try one.\nThe Kolmogorov-Smirnov (KS) plot is a way to check how well a binary classification model separates two groups: positives (class = 1) and negatives (class = 0). It helps us understand if the model is making clear distinctions between the two classes based on the probabilities it assigns.\nThe KS plot is based on something called the Cumulative Distribution Function (CDF), which is just a way of showing how the probabilities are distributed in each class. Imagine listing all predicted probabilities for a class in order from smallest to largest. The CDF tells us, for each probability value, how many cases fall at or below that value.\nConsider the plot below:\nThe blue line represents the positive class (y=1). It shows how many actual positive cases have a predicted probability less than or equal to a given value. The red line represents the negative class (y=0). It shows how many actual negative cases have a predicted probability less than or equal to that value. The KS statistic is the biggest vertical gap between the two lines. This gap tells us how well the model is distinguishing between positives and negatives. The KS statistic is a number between 0 and 1 that indicates how well the model separates the two classes:\nA high KS value (closer to 1) means the model is doing a good job distinguishing between positives and negatives. A low KS value (close to 0) means the model struggles to tell the two classes apart. If the KS value is greater than 0.4, it usually means the model is making strong distinctions between the two classes.\nThis plot is a great way to visually confirm how well a model is performing beyond standard metrics like accuracy and AUC-ROC.\nKolmogorov-Smirnov plot for the chosen model Confusion matrices are also a great way to interpret the model. They show how many samples were classified correctly and incorrectly. The confusion matrix for the chosen model, SVC, is shown below:\nConfusion matrix for the chosen model We see that, for class 0, the model classified all samples correctly. For class 1, the model classified 83% of the samples correctly. This is a good result, considering that the dataset is highly imbalanced.\nKey Takeaways and Business Impact # This project demonstrates that data science techniques can significantly improve fraud detection by addressing challenges associated with imbalanced datasets. Key insights include:\nMetric Selection is Crucial: Traditional metrics such as accuracy can be misleading in highly imbalanced scenarios. Our analysis shows that metrics like average precision (AUPRC), recall, and balanced accuracy provide a more realistic picture of model performance. Resampling Techniques Enhance Model Performance: Applying undersampling (using the Nearmiss-3 method) allowed us to balance the data and train models more effectively. The resulting improvements in precision and recall are critical for detecting fraudulent transactions. Support Vector Machines (SVC) Show Promise: After resampling and fine-tuning, SVC emerged as the best-performing model, balancing a high recall with an acceptable precision level. This balance is essential for minimizing both false negatives and false positives. Interpretability Aids Decision-Making: Using model-agnostic interpretability techniques, such as permutation importance and the Kolmogorov-Smirnov plot, provides transparency on which features most influence the model’s predictions. This insight is invaluable when communicating results to business stakeholders and aligning the model with operational strategies. The business impact of this work is substantial. A robust fraud detection system that leverages these techniques can reduce financial losses, improve customer trust by minimizing false alarms, and provide a scalable solution that evolves with emerging fraud tactics. Integrating such a model into existing systems can support real-time decision making, allowing financial institutions to act swiftly and allocate resources more efficiently.\nActionable Recommendations for the Fraud Detection Team # Based on our analysis, the following steps are recommended to enhance fraud detection operations:\nAdopt a Metrics-Driven Approach:\nMonitor not just accuracy but also AUPRC, recall, balanced accuracy, and the KS statistic to ensure the model effectively differentiates between genuine and fraudulent transactions. Implement Resampling Strategies:\nUse techniques such as NearMiss-3 to balance datasets, which can improve model learning and speed up training, especially when dealing with large volumes of transactions. Integrate the SVC Model into the Fraud Detection Workflow:\nDeploy the fine-tuned SVC model to flag potential fraud cases in real time, ensuring a balance between detecting fraud (high recall) and minimising false alerts (maintaining precision). Enhance Model Interpretability:\nUtilize tools such as permutation importance and KS plots to continuously monitor and explain model decisions. This will help in fine-tuning the system and ensuring transparency with stakeholders. Establish a Continuous Improvement Cycle:\nSet up a process for regular model retraining and validation using new transaction data to adapt to emerging fraud patterns. Incorporate feedback from manual evaluations of flagged transactions to refine the model further. Collaborate with Cross-Functional Teams:\nWork closely with IT, risk management, and customer service teams to align the model’s thresholds and alert mechanisms with operational needs and customer expectations. Assign cost values to false positives and false negatives:\nBy assigning costs to false positives and false negatives, the model can be fine-tuned to minimize financial losses and operational costs. Check the original features:\nThe features V1 to V28 are the result of a PCA transformation. It is important to check the original features to understand the model\u0026rsquo;s predictions better. Which are the original features with higher contribution to the components V1 to V28? Specifically for the features V14 and V17, which are the most important features for the model? Surely, this will give more insights into the model\u0026rsquo;s predictions. Implementing these recommendations will not only improve the detection of fraudulent transactions but also help in managing operational costs, improving customer satisfaction, and ultimately reducing financial losses associated with fraud.\nFinal Thoughts # This project underscores the transformative potential of data science in tackling real-world challenges such as fraud detection. By addressing issues like data imbalance through resampling techniques and carefully selecting performance metrics, we developed a robust model that balances the trade-off between recall and precision. The integration of interpretability tools further enhances stakeholder trust and aids in continuous model improvement. Overall, this work demonstrates how data-driven strategies can significantly enhance operational efficiency and reduce financial risk, while also paving the way for ongoing advancements in fraud prevention.\nYou can check the complete code for this project on the GitHub repository.\nReach out to me if you have any questions or would like to discuss how these techniques can be applied to your specific business challenges. Here are some ways to connect with me and learn more about my work:\nLinkedIn GitHub Portfolio ","externalUrl":null,"permalink":"/portfolio/2022-01-project_credit_card_fraud/","section":"Portfolio","summary":"In this work, we will use a credit card transactions database to study\ndifferent algorithms, which can be used to classify a given transaction\nas fraudulent or not. We will see how to deal with unbalanced databases\nin machine learning.","title":"Credit Card Fraud Detection","type":"portfolio"},{"content":" Abstract # It has been 2 years since the emergence of the COVID-19 virus. The pandemic control measures adopted by governments around the world have significantly affected everyone\u0026rsquo;s routine. Now, most governments are relaxing COVID restrictions despite high omicron variant spread. In this study, Our World in Data (OWID) database was used to see the evolution of cases, deaths, and vaccination. The impact of new variants on cases and deaths was shown as well as a possible relation with winter season. Some countries were selected to a more detailed view in order to compare the ones that did not adopt restrict measures with those that did.\nThe following page is written in Brazilian Portuguese.\nIntrodução # A COVID-19 é uma doença infecciosa causada por um recém-descoberto coronavírus.\nCompletamos pouco mais de 2 anos desde o surgimento do vírus COVID-19. As medidas para controle pandêmico adotadas por governos em todo mundo afetaram significativamente a rotina de todos. É de grande interesse acompanharmos a evolução da pandemia para saber seus reais efeitos e avaliar o retorno ao convívio normal.\nNeste trabalho, uma análise exploratória dos dados fornecidos pela Our World in Data (OWID) é feita, mostrando o avanço temporal de casos, óbitos e vacinação. Estudos comparativos e busca de correlações são feitos com intuito de melhor compreender os dados. Animações como a mostrada acima serão criadas e interpretadas.\nObtenção dos dados # Como já citado, os dados aqui utilizados são fornecidos pela Our World in Data (OWID) neste repositório, uma organização que reúne pesquisadores de todo o mundo para agregar dados de diversas fontes sobre os mais diversos problemas contemporâneos.\nObviamente, por ser uma doença recente, cuidados devem ser tomados no que diz respeito à interpretação dos dados e relações de causa e efeito. Como será mostrado adiante, nem todos os países fornecem dados completos e há algumas inconsistências nos dados a depender de suas origens. Além disso, com o crescente conhecimento a respeito da doença, por vezes se faz necessário alterar a forma de agregar os dados, causando algumas dificuldades de análise temporal. Não podemos ignorar também o fato de que, infelizmente, a visão passada por veículos de mídia e governantes para população pode variar e ser distorcida a depender dos interesses momentâneos dos mesmos.\nAssim, durante esse estudo, especial cuidado é destinado em apresentar os dados e buscar interpretá-los de forma rigorosa deixando claro eventuais limitações, conflitos e condições de contorno de cada análise. E, sempre lembrando, correlações não implicam em causalidade.\nA base de dados da OWID apresenta 67 variáveis (colunas) e 187.097 entradas. Há ausência de muitos dados sobre hospitalização e realização de testes por nem todos os países terem informações oficiais, de forma que essas categorias foram deixadas de fora desta análise.\nO estudo utilizou a linguagem de programação Python e alguns pacotes para esta linguagem. O pacote Pandas foi utilizado para trabalhar com os dados e construir matrizes de correlações. Os pacotes Matplotlib, Seaborn e Plotly foram utilizados para construir os gráficos. Funções foram criadas para padronizar os estilos de cada tipo de gráfico utilizado no trabalho. Tais funções se encontram no arquivo plots.py no repositório do estudo. A biblioteca datetime, presente em uma instalação padrão do Python, foi utilizada para lidar com datas.\nA base de dados baixada apresenta dados até 17 de maio de 2022, quando foi obtida. Porém, há alguns dados cuja periodicidade é diferenciada. Desta forma, vamos considerar como última data para análise 30 de abril de 2022 para termos apenas meses fechados, de janeiro de 2020 até abril de 2022.\nEvolução do número de casos # Vamos começar nossa análise avaliando a evolução no número total de casos em todo o mundo.\nTotal de casos # Mundo # Muito do que é exposto nas mídias foca na quantidade total de casos por país ou mundialmente. Vamos avaliar o perfil de crescimento no número de casos mundial:\nVemos que, desde o surgimento em meados de janeiro de 2020, foram necessários cerca de 3 meses para atingir 1 milhão de casos e 1 ano para 100 milhões de casos. Lembrando que esses são os casos efetivamente computados devido a testagem ou procura das pessoas pelas redes de saúde. O número real é potencialmente maior tendo em vista que há casos brandos ou assintomáticos, de maneira que os indivíduos não procuram as redes de saúde. De qualquer forma, considerando que a população mundial é estimada na ordem de 7,8 bilhões de pessoas, o número de casos até o momento indica que cerca de 6 % da população mundial já teve a doença.\nMuito se fala das variantes do vírus. A Organização Mundial da Saúde (OMS) em seu site descreve os critérios para considerar uma determinada variante como sendo de interesse ou preocupante. A OMS também esclarece que os nomes são dados um certo tempo depois que as primeiras amostras de cada variante são analisadas, conforme a tabela:\nVariante Data da primeira amostra Data do nome alfa Setembro/2020 - Reino Unido Dezembro de 2020 beta Maio/2020 - África do Sul Dezembro de 2020 gama Novembro/2020 - Brasil Janeiro de 2021 delta Outubro/2020 - Índia Abril de 2021 lambda Dezembro/2020 - Peru Junho de 2021 mu Janeiro/2021 - Colômbia Agosto de 2021 ômicron Novembro/2021 - Diversos Novembro de 2021 Neste estudo, optou-se por utilizar a data da primeira amostra nos gráficos, motivo pelo qual a beta aparece antes da alfa. Tal escolha se deve ao fato de a variante já estar se espalhando desde a data de amostra independentemente de ter recebido um nome. Vamos adicionar aos gráficos anteriores linhas indicando as datas de aparecimento de cada variante:\nO número de casos teve um acelerado crescimento inicial antes do surgimento da primeira variante (beta) e houve um aumento de 10 vezes entre as datas da variante beta e da variante alfa, um intervalo de 4 meses. O crescimento se torna, então, um mais lento. Nos quatro meses entre as variantes alfa e mu o número de casos cresceu 3 vezes.\nCerca de 2 meses depois do surgimento da variante ômicron, ou seja, em janeiro de 2022, houve um acentuado aumento no número de casos.\nPrincipais países # Vamos agora olhar os países com mais casos até abril de 2022.\nTotais absolutos # Em um primeiro momento, podemos supor que países com maiores populações apresentem mais casos. Vamos verificar as maiores populações mundiais, e seus totais de casos e mortes:\nlocation population total_cases total_deaths China 1,444,216,102 977,966 5,060 India 1,393,409,033 43,079,188 523,843 United States 332,915,074 81,352,100 993,665 Indonesia 276,361,788 6,046,796 156,257 Pakistan 225,199,929 1,527,956 30,369 Brazil 213,993,441 30,448,236 663,736 Nigeria 211,400,704 255,716 3,143 Bangladesh 166,303,494 1,952,691 29,127 Russia 145,912,022 17,917,191 368,319 Mexico 130,262,220 5,739,680 324,334 Agora, vamos organizar uma tabela mostrando os países com mais casos e, também, expressar isto graficamente:\nlocation continent population total_cases total_deaths United States North America 332,915,074 81,352,100 993,665 India Asia 1,393,409,033 43,079,188 523,843 Brazil South America 213,993,441 30,448,236 663,736 France Europe 67,422,000 28,699,367 145,999 Germany Europe 83,900,471 24,809,785 135,461 United Kingdom Europe 68,207,114 22,112,691 175,081 Russia Europe 145,912,022 17,917,191 368,319 South Korea Asia 51,305,184 17,275,649 22,875 Italy Europe 60,367,471 16,463,200 163,507 Turkey Asia 85,042,736 15,032,093 98,771 Vemos que 4 países dentre os que apresentam maiores populações no mundo também figuram entre os com mais casos: Estados Unidos, Índia, Brasil e Rússia. Há a ausência da China, mas os dados de lá não são confiáveis tendo em vista o regime ditatorial, sendo que o país até mesmo se nega a fornecer dados mais completos sobre a própria origem do vírus.\nOutra ausência que chama a atenção é a Indonésia. Novamente, devido a questões políticas, não se pode confiar totalmente nos dados reportados por tal país, visto que o próprio presidente da Indonésia afirmou em dado ponto que não estavam disponibilizando informações para \u0026ldquo;evitar pânico\u0026rdquo; na população. Obviamente, tal posicionamento é amplamente criticado.\nVemos por esses dois casos que há diversos fatores sociais, econômicos e políticos que podem afetar a análise. Há países entre as maiores populações que enfrentam questões políticas, econômicas e de saúde complicadas, como Paquistão, Bangladesh e Nigéria, que podem afetar a capacidade de tais países em acompanhar e reportar os casos adequadamente. Inclusive, de acordo com dados e relatórios das Nações Unidas, apenas dois terços dos países do mundo possuem registros de pelo menos 90 % dos nascimentos e óbitos. Todos os países citados aparecem nos relatórios como países com dificuldades de registro.\nNeste estudo, vamos nos ater ao que é apresentado. Mas é importante notar tais situações.\nComparando com a primeira versão deste estudo, publicada em outubro de 2021, temos as três primeiras posições com os mesmos países. A França passou da sétima posição para a quarta, anteriormente ocupada pelo Reino Unido. A Alemanha nem ao menos aparecia na lista em outubro de 2021 e, agora, ocupa a quinta posição, antes ocupada pela Rússia. A Túrquia antes ocupava a sexta posição e, agora, a décima. Itália e Coreia do Sul não figuravam na lista.\nVamos montar um gráfico interativo para avaliar cada país por continente.\nPara interagir com o gráfico, clique nos continentes para ter mais detalhes do mesmo. No celular pode ser que o título fique cortado pelo tamanho da tela, mas funciona igual. No gráfico, temos uma ideia da proporção do total de casos de cada país frente aos demais de seu continente e do mundo.\nMas será que essa é a melhor métrica para avaliar comparativamente a situação de cada país?\nTotais por milhão de habitantes # Uma análise do total absoluto de casos não necessariamente reflete a realidade de cada país. Afinal, como já dito, países com maiores populações tendem a ter maior número de casos. No entanto, isso não significa que países com populações pequenas não possam estar em situação pior. Afinal, podem, relativamente ao seu número de habitantes e à sua estrutura de saúde pública, estar com elevado número de casos. E regiões com maiores densidades populacionais podem favorecer uma maior taxa de transmissão (hipótese que será estudada mais adiante).\nVamos, então, verificar os países com mais casos por milhão de habitantes:\nlocation continent population total_cases total_cases_per_million Faeroe Islands Europe 49,053.00 34,658.00 706,541.90 Denmark Europe 5,813,302.00 3,116,655.00 536,124.74 Cyprus Europe 896,005.00 480,220.00 535,956.83 Andorra Europe 77,354.00 41,349.00 534,542.49 Gibraltar Europe 33,691.00 17,837.00 529,429.22 Iceland Europe 368,792.00 185,579.00 503,207.77 Slovenia Europe 2,078,723.00 1,010,058.00 485,903.12 San Marino Europe 34,010.00 16,437.00 483,299.03 Netherlands Europe 17,173,094.00 8,141,249.00 474,070.02 Saint Pierre and Miquelon North America 5,771.00 2,701.00 468,029.80 Percebemos uma grande mudança, aparecendo pequenos territórios e países. Na primeira posição, temos as Ilhas Faroe, um território dependente da Dinamarca com cerca de 50 mil habitantes. Por mais que a localidade ainda seja oficialmente parte da Dinamarca, a base de dados em questão trabalha com o conceito de territórios e não de países.\nA própria Dinamarca, considerando a porção continental do país, aparece em segundo. Ainda no início de 2021, o país já enfrentava críticas internas sobre sua política de lockdown como mostra esse artigo da Science. Recentemente, no início de 2022, o país retirou todas as restrições e viu o número de casos diários diminuir significativamente. No entanto, como descrito no artigo citado, a política de testagem mudou, não sendo possível fazer uma comparação adequada entre o período atual, sem restrições, e o anterior, com restrições. Em recente entrevista, Camilla Holten-Moller, uma das responsáveis por modelos matemáticos utilizados pelo governo dinamarquês, justificou a retirada de todas as restrições ao final de janeiro de 2022 ainda que os casos na época estivessem aumentando devido à variante ômicron. E ainda fez análises críticas sobre o uso de modelos matemáticos em situações políticas.\nOutros territórios aparecem na listagem:\nGibraltar (território britânico) São Pedro e Miquelão (território francês), único da lista não localizado na Europa Como vemos, quando consideramos a proporção de casos ao invés do total absoluto, o perfil da análise muda significativamente. E fica mais seguro e coerente fazer comparações com os dados em uma mesma escala. O fato de termos predominância de localidades na Europa sugere que há características do continente que favorecem o espalhamento do vírus. Tais características podem ser: clima, idade da população, densidade populacional, dentre inúmeras outras. Adiante, iremos nos aprofundar em algumas dessas características e verificar se há algum tipo de correlação com os dados de COVID.\nApenas três localidades da listagem possuem populações na ordem milhões: Dinamarca, Eslovênia e Holanda. Sobre a Dinamarca já escrevemos um pouco anteriormente. Tanto a Eslovênia quanto a Holanda também adotaram políticas de lockdown e restrições, que foram retiradas nos últimos meses. Como descrito no link sobre a Holanda, o país já enfrentava dificuldades no setor de saúde antes da pandemia, por falta de profissionais, e há críticas quanto ao modo que o governo local abordou a situação durante a pandemia e preocupação caso haja uma nova onda da doença. Ainda assim, o número de casos no país cai continuamente após a retirada das restrições.\nVamos criar um gráfico interativo mostrando cada país por continente:\nPara interagir com o gráfico, clique nos continentes para ter mais detalhes do mesmo. No celular pode ser que o título fique cortado pelo tamanho da tela, mas funciona igual. Veja como a análise proporcional muda significativamente o perfil do gráfico. Todos os países que apareciam como líderes em totais absolutos não figuram entre os que possuem mais casos por milhão de habitantes. Na Europa, vemos uma maior participação de países do leste europeu que tiveram uma nova onda ao final do ano passado. Mesmo com os casos na região caindo, a OMS tem alertado os países da região sobre o risco de novas ondas. Na América do Sul, vemos que o Brasil se encontra em quarto, atrás de Argentina, Uruguai e Chile. Uruguai e Argentina foram considerados modelos em diversos estágios da pandemia com suas medidas restritivas e lockdowns, mas agora lideram o total de casos por milhão.\nNa Ásia, vemos que o país com mais casos por milhão de habitantes é Israel. O país adotou lockdowns e diversas estratégias restritivas e foi um dos mais ágeis do mundo na distribuição de vacinas, inclusive as doses de reforço, para população. No entanto, como vemos, os resultados não foram os esperados. Em recente entrevista, Cyrille Cohen, um dos membros do comitê de vacinas do governo israelense, disse \u0026ldquo;cometemos enganos\u0026rdquo; durante a pandemia. Dentre os \u0026ldquo;enganos\u0026rdquo; ele cita: passaportes vacinais, que não são efetivos; as vacinas, que não previnem transmissão como esperado inicialmente, e que não deveriam ser obrigatórias; ter fechado escolas e universidades, o que prejudicará de forma incalculável a evolução cognitiva de crianças e jovens. Por fim, na entrevista, Cohen afirma que não se deveria ignorar a imunidade de rebanho e que, com a ômicron e novas variantes, a COVID será \u0026ldquo;como uma gripe\u0026rdquo;.\nVamos construir uma mapa interativo mostrando a evolução do total de casos por milhão em cada país. A consolidação foi feita por mês apenas para deixar a animação do mapa mais rápida, se fosse evolução diária seria uma animação bem demorada.\nPara interagir com o gráfico, clique na seta de play. No celular pode ser que o título fique cortado pelo tamanho da tela, mas funciona igual. Vemos no mapa que apenas alguns países da África apresentaram significativa evolução no número de casos. Como já escrito anteriormente, provavelmente isso está relacionado com as precárias condições de tais países em reportar adequadamente casos e mesmo realizar testes. No entanto, como será mostrado adiante, o perfil mais jovem da população também pode ter alguma relação, já que a doença é mais branda em jovens, o que pode fazer com que menos pessoas busquem tratamento, ficando de fora dos números oficiais. Há estudos que sugerem tal explicação, além de outras. Mais algumas referências sobre o assunto COVID na África: Nature, JNMA e Science. Todas as referências citam o fato de o número de casos e mortes no continente africano estarem bem abaixo do esperado com base em modelos e que ainda não há clareza sobre os motivos.\nNa Oceania, vemos poucos casos na Austrália e na Nova Zelândia até o início de 2022. Os dois países adotaram políticas altamente restritivas e questionáveis, como campos de quarentena forçada, buscando zerar novos casos. Agora, se veem forçados a afrouxar tais políticas por não terem tido o efeito desejado e estarem quebrando suas economias. Ao reabrirem suas economias pelo fracasso da política de COVID zero, viram o números de casos disparar, especialmente pela variante ômicron.\nNa Austrália, a população já estava saturada das restrições e o número particularmente alto também pode ser reflexo dos testes de PCR ainda serem gratuitos, o que não é o caso em boa parte dos países. Na Nova Zelândia, a disruptura social causada pelas medidas restritivas tem levado a um aumento na criminalidade em grandes centros após a reabertura. A preocupação é a maior participação de jovens em atividades criminosas, tendo em vista que muitos se afastaram das escolas e colégios durante os lockdowns. Além da situação financeira, com o aumento do custo de vida, que tem gerado problemas de habitação.\nObserve no parágrafo anterior o comentário sobre os testes de PCR. Já havíamos visto que a Dinamarca mudou sua política de testagem, apenas para \u0026ldquo;casos médicos especiais\u0026rdquo;, enquanto que a Austrália ainda faz testagem gratuitamente em sua população. Estas diferentes políticas adotadas por países dificulta a comparação entre os mesmos e pode levar a distorções nos dados. Inclusive, o primeiro ministro australiano Scott Morrison, candidato à reeleição que foi derrotado nas eleições que ocorreram em maio de 2022, criticou a política de testagem atual e de registro de óbitos em recente entrevista. Com mais de 95 % da população adulta vacinada, Morrison disse que se deve conviver com a COVID, e que muitas mortes registradas com COVID não necessariamente foram devido à COVID. Isto porque os protocolos locais orientam o registro como COVID de qualquer situação confirmada ou que seja provável de infecção pelo vírus, a menos que uma \u0026ldquo;clara alternativa\u0026rdquo; exista.\nIdade e riqueza # Vamos verificar se o número de casos possui alguma relação com a renda per capita do país ou a idade da população.\nComecemos verificando os países com maior PIB per capita:\nlocation population total_cases total_cases_per_million gdp_per_capita continent Qatar 2,930,524.00 364,602.00 124,415.29 116,935.60 Asia Macao 658,391.00 82.00 124.55 104,861.85 Asia Luxembourg 634,814.00 237,856.00 374,686.13 94,277.96 Europe Singapore 5,453,600.00 1,193,250.00 218,800.42 85,535.38 Asia Brunei 441,532.00 141,850.00 321,267.77 71,809.25 Asia Ireland 4,982,904.00 1,517,112.00 304,463.42 67,335.29 Europe United Arab Emirates 9,991,083.00 898,571.00 89,937.30 67,293.48 Asia Kuwait 4,328,553.00 631,409.00 145,870.69 65,530.54 Asia Norway 5,465,629.00 1,426,013.00 260,905.56 64,800.06 Europe Switzerland 8,715,494.00 3,619,598.00 415,306.12 57,410.17 Europe Como era de se esperar, vemos apenas países da Ásia e Europa.\nA base de dados possui entradas para agregados de países com base na classificação de renda do Banco Mundial. Tal classificação baseia-se na renda per capita da seguinte forma (dólares americanos):\nClassifição Limite inferior Limite superior Renda baixa (low-income) - 1045 Renda média baixa (lower-middle-income) 1046 4095 Renda média alta (upper-middle-income) 4096 12695 Renda alta (high-income) 12696 - Para detalhes de classificação de cada país, veja este link. O Brasil, por exemplo, é considerado uma economia de renda média alta. Abordaremos com mais detalhes o caso brasileiro em uma seção específica mais adiante.\nVejamos, então, o total de casos por milhão de habitantes considerando estes agregados:\nVemos claramente que há mais casos em países de renda alta, com quase duas ordens de grandeza mais casos que países de renda baixa. O perfil de crescimento é similar em todas as classificações.\nVamos criar um gráfico interativo buscando avaliar como os casos variam com a expectativa de vida e o PIB per capita:\nPara interagir com o gráfico, passe o mouse pelos círculos ou clique nos nomes dos continentes para mostrá-los ou não. No celular pode ser que o título fique cortado pelo tamanho da tela, mas funciona igual. No gráfico vemos claramente que os países do continente africano possuem, em sua maioria, menores expectativas de vida e menores PIB per capita (menores círculos no gráfico). No entanto, Seicheles, país africano com maior PIB per capita e uma das maiores expectativas de vida do continente, lidera o continente em total de casos por milhão. Na primeira versão deste trabalho, em outubro de 2021, Seicheles liderava o mundo em casos por milhão, mesmo sendo o país com maior porcentagem da população vacinada à época.\nVemos uma tendência similar em outros continentes, maiores expectativas de vida e PIB per capita com mais casos. Obviamente que países mais ricos tendem a ter uma maior parcela da população com idade avançada e, como a doença afeta mais pessoas idosas, é de se esperar maior notificação de casos nesses países. No entanto, cabe destacar que há notáveis exceções à essa tendência como, por exemplo, o Japão.\nUma maior expectativa de vida, no entanto, não necessariamente significa que a população atual possui mais idosos que jovens. Assim, vamos repetir o gráfico substituindo o eixo de expectativa de vida por mediana de idade:\nPara interagir com o gráfico, passe o mouse pelos círculos ou clique nos nomes dos continentes para mostrá-los ou não. No celular pode ser que o título fique cortado pelo tamanho da tela, mas funciona igual. Vemos a mesma tendência geral: população mais velha, mais casos notificados. É interessante notar que o Japão possui a maior mediana de idade do mundo e não possui um valor muito elevado de casos por milhão. O país não adotou políticas como lockdowns e quarentenas compulsórias pois entendeu que tais medidas impostas violariam os direitos humanos expressos em sua constituição. Ao invés, adotou o sistema de estados de emergência, onde apenas algumas medidas voltadas para locais com muitas pessoas podiam ser tomadas e, mesmo assim, não havia poder legal de impedir a movimentação de pessoas. Inclusive, a Corte de Tóquio considerou ilegal uma ordem do governo metropolitano de restringir o horário de uma cadeia de restaurantes.\nEnquanto a política interna não foi muito restritiva, a voltada para as fronteiras foi. Apenas agora, em maio de 2022, o país começa a abrir aos poucos suas fronteiras, ainda com diversas restrições. O Japão é o único país do G7 que ainda não retirou restrições de viagem e sua política de fronteiras tem recebido críticas como \u0026ldquo;isolacionista e xenófoba\u0026rdquo;, além de sem sentido tendo em vista a transmissibilidade da variante ômicron. A pressão interna para reabertura tem aumentado, já que a economia do país passa por dificuldades e o turismo sempre foi uma grande fonte de recursos. A guerra da Ucrânia e os absurdos lockdowns na China causaram aumento de preços dentro do Japão por ruptura da cadeia de suprimentos.\nMas se o Japão não adotou medidas restritivas severas como, então, não teve um grande número de casos e de óbitos? Ainda no início da pandemia, estudos tentavam responder esse questionamento. Alguns aspectos culturais foram considerados, como a ausência de apertos de mão e abraços ao cumprimentar, a já presente cultura de uso de máscaras, alguns aspectos genéticos e uma possível ajuda da vacina BCG, obrigatória em crianças. Nenhuma dessas alternativas provavelmente responde por completo a questão. As máscaras, por exemplo, são utilizadas por pessoas de diversos países na Ásia para evitar rinite por pólen ou diminuir o efeito respiratório da poluição de grandes centros. Além disso, há estudos que mostram que máscaras são pouco efetivas para proteger contra infeção respiratória.\nTalvez uma explicação esteja no sistema de saúde e a experiência do país em outras epidemias respiratórias. A maneira como o país monitora casos de influenza é considerada modelo e há indícios que o protocolo utilizado, e que foi adotado inicialmente para a pandemia, tenha colaborado no tratamento nos estágios iniciais de COVID.\nPor fim, é interessante notar como a Itália, com expectativa de vida, mediana de idade, e PIB per capita similares aos do Japão, possui cerca de 4 vezes mais casos. Além disso, a população da Itália é de cerca de 60 milhões de habitantes, pouco menos da metade dos 125 milhões do Japão, de forma que a densidade populacional italiana é bem menor.\nLembrando, a Itália foi o país europeu mais afetado no início da pandemia. Em março de 2020, era o terceiro em total de casos e o primeiro em número de óbitos em todo o mundo. Na época, muito se falou sobre a idade da população, mas, como vemos agora, não se pode avaliar um único parâmetro já que, por idade, o Japão deveria ter dados similares.\nHá muito mais a ser analisado e nem sempre é possível resumir tudo em números que representam bem todo um país.\nEste artigo avalia como as 21 regiões administrativas italianas lidaram com o início da pandemia. Na Itália, cada região tem certa autonomia para organizar suas políticas de saúde. O artigo mostra como as regiões que adotaram hospitalização logo no início tiveram números piores do que outras regiões. Além disso, destaca como diferentes políticas de testagem dificultam a comparação de casos entre as regiões, um aspecto já levantado em outros contextos aqui neste estudo. Por fim, o artigo também destaca que cerca de um terço das mortes atribuídas ao COVID-19 até maio de 2020 ocorreram em casas de repouso para idosos e que não necessariamente este número é confiável.\nNovos casos # Até o momento focamos em avaliar a evolução do total de casos no mundo e em cada país. Agora, vamos verificar a evolução de novos casos, à medida que foram sendo reportados. Assim, podemos verificar em quais momentos houve maior notificação, as popularmente chamadas \u0026ldquo;ondas\u0026rdquo; de casos.\nA base de dados apresenta as entradas na forma de dados diários e na forma de média móvel de 7 dias. A média móvel ajuda a visualizar melhor a tendência dos dados, visto que há grande variação dos dados diários. Vamos começar com os casos em todo mundo:\nVemos que está surgindo um padrão de aceleração de casos e máximos. Em 2020, vimos três grandes saltos em novos casos, com inícios em março, em junho e em novembro. Em 2021, vimos novamente saltos em março e junho. Na virada de 2021 para 2022 tivemos um grande aumento de casos.\nPodemos verificar se há algum indício de relação entre novos casos e as variantes:\nEm 2020, vemos que o aumento de casos entre junho e julho ocorre após o surgimento da variante beta. De forma similar, após o surgimento da variante delta, ocorre o aumento significativo de casos entre outubro e novembro. Isso corrobora as afirmações veiculadas à época na mídia que tal variante era mais transmissível que as primeiras. Durante o ano de 2021, algumas variantes de menor impacto surgiram, mas ficaram pouco tempo como variantes de interesse na classificação da OMS. Em novembro de 2021, houve o surgimento da variante ômicron e, logo após sua identificação, o grande aumento no número de casos na passagem de 2021 para 2022.\nAgora, sabemos que em estações mais frias usualmente há mais casos de resfriados e gripes. Será que há alguma relação entre inverno e casos de COVID-19? Vejamos:\nVemos que há uma possível relação, repare os períodos entre junho e setembro dos anos de 2020 e 2021, e os períodos entre dezembro e março nas passagens de 2020 para 2021 e de 2021 para 2022. No entanto, o máximo ao final de abril de 2021 não encaixa nessa explicação. Como veremos adiante, este máximo é devido a casos na Índia, sendo devido a situações específicas deste país. Assim, podemos considerar que há uma forte correlação entre períodos de frio e casos de COVID, o que é característico de infecções respiratórias.\nVamos comparar os dados consolidados mundialmente com os dados individuais dos países que vimos anteriormente possuir mais casos:\nAqui vemos mais claramente como o pico entre abril e maio de 2021 possui grande influência da Índia. Na época, notícias também demonstravam uma certa dúvida nos motivos que levaram a Índia a ter esse surto de casos, suspeitando-se de novas variantes ou de espalhamento para os grandes centros urbanos. Posteriormente, ficou mais evidente o papel das eleições que ocorreram em algumas localidades. Também contribuiu o fato de milhares de pessoas, com medo do aumento de casos, recorrerem ao ritual de se dirigir ao rio Ganges para se banhar, já que o rio é considerado sagrado na cultura hindu.\nA escala linear do gráfico não é muito adequada para uma comparação. Vamos recriar o gráfico com uma escala logarítmica:\nVemos que, com exceção do período entre abril e setembro de 2020, os comportamentos de Estados Unidos, França e Alemanha possuem perfis similares. As curvas de Índia e Brasil não se assemelham entre si nem com os demais países, exceto no que diz respeito aos novos casos decorrentes da variante ômicron no início de 2022.\nPartimos agora para uma análise mais global. Já vimos que aparentemente há um caráter sazonal nos casos de COVID-19. Vamos criar um mapa que apresente esse perfil para cada país do mundo:\nPara interagir com o gráfico, clique na seta de play. No celular pode ser que o título fique cortado pelo tamanho da tela, mas funciona igual. Observe como as cores oscilam para os países enquanto o tempo passa, e como as oscilações não são sincronizadas. Compare, por exemplo, os Estados Unidos e o Brasil para perceber essa falta de sincronia. Será que conseguimos analisar esse comportamento a nível de continentes?\nVamos verificar o perfil de cada continente, ainda comparando com o acumulado mundial:\nAqui percebemos que o perfil da Ásia não acompanha fielmente o da Europa e o da América do Norte, mesmo estando todos estes continentes no mesmo hemisfério. Mas, como vimos, há grande efeito dos números da Índia no continente asiático e há diversos países suspeitos de subnotificação no mesmo continente, de forma que a comparação pode ser prejudicada.\nQuanto as continentes do hemisfério sul, não se pode afirmar claramente se há alguma tendência conjunta.\nÉ perceptível no gráfico o efeito da variante ômicron na Oceania. Como já discutido anteriormente, a política de COVID zero adotada por Austrália e Nova Zelândia fracassou e os dois países vêm enfrentando um grande aumento de casos.\nA dificuldade em encontrar padrões entre continentes é resultado da grande diferença de população entre os mesmos, além da posição geográfica e de possíveis subnotificações já citadas. Não necessariamente pertencer ao mesmo hemisfério significa ter estações do ano similares. Além de haver diversos fatores relacionados ao microclima de cada país/região e, obviamente, aspectos políticos e econômicos muito distintos. Apenas de forma ilustrativa, vejamos a população de cada continente e o total de casos por milhão de habitantes:\nlocation total_cases_per_million population Oceania 166,283 43,219,954 South America 130,621 434,260,137 North America 161,446 596,581,283 Europe 257,362 748,962,983 Africa 8,499 1,373,486,472 Asia 31,825 4,678,444,992 Veja como o total de casos por milhão é significativamente maior na Europa. O continente africano possui um número muito baixo de casos por milhão, conforme já discutido anteriormente. Quanto à Ásia, o valor baixo se deve a números não confiáveis de diversos países, pelos motivos vistos no início deste estudo, principalmente China e Indonésia. O caso da Oceania é um reflexo do grande número de casos da variante ômicron na Austrália e na Nova Zelândia.\nAssim como já discutido para o total de casos, talvez seja mais elucidativo comparar os novos casos por milhão de habitantes, para diminuir eventuais efeitos de países com grandes populações. Comecemos mostrando o perfil de novos casos por milhão para os países que anteriormente vimos serem os que possuem maior total de casos até o fim de abril de 2022:\nAqui percebemos como França e Alemanha foram muito afetadas pela variante ômicron, na passagem do ano 2021 para 2022. Muito mais que o Brasil, por exemplo. Novamente, fica evidente a importância de se comparar números relativos, e não números absolutos, quando se compara países. Os Estados Unidos também apresentaram muitos novos casos. Como já mostrado anteriormente, o grande aumento no período coincide com o inverno no Hemisfério Norte.\nVejamos o gráfico de novos casos por milhão de habitantes para os continentes:\nO gráfico está em escala logarítmica pois as ordens de grandeza mudam muito entre os continentes. Vemos como cada continente possui um comportamento próprio, tendo em vista que cada um possui países com especifidades próprias, conforme viemos discutindo durante todo o estudo. É perceptível que a variante ômicron foi significativa em todos os continentes.\nVejamos a evolução temporal de novos casos por milhão de habitantes através de um mapa:\nPara interagir com o gráfico, clique na seta de play. No celular pode ser que o título fique cortado pelo tamanho da tela, mas funciona igual. Assim como já visto no mapa para o número absoluto de novos casos, fica evidente o caráter sazonal, popularmente conhecido como \u0026ldquo;ondas\u0026rdquo; de casos.\nVejamos como foi o comportamento de novos casos considerando agregados de países com base na classificação de renda do Banco Mundial:\nAssim como já havíamos discutido para o total de casos, vemos que as ondas de novos casos possuem maior impacto em países de mais alta renda. A variante ômicron, na passagem de 2021 para 2022, é perceptível em todas as classificações.\nAgora, será que há alguma forma de medir a velocidade de transmissão da doença?\nTaxa efetiva de reprodução (R) # A taxa efetiva de reprodução (R) é o número médio de pessoas infectadas em determinado momento por um indivíduo infectado introduzido em uma população parcialmente imune. Atenção ao \u0026ldquo;parcialmente imune\u0026rdquo;, pois no início da pandemia muito se falava do R0, que é um conceito análogo mas para uma população completamente suscetível, ou seja, sem indivíduos imunizados seja por contágio prévio ou por vacinação.\nA interpretação do valor calculado de R é simples:\nR \u0026gt; 1: o número de casos da doença está aumentando. Epidemia. R = 1: cada infectado causa uma nova infecção. Endemia. R \u0026lt; 1: cada vez menos indivíduos se infectam e o número dos contágios retrocede. Vamos verificar se podemos visualizar alguma relação entre mudanças no valor de R, as diversas variantes e períodos de inverno:\nValores elevados aparecem apenas no início do período. É possível perceber leves aumentos coincidentes com os períodos de máximos de novos casos discutidos anteriormente. Mesmo a variante ômicron, reconhecível no gráfico pelo máximo em janeiro de 2022, não atingiu um valor de R comparável ao início da pandemia. Como se trata dos valores de todo o mundo, a curva pode estar sendo balanceada entre países com taxas elevadas e países com taxas baixas. Vamos refazer o gráfico com os dados dos cinco países com mais casos:\nAqui vemos mais flutuações. Os períodos de maiores valores coincidem com os períodos de aumento de novos casos vistos anteriormente.\nEm um primeiro momento, podemos pensar se há alguma relação entre a taxa de reprodução efetiva e a densidade populacional de um país. Afinal, mais pessoas próximas pode levar à uma maior transmissibilidade. Vamos verificar os países com maiores taxas de reprodução efetiva ao fim de abril de 2022 e verificar se há algum sinal de correlação:\nlocation continent population population_density reproduction_rate Taiwan Asia 23,855,008.00 NaN 2.19 Grenada North America 113,015.00 317.13 1.61 Jamaica North America 2,973,462.00 266.88 1.57 Mauritania Africa 4,775,110.00 4.29 1.57 Panama North America 4,381,583.00 55.13 1.55 Saint Lucia North America 184,401.00 293.19 1.53 Eswatini Africa 1,172,369.00 79.49 1.46 Guyana South America 790,329.00 3.95 1.46 South Africa Africa 60,041,996.00 46.75 1.41 Dominican Republic North America 10,953,714.00 222.87 1.38 Para interagir com o gráfico, passe o mouse pelos círculos ou clique nos nomes dos continentes para mostrá-los ou não. No celular pode ser que o título fique cortado pelo tamanho da tela, mas funciona igual. Vemos que as 7 maiores densidades populacionais do mundo estão com R abaixo de 1. Ao menos pelo gráfico, não parece haver uma correlação tão direta entre as duas variáveis, mas como são dinâmicas o ideal é fazer uma análise temporal e não estática como no caso. Perceba, também, que a variável escolhida para o tamanho dos círculos foi o total de casos por milhão em cada localidade. Veja que há localidades com grande quantidade de casos acumulados mas com R \u0026lt; 1, indicando que já tiveram momentos de maior contágio no passado mas que, em abril de 2022, estavam em momentos de retração de contágio.\nEvolução do número de mortes # Infelizmente alguns casos acabam levando a mortes. Vamos analisar como foi a evolução dos números.\nTotal de mortes # Mundo # Começando pelo total de mortes no mundo:\nObserve que a ordem de grandeza dos eixos verticais é bem menor que a vista no gráfico análogo referente ao número de casos. Voltaremos a esse ponto posteriormente.\nVejamos se há alguma possível relação entre o total de óbitos e as variantes:\nEnquanto nos gráficos de casos era possível perceber aumentos e eventualmente relacioná-los com variantes, vemos nos gráficos de mortes que não é tão evidente tal relação. Mesmo no caso da variante ômicron, não vemos um aumento na taxa de óbitos. Isto é um indicativo de que as variantes são menos letais que o vírus original. Na página do CDC - Centers for Disease Control and Prevention americano, o órgão afirma que a ômicron se espalha mais que as variantes anteriores, mesmo pessoas vacinadas podem contrair e passar a variante, mas é menos severa que as variantes anteriores.\nPrincipais países # Totais absolutos # Vamos verificar os países que possuem os maiores totais de óbitos até abril de 2022:\nlocation continent population total_deaths United States North America 332,915,074 993,665 Brazil South America 213,993,441 663,736 India Asia 1,393,409,033 523,843 Russia Europe 145,912,022 368,319 Mexico North America 130,262,220 324,334 Peru South America 33,359,415 212,810 United Kingdom Europe 68,207,114 175,081 Italy Europe 60,367,471 163,507 Indonesia Asia 276,361,788 156,257 France Europe 67,422,000 145,999 Vemos que o Brasil aparece em segundo, atrás apenas dos Estados Unidos. Também observamos a presença de outro país da América do Sul entre os 10 países: o Peru. Como tal país não possui população tão numerosa quanto os primeiros colocados, é um sinal que a proporção de mortes por milhão é alta, o que veremos mais adiante.\nVamos verificar o total de óbitos até o momento por país de cada continente:\nPara interagir com o gráfico, clique nos continentes para ter mais detalhes do mesmo. No celular pode ser que o título fique cortado pelo tamanho da tela, mas funciona igual. Totais por milhão de habitantes # Como já discutido ao apresentar os dados referentes a casos de COVID-19, números absolutos por vezes distorcem nossa percepção sobre os impactos reais em cada localidade. Faz mais sentido avaliar os números por milhão de habitantes. Vamos, então, construir a tabela e o gráfico:\nlocation continent total_deaths_per_million Peru South America 6,379.31 Bulgaria Europe 5,352.31 Bosnia and Herzegovina Europe 4,830.76 Hungary Europe 4,795.54 North Macedonia Europe 4,455.84 Montenegro Europe 4,321.31 Georgia Asia 4,223.10 Croatia Europe 3,877.84 Czechia Europe 3,744.21 Slovakia Europe 3,648.01 Percebe-se claramente que a situação do Peru é diferenciada. E tal situação vem chamando a atenção da mídia mundial e de periódicos especializados. As condições precárias em regiões mais pobres do país e problemas no setor de saúde parecem contribuir para o alto número de óbitos. Da mesma forma, a situação do leste europeu tem gerado manchetes nos principais veículos de mídia mundiais.\nVamos analisar a situação de cada país por continente:\nPara interagir com o gráfico, clique nos continentes para ter mais detalhes do mesmo. No celular pode ser que o título fique cortado pelo tamanho da tela, mas funciona igual. Observe como a Dinamarca, e seu território Ilhas Faroe, líder em casos por milhão, aparece como um dos países da Europa com menos mortes por milhão. Como discutido em outros trechos deste estudo, a mortalidade pode estar mais relacionada com aspectos sócio-econômicos e com o sistema de saúde de cada localidade do que com a agressividade da doença em si.\nOutro país que merece destaque é a Suécia. Na contramão de outros países europeus, em especial seus vizinhos da Escandinávia, o país não adotou políticas restritivas como lockdown durante a pandemia. Devido ao sistema legal do país, as decisões costumam ser descentralizadas para os ministérios, e estes não têm poder de lei. O Ministério da Saúde local adotou uma política de conscientização da população. As fronteiras com outros países foram fechadas, mas internamente as medidas foram brandas. Vemos nos dados de casos e de mortes que o país está dentre os menores números da Europa, chamando a atenção da mídia, indicando que tal política não levou ao caos que apoiadores de políticas restritivas diziam no início da pandemia. No entanto, como vemos nos gráficos, os números da Suécia são maiores que seus vizinhos escandinavos. Alguns estudos mostram que ocorreram mais mortes na porção de mais alta idade (acima de 80 anos) no país, comparado aos seus vizinhos, indicando possíveis problemas em casas de cuidados para idosos. Internamente, a visão é de que a política não restritiva foi, em geral, correta.\nJá fiz uma pequena discussão na parte de casos acerca de países que provavelmente estão com dados abaixo dos números reais. Mas aqui cabe mais algumas observações sobre este tópico.\nComeçando pela América do Sul, percebemos a quase ausência da Venezuela, com um número muito abaixo de seus vizinhos. Obviamente que a situação chamou a atenção a ponto de a Nature e o periódico BMJ irem verificar a situação. Como é de se esperar de regimes ditatoriais, há grande opressão governamental para abafar os casos e óbitos, além de falta de recursos básicos para controle da situação, conforme descrito nos links.\nNa América do Norte, apesar de boa parte da atenção midiática ser destinada aos Estados Unidos, vemos que Trinidade e Tobago e México possuem números de óbitos por milhão de habitantes comparáveis aos americanos.\nPor fim, um pouco sobre a África e a Ásia. De acordo com as Nações Unidas parte significativa dos países africanos e asiáticos não possuem registros de mortes confiáveis, conforme figura abaixo retirada do site da instituição. Desta forma, cuidado deve ser tomado ao se fazer comparações com estes países.\nHá também notícias como esta a respeito dos problemas de registro de óbitos em países africanos.\nVejamos um mapa interativo da evolução das mortes por milhão em cada país:\nPara interagir com o gráfico, clique na seta de play. No celular pode ser que o título fique cortado pelo tamanho da tela, mas funciona igual. Idade e riqueza # Vamos verificar se o número de mortes possui alguma relação com a renda per capita do país ou a idade da população.\nComecemos verificando os países com maior PIB per capita:\nlocation continent total_deaths total_deaths_per_million gdp_per_capita Qatar Asia 677.00 231.02 116,935.60 Macao Asia NaN NaN 104,861.85 Luxembourg Europe 1,064.00 1,676.08 94,277.96 Singapore Asia 1,335.00 244.79 85,535.38 Brunei Asia 218.00 493.74 71,809.25 Ireland Europe 7,087.00 1,422.26 67,335.29 United Arab Emirates Asia 2,302.00 230.41 67,293.48 Kuwait Asia 2,555.00 590.27 65,530.54 Norway Europe 2,932.00 536.44 64,800.06 Switzerland Europe 13,712.00 1,573.29 57,410.17 Já foi mostrado que a base de dados possui valores para agregados de países de acordo com a classificação de renda do Banco Mundial. Vejamos como estes agregados se comportam com relação ao total de mortes por milhão:\nVemos claramente que há mais mortes em países de renda alta, com quase duas ordens de grandeza mais casos que países de renda baixa. O perfil de crescimento é similar em todas as classificações. Observe como a faixa de valores deste gráfico, com máximo na ordem de 103, é bem mais baixa que a do gráfico análogo visto na seção sobre casos, cujo máximo era na ordem de 105.\nPaíses com maiores rendas tendem a ter uma população mais velha. Vejamos como isto se relaciona com mortes por COVID-19:\nPara interagir com o gráfico, passe o mouse pelos círculos ou clique nos nomes dos continentes para mostrá-los ou não. No celular pode ser que o título fique cortado pelo tamanho da tela, mas funciona igual. No gráfico, vemos claramente que os países do continente africano possuem, em sua maioria, menores expectativas de vida e menores PIB per capita (menores círculos no gráfico). Seicheles, que é país africano com maior PIB per capita com uma das maiores expectativas de vida do continente e chegou a liderar os dados mundiais em total de casos por milhão ao final de 2021, fica em segundo no continente no que diz respeito a mortes por milhão. No entanto, países dos demais continentes possuem números maiores de mortes.\nVemos uma tendência de localidades com maiores expectativas de vida apresentarem mais óbitos. Obviamente que países mais ricos tendem a ter maior parcela da população com idade avançada e, como a doença afeta mais pessoas idosas, é de se esperar maior quantidade de óbitos nesses países. No entanto, cabe destacar que há notáveis exceções nessa tendência como, por exemplo, o Japão, sobre o qual já fizemos uma extensa análise anteriormente. Singapura e Coreia do Sul também são notáveis exceções, sendo que vimos anteriormente que a Coreia do Sul figura entre os países com maiores números de casos totais. Vemos, portanto, que mais casos não necessariamente levam a mais óbitos. A Coreia do Sul não adotou lockdown como política de controle nem fechou estabelecimentos comerciais. Foi adotava uma política de muita testagem e de controle de distanciamento via celular e uso de cartão de crédito. O que gerou desconforto na população. E a política de hospitalização focou em pacientes de alto risco.\nNo gráfico, vemos que a expectativa de vida peruana é maior que a do Brasil, por exemplo, mas que o total de mortes por milhão de habitantes por COVID-19 é mais que o dobro da brasileira. Assim como já discutido em outros momentos do estudo, não se pode tirar grandes conclusões de apenas uma variável.\nUma maior expectativa de vida, no entanto, não necessariamente significa que a população atual possui mais idosos que jovens. Assim, vamos repetir o gráfico substituindo o eixo de expectativa de vida por mediana de idade:\nPara interagir com o gráfico, passe o mouse pelos círculos ou clique nos nomes dos continentes para mostrá-los ou não. No celular pode ser que o título fique cortado pelo tamanho da tela, mas funciona igual. Vemos a mesma tendência: população mais idosa, mais mortes. No entanto, o caso do Peru se torna ainda mais chamativo por fugir da tendência dos demais países.\nO segundo país com mais mortes por milhão é a Bulgária. Se ampliarmos o gráfico anterior na porção de maiores medianas de idade, veremos que a Bulgária possui a oitava maior mediana de idade do mundo (44,7 anos), mas é o país com menor PIB per capita entre os 10 países com maior mediana de idade. O país passa por uma crise demográfica há alguns anos, com sua população envelhecendo e diminuindo de tamanho, além de ter uma parcela cada vez maior da população próximo ao nível de pobreza. Este retrato búlgaro é similar, guardadas as especificidades de cada país, aos demais países do leste europeu que aparecem na listagem de mais mortes por milhão. A Bulgária acabou com restrições relativas ao COVID-19 no início de maio.\nO Peru possui uma mediana de idade bem menor que a búlgara, 29,1 anos, e um PIB per capita um terço menor. Conforme destacado em notícias e artigos, a situação de fragilidade econômica da população pode ter colaborado significativamente para a situação. Nas referências linkadas vemos, por exemplo, que cerca de 40 % das residências peruanas não possuem geladeiras, e estimasse que mais de 10 % das residências possuem mais pessoas que o recomendável para seus tamanhos. O país foi um dos primeiros a decretar lockdown na América do Sul, sendo até considerado modelo neste aspecto embora claramente não tenha ajudado, e a fornecer auxílio financeiro à sua população. No entanto, mais de um terço da população adulta não possui contas bancárias, não tendo acesso fácil ao auxílio.\nOutra comparação de interesse entre os dois países é quanto à vacinação de suas respectivas populações. Os dados completos de vacinação serão apresentados adiante, mas já podemos adiantar que o Peru possui 80 % de sua população com esquema vacinal completo, enquanto que a Bulgária possui apenas 29 %. Desta forma, não parece ser razoável explicar a situação peruana com base em apenas vacinas.\nNovas mortes # Até o momento focamos em avaliar a evolução do total de óbitos no mundo e em cada país. Agora, vamos verificar a evolução de novos óbitos, à medida que foram sendo reportados. Assim, podemos verificar em quais momentos ocorreram as popularmente chamadas \u0026ldquo;ondas\u0026rdquo;.\nA base de dados apresenta as entradas na forma de dados diários e na forma de média móvel de 7 dias. A média móvel ajuda a visualizar melhor a tendência dos dados, visto que há grande variação dos dados diários. Vamos começar com as mortes em todo mundo:\nVemos que os máximos em novos óbitos acompanham os máximos de novos casos já discutido anteriormente. Nota-se, entretanto, uma grande diminuição na ordem de grandeza de casos para óbitos, além de verificarmos uma tendência de queda nos óbitos. Por exemplo, enquanto a variante ômicron levou a um grande aumento de casos, vemos que, em termos de óbitos, não houve um aumento tão grande quando comparamos com outras variantes. Vejamos nos próximos gráficos, com as datas de variantes e épocas de inverno:\nA sazonalidade pode ser observada nos mapas interativos de novas mortes e novas mortes por milhão:\nPara interagir com o gráfico, clique na seta de play. No celular pode ser que o título fique cortado pelo tamanho da tela, mas funciona igual. Para interagir com o gráfico, clique na seta de play. No celular pode ser que o título fique cortado pelo tamanho da tela, mas funciona igual. Vejamos como foi o comportamento de novas mortes considerando agregados de países com base na classificação de renda do Banco Mundial:\nAssim como já havíamos discutido para novos casos, vemos que as ondas possuem maior impacto em países de mais alta renda. A variante ômicron, na passagem de 2021 para 2022, é perceptível em todas as classificações. No entanto, vemos que o incremento de mortes da ômicron é menor que de outras ondas do passado. Isto corrobora o que vem sendo mostrado no estudo e nas referências, que a ômicron é menos letal que variantes antecedentes.\nEvolução no número de vacinados # Certamente um dos pontos mais discutidos recentemente no contexto da pandemia. Vamos verificar a evolução.\nTotal de vacinados # Começando pelo total de vacinados:\nOs gráficos começam em dezembro de 2020, quando as primeiras doses foram aplicadas ao redor do mundo. Vemos que, até abril de 2022, cerca de 5,1 bilhões de pessoas já receberam ao menos uma dose da vacina, praticamente dois terços da população mundial. Os saltos nos gráficos se devem a questões de disponibilização dos dados.\nVejamos quantas pessoas já receberam todas as doses protocolares:\nVemos que uma parcela significativa da população mundial já tomou todas as doses protocolares. Segundo as diretrizes da OWID, são consideradas totalmente vacinadas as pessoas que receberam todas as doses inicialmente previstas no protocolo de cada vacina. Por exemplo, se uma vacina era prevista como sendo de duas doses, pessoas com duas doses são consideradas completamente vacinadas, mesmo que posteriormente não tenham tomado as doses de reforço. As doses de reforço são consideradas a parte, e podemos avaliá-las também:\nVemos que o número de doses de reforço aplicadas vem subindo consideravelmente desde o meio de 2021.\nVejamos quais países possuem mais pessoas vacinadas com ao menos uma dose:\nlocation continent population people_vaccinated China Asia 1,444,216,102 1,284,935,000 India Asia 1,393,409,033 1,003,162,202 United States North America 332,915,074 257,327,049 Indonesia Asia 276,361,788 199,346,528 Brazil South America 213,993,441 182,599,066 Pakistan Asia 225,199,929 134,313,917 Bangladesh Asia 166,303,494 128,729,921 Japan Asia 126,050,796 103,153,093 Mexico North America 130,262,220 85,797,486 Russia Europe 145,912,022 80,862,100 Vemos aqui que China e Índia, considerando suas imensas populações, já vacinaram com ao menos uma dose mais de três quartos das pessoas. Brasil e Estados Unidos também possuem quantidades significativas de pessoas vacinadas. Lembrando que não necessariamente o número a ser buscado é 100 % tendo em vista que os protocolos atuais não preveem vacinações em crianças.\nVamos verificar cada país por continente:\nPara interagir com o gráfico, clique nos continentes para ter mais detalhes do mesmo. No celular pode ser que o título fique cortado pelo tamanho da tela, mas funciona igual. Observe que o gráfico acima possui menos países que os mostrados anteriormente para casos e óbitos. Isto se deve ao fato de que nem todos os países possuem registros oficiais de vacinados de onde a OWID possa obter dados. O intervalo de disponibilização dos dados também é distinto para cada país, de forma que comparações devem ser feitas com cautela.\nAssim como para casos e óbitos, análises comparativas fazem mais sentido com números relativos ao total da população de cada localidade. Vejamos então os locais com maior percentual da população vacinada com ao menos uma dose:\nlocation continent population people_vaccinated_per_hundred Gibraltar Europe 33,691.00 124.88 United Arab Emirates Asia 9,991,083.00 98.99 Portugal Europe 10,167,923.00 95.42 Cuba North America 11,317,498.00 94.17 Samoa Oceania 200,144.00 93.63 Brunei Asia 441,532.00 93.32 Chile South America 19,212,362.00 93.25 Malta Europe 516,100.00 92.13 Singapore Asia 5,453,600.00 91.91 Cayman Islands North America 66,498.00 91.43 Obviamente que o valor para Gibraltar está equivocado. De acordo com a OWID, valores maiores do que 100 % podem ocorrer quando os valores para população estão desatualizados e/ou quando pessoas não residentes nos locais acabam entrando na conta como, por exemplo, turistas. No caso de Gibraltar, o aspecto turístico pode estar causando essa distorção.\nComo era de se esperar, vemos o predomínio de localidades relativamente pequenas no que diz respeito ao número de habitantes, aparecendo apenas o Chile com população acima de 15 milhões de pessoas. Vejamos um gráfico de países por continente:\nPara interagir com o gráfico, clique nos continentes para ter mais detalhes do mesmo. No celular pode ser que o título fique cortado pelo tamanho da tela, mas funciona igual. Observa-se que, para ao menos uma dose, a cobertura vacinal está razoável, com cerca de dois terços da população mundial (considerando apenas os países para os quais há dados). Apenas o continente africano ainda possui a maior parte dos países com menos de 50 % das pessoas vacinadas com ao menos uma dose.\nVejamos agora os números para pessoas completamente vacinadas:\nlocation continent population people_fully_vaccinated_per_hundred Gibraltar Europe 33,691.00 122.94 United Arab Emirates Asia 9,991,083.00 96.42 Brunei Asia 441,532.00 91.82 Singapore Asia 5,453,600.00 91.25 Chile South America 19,212,362.00 90.88 Malta Europe 516,100.00 90.74 Qatar Asia 2,930,524.00 88.80 Cayman Islands North America 66,498.00 88.49 Cuba North America 11,317,498.00 87.89 Portugal Europe 10,167,923.00 86.93 Para interagir com o gráfico, clique nos continentes para ter mais detalhes do mesmo. No celular pode ser que o título fique cortado pelo tamanho da tela, mas funciona igual. Alguns países merecem ser mencionados. Vimos no início deste estudo que a Dinamarca era o país com mais casos por milhão de habitantes e, agora, vemos que é o quinto mais vacinado da Europa. Também discutimos amplamente a situação de Austrália e Nova Zelândia, que enfrentam um grande aumento de casos da variante ômicron, sendo que ambos já vacinaram percentuais significativos de suas populações. Na América do Sul, o Peru, que já vacinou um percentual da população maior que o Brasil, por exemplo, possui o maior número óbitos por milhão de habitantes em todo o mundo. Na Ásia, mostramos que a Coreia do Sul é o oitavo país com mais casos no mundo e é o quinto mais vacinado na Ásia, sendo que possui números muito baixos de óbitos.\nAssim, vemos que não é simples avaliar o impacto real das vacinações a partir de números tão genéricos. Citamos exemplos de países com elevadas taxas de vacinação que tiveram problemas com surtos de novos casos ou com elevado número de mortes. Cabe destacar que se está olhando um retrato, um momento no tempo. Não necessariamente um país com elevada taxa de vacinação agora começou a aplicação cedo, pode ser que tenha começado a aplicação tardiamente e eventuais benefícios das vacinas não tenham sido aproveitados por sua população, levando a casos mais graves e óbitos. Da mesma forma, comparando os casos de Peru e Bulgária com os de Japão e Coreia do Sul, todos detalhados durante este estudo, vemos que o preparo da rede de saúde e as condições de vida da população têm efeito imenso no resultado final de casos e óbitos, eventualmente até mais que a vacinação em si.\nVejamos se há alguma relação entre quantidade de vacinados e PIB per capita e se países com pessoas mais velhas estão se vacinando mais:\nNeste primeiro gráfico, vemos como países de mais alta renda possuem um percentual de totalmente vacinados bem maior que baixas de renda mais baixa. Além disso, vemos como os classificados como de renda alta atingiram metade de pessoas vacinadas de forma muito mais rápida que países das demais classificações.\nPodemos adicionar mais camadas de informação, avaliando o perfil de idade, por exemplo:\nPara interagir com o gráfico, passe o mouse pelos círculos ou clique nos nomes dos continentes para mostrá-los ou não. No celular pode ser que o título fique cortado pelo tamanho da tela, mas funciona igual. Como já discutido anteriormente, países com maior PIB per capita tendem a ter uma população mais velha e, pelo gráfico, uma maior parcela da população vacinada. Faz sentido se considerarmos que há custo envolvido em adquirir as vacinas, de forma que países mais ricos tendem a conseguir adquirir vacinas mais facilmente e a ter melhores condições de realizar grandes campanhas de vacinação. O dado para Luxemburgo não está atualizado por problemas nos relatórios do país. É perceptível como países africanos, que possuem baixa mediana de idade e valores de PIB per capita baixos, também possuem baixo percentual de vacinados.\nNovas vacinações # Já vimos a evolução dos números totais, vejamos agora a evolução de novas vacinações:\nVemos que há uma tendência decrescente. Podemos considerar algumas hipóteses para este declínio que, provavelmente, ocorrem em conjunto:\na mais evidente é que à medida que mais pessoas completam o protocolo de vacinação, menos vacinas são tomadas; países mais pobres estão tendo dificuldades de adquirir vacinas. Conforme o artigo do link, há pressão para que as patentes das tecnologias aplicadas pelas grandes farmacêuticas sejam quebradas para que empresas locais possam fabricar as vacinas a um menor custo. Ou que sejam feitas colaborações com as tais empresas; menos pessoas querendo se vacinar, por diversos motivos como (evidências nos links): a crescente percepção pública e de cientistas de que as vacinas são menos eficazes do que inicialmente se pensava, especialmente devido ao surgimento de variantes; crescente desconfiança quanto a potenciais conflitos de interesse que eventualmente contribuíram para a aprovação emergencial das vacinas com triagem diferenciada e para o boicote a medicamentos utilizados no que ficou conhecido como tratamento precoce; crescente revolta entre a população de diversos países frente à imposição dos chamados passaportes de vacinação. Exemplos aqui e aqui. Muito embora durante todo o estudo tenham sido citadas referências mostrando que boa parte dos países já retiraram total ou parcialmente as restrições referentes à COVID, é pouco provável que pessoas que se sentiram agredidas em suas liberdades durante o período repressivo busquem se vacinar agora que as restrições foram levantadas. no mesmo sentido, a Áustria, que implementou lockdown para não vacinados, não vê seu número de vacinados aumentar, provavelmente porque tais pessoas que tiveram restringidas suas liberdades não se sentem motivadas a seguir recomendações forçadas. Além do aspecto de divisão social mostrado na referência. Desta forma, a crescente segregação das atividades permitidas ou não para aqueles que não se vacinaram pode estar contribuindo para que aqueles que não se vacinaram continuem com este posicionamento. eventuais riscos não previstos de algumas vacinas. Qual dos motivos apontados contribui mais ou se há mais algum motivo é difícil de avaliar com base nos dados disponíveis. No entanto, se verificarmos o perfil de novas vacinações com base na classificação de renda do Banco Mundial, gráfico a seguir, vemos que países de mais alta renda já estão com perfil decrescente de novas vacinações, enquanto que países de renda baixa estão em perfil crescente. Isto corrobora o escrito acima, sobre a dificuldade que países pobres estão tendo para adquirir vacinas.\nComparações e correlações # Já analisamos casos, óbitos e vacinações de forma separada. Vamos começar a buscar comparações e correlações. Primeiro, vamos comparar a ordem de grandeza entre casos, mortes e vacinações nos continentes:\nComo já abordado brevemente anteriormente, há uma diferença de cerca de duas ordens de grandeza entre casos e mortes. Podemos ver isto também em um gráfico com os mesmos dados por milhão de habitantes:\nEsta observação está coerente com estudos que indicam que a mortalidade da COVID-19 fica em torno de 1 a 2 %. Cabe ressaltar que há diferentes formas de cálculo e interpretações para mortalidade como mostra esse material da OMS, especialmente com a pandemia em andamento. E já vimos que há diversas questões envolvendo a disponibilização de dados por parte de alguns países.\nNo entanto, se confirmada essa faixa de mortalidade, a pandemia de COVID-19 seria proporcionalmente menos fatal que outras pandemias no último século. O que diferencia a COVID-19, segundo estudos, é sua alta transmissibilidade que a espalhou por todo o planeta, de forma que a contagem total de mortos se tornou elevada. Cabe ressaltar que, como toda comparação, cuidados devem ser tomados e há estudos que abordam tais cuidados, que fogem ao escopo deste trabalho.\nDurante a análise, em alguns momentos correlações de casos e óbitos com idade da população e PIB per capita foram estudadas. Vamos avaliar, através de matrizes de correlação, se há correlações positivas ou negativas entre variáveis. Comecemos procurando relações entre totais de casos/óbitos com vacinação, indicadores de riqueza e indicadores de idade:\nPodemos criar matriz similar mas para novos casos/óbitos/vacinações e suas relações com índices que variam no tempo:\nNas figuras acima temos algumas correlações mais óbvias e que já foram discutidas no decorrer do estudo, que são:\ncorrelação positiva entre idades mais avançadas e maior PIB per capita; correlação positiva entre mais pessoas vacinadas e maior PIB per capita; como consequência das anteriores, correlação positiva entre pessoas vacinadas e idades mais avançadas Outras correlações:\ncorrelação positiva entre pessoas vacinadas e casos por milhão; correlação negativa entre pessoas vacinadas e mortes por milhão; correlação positiva entre o índice de restrição e a taxa de reprodução efetiva; correlação positiva entre o índice de restrição e novas mortes; Estas duas últimas correlações, embora fracas, encontram respaldo em algumas publicações científicas recentes, como esta e esta, que parecem indicar ineficácia ou mesmo piora no número de casos e óbitos devido ao uso de medidas restritivas.\nMuito se fala sobre o efeito de comorbidades, vamos verificar se há correlações envolvendo as variáveis referentes a doenças:\nCuriosamente há relação negativa entre taxa de mortalidade por doenças cardiovasculares (lembrando que os dados de comorbidades são de 2017) e casos e óbitos. E há relação positiva entre mulheres fumantes e casos e óbitos, assim como para homens mas com valores menores. Não se pode fazer análises muito profundas com base nestes dados pois não significa que as pessoas que tiveram os casos ou morreram tinham as doenças ou fumavam. Os dados de fumantes e doenças são para cada localidade e não para cada indivíduo.\nBrasil # Para terminar, vamos abordar um pouco da situação brasileira. Em alguns momentos durante o estudo comentários já foram feitos acerca do país, então apenas complementaremos com mais algumas informações.\nComecemos verificando como a evolução de novos casos se relaciona com as datas de surgimento de novas variantes e com os períodos de inverno:\nNo gráfico há um aumento significativo de casos logo após a variante gama, cujo primeira amostra foi no país. No entanto, cabe ressaltar que as variantes podem demorar um certo tempo para se espalhar pelo mundo, de forma que as datas das outras variantes não necessariamente são estas no país.\nHá picos de casos nos invernos, porém os maiores picos foram entre março e maio de 2021 e janeiro e fevereiro de 2022. E no último inverno tivemos um pico no início da estação mas um perfil decrescente na parte final.\nO Ministério da Saúde, ao fim de abril de 2022, declarou o fim da emergência sanitária.\nVejamos o perfil de novos óbitos:\nVemos que o perfil de novos óbitos segue o de novos casos, mas em menor ordem de grandeza. Também é possível observar como a variante ômicron, que aumentou significativamente o número de casos, não aumentou na mesma proporção o número de óbitos.\nÉ interessante observar como o Brasil se compara com os demais países da América do Sul e, também, com os demais países classificados como de renda média alta na classificação do Banco Mundial. Comecemos com o total de casos por milhão de habitantes:\nVemos que o Brasil acompanha o perfil da América do Sul. No entanto, possui valores acima do agregado de países de renda média alta. No link do Banco Mundial sobre a classificação, vemos que nessa categoria há países como China, alguns africanos e asiáticos. Conforme descrito no início deste estudo, nem sempre números vindos destes locais são confiáveis. Desta forma, não necessariamente o país, e a América do Sul, estão tendo um desempenho pior para lidar com a doença que os demais países de mesma classificação.\nQuanto a novos casos, total de mortes e novas mortes, temos os seguintes gráficos:\nA mesma discussão feita para o total de casos por milhão pode ser estendida para novos casos, total de mortes e novas mortes.\nA seguir, vemos que tanto o Brasil acompanhou o perfil da América do Sul e dos demais países classificados como de renda média alta no quesito vacinação.\nInfelizmente a base de dados é bem incompleta para o Brasil. Há diversos dados ausentes referentes a hospitalizações e testes. Em breve farei um estudo focado no país utilizando dados oficias governamentais. Acompanhe meu perfil no LinkedIn para saber quando eu divulgar.\nConclusões # Foi um longo estudo, mas espero que tenha sido proveitoso e que tenha trazido novas visões a respeito da pandemia. Busquei colocar links para diversas notícias e estudos com o intuito de embasar afirmações e facilitar a compreensão por parte dos leitores. Vamos fazer uma breve recaptulação do que foi mostrado:\nevolução de casos e mortes e possíveis relações com variantes sazonalidade dos casos e mortes e possível relação com períodos de inverno importância de avaliar os dados por milhão de habitantes ao invés dos totais correlações existentes entre diversas variáveis Caso tenha dúvidas, comentários e/ou críticas construtivas me procure:\nLinkedIn GitHub Site Telegram Veja o repositório no GitHub para ter acesso ao código e à análise completa. Ou, se preferir, clique no ícone abaixo para abrir o trabalho completo no Google Colab:\nConheça meu portfolio.\n","externalUrl":null,"permalink":"/portfolio/2022-04-project_covid/","section":"Portfolio","summary":"It has been 2 years since the emergence of the COVID-19 virus.\nThe pandemic control measures adopted by governments around the world have\nsignificantly affected everyone’s routine. Now, most governments are\nrelaxing COVID restrictions despite high omicron variant spread. What can\nwe learn from COVID data?","title":"Global overview of COVID-19 - The omicron spread","type":"portfolio"},{"content":" This is a personal project of a scientific communication platform, focused on usage and development of technological tools. I show how we can use Python and software for a better understanding of scientific concepts and daily situations. I also cover Data Science topics and coding best practices.\nThe website and the YouTube channel have thousands of views per month.\nBelow, there are some articles from the website. I translated the titles to English, but the texts are written in Brazilian Portuguese.\nAnalyzing Olympics data with Pandas and Plotly Usain Bolt vs. Python: calculating the speed of an athlete Studying our atmosphere with Python Creating a virtual environment for your Python project Git and GitHub: definite guide to collaboration SymPy tutorials Chemical process mass balance with Python Top 3 chemistry Python packages Project links:\nSite YouTube. ","externalUrl":null,"permalink":"/portfolio/2020-ciencia-programada/","section":"Portfolio","summary":"This is a personal project of a scientific communication platform, focused on\nusage and development of technological tools. I show how we can use Python and\nsoftware for a better understanding of scientific concepts and daily\nsituations. I also cover Data Science topics and coding best practices.","title":"Science communication at Ciência Programada","type":"portfolio"},{"content":"As a Content Writer at Necto Systems, I specialized in crafting compelling articles for the company\u0026rsquo;s website, focusing on a variety of key topics.\nMy expertise in data analysis allowed me to provide insightful content that demonstrated the power of data-driven decision-making in business. I explored the intricate world of Business Intelligence, elucidating how it transforms raw data into meaningful insights for strategic planning.\nMy work also included detailed write-ups on the company\u0026rsquo;s cases, where I highlighted our successful strategies and solutions in addressing client needs.\nAdditionally, I delved into the realm of custom software development, offering a comprehensive view on how tailored software solutions can significantly enhance business operations and efficiency.\nThis diverse range of topics not only underlined my versatility as a writer but also showcased our company\u0026rsquo;s multifaceted expertise in the tech industry.\nBelow are the main articles I wrote during the period. The articles were written in Brazilian Portuguese. I have included the original title in Portuguese and a translation of the title in English.\nVocê confia nos dados e processos de sua empresa? — Do You Trust the Data and Processes of Your Company? Análise de Dados, Ciência de Dados e Engenharia de Dados: Entenda as Diferenças Para o Seu Negócio — Data Analysis, Data Science, and Data Engineering: Understanding the Differences for Your Business A Ponte entre Ciência de Dados e Sustentabilidade: Soluções de Software Personalizadas — The Bridge between Data Science and Sustainability: Customized Software Solutions Abordagens de Tomada de Decisão Baseada em Dados para PMEs — Data-Driven Decision-Making Approaches for SMEs Desmistificando a ciência de dados: uma introdução para empreendedores — Demystifying Data Science: An Introduction for Entrepreneurs O poder da análise descritiva: entendendo os dados do seu negócio — The Power of Descriptive Analysis: Understanding Your Business Data Melhore o atendimento ao cliente com ciência de dados — Enhance Customer Service with Data Science Como a ciência de dados pode melhorar seu marketing — How Data Science Can Improve Your Marketing Qualidade de dados em ambiente empresarial — Data Quality in a Business Environment You can access the articles on the Necto Systems website.\n","externalUrl":null,"permalink":"/portfolio/2023-content-writer/","section":"Portfolio","summary":"As a Content Writer for Necto Systems, I have enriched our website with engaging\narticles, covering areas such as data analysis, Business Intelligence, and custom\nsoftware development. My contributions offer insights into our successful cases,\nhighlighting how we leverage data and technology to drive business growth and\nefficiency. This diverse content reflects both my writing versatility and our\ncompany’s expertise in the tech sector.","title":"Content writer for Necto Systems","type":"portfolio"},{"content":" Researcher responsible for a development group of interactive educational software, based on the Python programming language and the Jupyter Notebook tool. The developed pieces of software are used in chemistry classes.\nThe group aims to show how computational tools can be used in real chemical problems. Jupyter Notebooks were chosen because they provide an easy way to integrate text, calculations, and visualizations.\nThe following chart and bullet points summarize the research group philosophy:\nGood practices (automated tests, version control with Git) Team management with Trello and GitHub Main scientific Python packages: NumPy, SciPy, SymPy, and Pandas Main visualization Python packages: Matplotlib and Plotly Here are some products of the project:\nPlanck\u0026rsquo;s Law interactive plot Interactive phase diagrams Interactive species diagrams Effective nuclear charge diagrams Ideal gases pressure x volume x temperature surface Comparing the solubility of inorganic compounds I have made some math related projects too, that can be seen here.\n","externalUrl":null,"permalink":"/portfolio/2015-professor_ifrj/","section":"Portfolio","summary":"I’m the researcher responsible for a development group of interactive\neducational software, based on the Python programming language and the Jupyter\nNotebook tool.","title":"Educational software development","type":"portfolio"},{"content":" I\u0026rsquo;m a chemist and, besides test tubes and colorful compounds, I also really love math. So, here are some math related projects, like truth-table generators and visualizations for abstract mathematical concepts.\nTruth table generator Fourier series convergence Integrals with Riemann Sums Matplotlove - animated heart-shaped math functions ","externalUrl":null,"permalink":"/portfolio/2019-math_projects/","section":"Portfolio","summary":"I’m a chemist and, besides test tubes and colorful compounds, I also really\nlove math. So, here are some math related projects, like truth-table\ngenerators and visualizations for abstract mathematical concepts.","title":"Math projects","type":"portfolio"},{"content":"A new version of this study can be found here.\nAbstract # It has been almost 2 years since the emergence of the COVID-19 virus. The pandemic control measures adopted by governments around the world have significantly affected everyone\u0026rsquo;s routine. With that in mind, it is of great interest to follow and evaluate the evolution of the pandemic to know its real effects and to consider the return to normal life. In this study, OWID data was used to see the evolution of cases, deaths, and vaccination. The impact of new variants on cases and deaths was shown as well as a possible relation with winter season.\nThe following page is written in Brazilian Portuguese.\nIntrodução # A COVID-19 é uma doença infecciosa causada por um recém-descoberto coronavírus.\nEstamos completando quase 2 anos desde o surgimento do vírus COVID-19. As medidas para controle pandêmico adotadas por governos em todo mundo afetaram significativamente a rotina de todos e é de grande interesse acompanharmos a evolução da pandemia para saber seus reais efeitos e avaliar o retorno ao convívio normal.\nAnimações como esta serão usadas no texto. Se quiser saber como fazer e ainda interagir com as animações, acompanhe até o final Neste trabalho, uma análise exploratória dos dados fornecidos pela Our World in Data (OWID) é feita, mostrando o avanço temporal de casos, óbitos e vacinação. Estudos comparativos e busca de correlações são feitos com intuito de melhor compreender os dados. Animações como a mostrada acima são mostradas e interpretadas.\nObtenção dos dados e bibliotecas utilizadas # Como já citado, os dados aqui utilizados são fornecidos pela Our World in Data (OWID) neste repositório, uma organização que reúne pesquisadores de todo o mundo para agregar dados de diversas fontes sobre os mais diversos problemas contemporâneos.\nObviamente que por ser uma doença recente cuidados devem ser tomados no que diz respeito à interpretação dos dados e relações de causa e efeito. Como será mostrado adiante, nem todos os países fornecem dados completos e há algumas inconsistências nos dados a depender de suas origens. Além disso, com o crescente conhecimento a respeito da doença, por vezes se faz necessário alterar a forma de agregar os dados, causando algumas dificuldades de análise temporal. Não podemos ignorar também o fato de que, infelizmente, a visão passada por veículos de mídia e governantes para população pode variar e ser distorcida a depender dos interesses momentâneos dos mesmos.\nAssim, durante esse estudo, especial cuidado é destinado em apresentar os dados e buscar interpretá-los de forma rigorosa deixando claros eventuais limitações, conflitos e condições de contorno de cada análise. E, sempre lembrando, correlações não implicam em causalidade.\nNo total, a base de dados possui 65 variáveis e 122.175 entradas. Há ausência de muitos dados sobre hospitalização e realização de testes por nem todos os países terem informações oficiais, de forma que essas categorias foram deixadas de fora desta análise.\nO pacote Pandas foi utilizado para trabalhar com os dados e construir matrizes de correlações. Os pacotes Matplotlib, Seaborn e Plotly foram utilizados para construir os gráficos. A biblioteca datetime, presente em uma instalação padrão do Python, foi utilizada para lidar com datas.\nA base de dados baixada apresenta entradas até 8 de outubro de 2021, quando foi obtida. Porém, há alguns dados cuja periodicidade é diferenciada. Desta forma, vamos considerar como última data para análise 30 de setembro de 2021 para termos apenas meses fechados, de janeiro de 2020 até setembro de 2021.\nEvolução do número de casos # Vamos começar nossa análise avaliando a evolução no número total de casos em todo o mundo.\nTotal de casos # Muito do que é exposto nas mídias foca na quantidade total de casos por país ou mundialmente. Vamos avaliar o perfil de crescimento no número de casos mundial:\nVemos que, desde o surgimento em meados de janeiro de 2020, foram necessários cerca de 3 meses para atingir 1 milhão de casos e 1 ano para 100 milhões de casos. Lembrando que esses são os casos efetivamente computados devido a testagem ou procura das pessoas pelas redes de saúde. O número real é potencialmente maior tendo em vista que a maioria dos casos é branda ou assintomática, de forma que os indivíduos não procuram as redes de saúde. De qualquer forma, considerando que a população mundial é estimada na ordem de 7,8 bilhões de pessoas, o número de casos até o momento indica que cerca de 3 % da população mundial já teve a doença.\nMuito se fala das variantes do vírus. A Organização Mundial da Saúde (OMS) em seu site descreve os critérios para considerar uma determinada variante como sendo de interesse ou preocupante. A OMS também esclarece que os nomes são dados um certo tempo depois que as primeiras amostras de cada variante são analisadas, conforme a tabela:\nVariante Data da primeira amostra Data do nome alfa Setembro/2020 - Reino Unido Dezembro de 2020 beta Maio/2020 - África do Sul Dezembro de 2020 gama Novembro/2020 - Brasil Janeiro de 2021 delta Outubro/2020 - Índia Abril de 2021 lambda Dezembro/2020 - Peru Junho de 2021 mu Janeiro/2021 - Colômbia Agosto de 2021 Neste estudo, optou-se por utilizar a data da primeira amostra nos gráficos, motivo pelo qual a beta aparece antes da alfa. Tal escolha se deve ao fato de a variante já estar se espalhando desde a data de amostra independentemente de ter recebido um nome. Vamos adicionar aos gráficos anteriores linhas indicando as datas de aparecimento de cada variante:\nO número de casos teve um acelerado crescimento inicial antes do surgimento da primeira variante (beta) e houve um aumento de 10 vezes entre as datas da variante beta e da variante alfa, um intervalo de 4 meses. O crescimento se torna, então, mais lento. Nos quatro meses entre as variantes alfa e mu o número de casos cresceu 3 vezes.\nVamos agora olhar os países com mais casos até setembro de 2021. Em um primeiro momento, podemos supor que países com maiores populações apresentem mais casos. Vamos verificar as maiores populações mundiais:\nPaís População China 1.444.216.102 Índia 1.393.409.033 Estados Unidos 332.915.074 Indonésia 276.361.788 Paquistão 225.199.929 Brasil 213.993.441 Nigéria 211.400.704 Bangladesh 166.303.494 Rússia 145.912.022 México 130.262.220 Agora, vamos verificar os países com mais casos:\nVemos que 4 países dentre os que apresentam maiores populações no mundo também figuram entre os com mais casos: Estados Unidos, Índia, Brasil e Rússia. Há a ausência da China, mas os dados de lá não são confiáveis tendo em vista o regime ditatorial, sendo que o país até hoje se nega a fornecer dados mais completos sobre a própria origem do vírus.\nOutra ausência que chama a atenção é a Indonésia. Novamente, devido a questões políticas, não se pode confiar totalmente nos dados reportados por tal país, visto que o próprio presidente da Indonésia afirmou em dado ponto que não estavam disponibilizando informações para \u0026ldquo;evitar pânico\u0026rdquo; na população.\nVemos por esses dois casos que há diversos fatores sociais, econômicos e políticos que podem afetar a análise. Há países entre as maiores populações que enfrentam questões políticas, econômicas e de saúde complicadas, como Paquistão, Bangladesh e Nigéria, que podem afetar a capacidade de tais países em acompanhar e reportar os casos adequadamente. Inclusive, de acordo com dados e relatórios das Nações Unidas, apenas dois terços dos países do mundo possuem registros de pelo menos 90 % dos nascimentos e óbitos e todos os países citados aparecem nos relatórios como países com dificuldades de registro.\nNeste estudo, vamos nos ater ao que é apresentado. Mas é importante notar tais situações.\nNo gráfico interativo a seguir temos a situação de cada país por continente:\nPara interagir com o gráfico, clique nos continentes para ter mais detalhes do mesmo. No celular pode ser que o título fique cortado pelo tamanho da tela, mas funciona igual. No gráfico, temos uma ideia da proporção do total de casos de cada país frente aos demais de seu continente e do mundo.\nMas será que essa é a melhor métrica para avaliar comparativamente a situação de cada país?\nUma análise do total absoluto de casos não necessariamente reflete a realidade de cada país. Afinal, como já dito, países com maiores populações tendem a ter maior número de casos. No entanto, isso não significa que países com populações pequenas não possam estar em situação pior. Afinal, podem, relativamente ao seu número de habitantes, estar com elevado número de casos considerando suas redes de saúde. E regiões com maiores densidades populacionais podem favorecer uma maior taxa de transmissão (hipótese que será estudada mais adiante).\nVamos, então, verificar os países com mais casos por milhão de habitantes:\nPercebemos uma grande mudança, aparecendo pequenos países. Em primeiro temos Seicheles, um país insular do continente africano, tendo um grande fluxo de turistas. Já em maio de 2021 notícias surgiam mostrando o aumento de casos no país apesar de ter sido o mais vacinado do mundo (proporcionalmente à sua população) na época.\nInclusive, vemos no gráfico outros países que atingiram rapidamente elevadas taxas de vacinação e, mesmo assim, tiveram picos de novos casos como, por exemplo, Israel. Veremos dados de vacinação mais adiante.\nVamos ver em um gráfico interativo mostrando cada país por continente:\nVeja como a análise proporcional muda significativamente o perfil do gráfico. Todos os países que apareciam como líderes em totais absolutos não figuram entre os que possuem mais casos por milhão de habitantes, com exceção dos Estados Unidos. Na Europa, vemos uma maior participação de países do leste europeu que, inclusive, parece estar entrando em uma nova onda. Na América do Sul, vemos que o Brasil se encontra em terceiro, atrás de Argentina e Uruguai, países que foram considerados modelos em diversos estágios da pandemia com suas medidas restritivas e lockdowns.\nVamos ver um mapa interativo mostrando a evolução do total de casos por milhão em cada país. A consolidação foi feita por mês apenas para deixar a animação do mapa mais rápida, se fosse evolução diária seria uma animação bem demorada.\nCaso queira interagir com o mapa, clique na animação que você será redirecionado para uma plataforma onde pode verificar mais detalhes. Mas termine de ler o texto primeiro ;-) Vemos no mapa que apenas alguns países da África apresentaram significativa evolução no número de casos. Como já escrito anteriormente, provavelmente isso está relacionado com as precárias condições de tais países em reportar adequadamente casos e mesmo realizar testes. No entanto, como será mostrado adiante, o perfil mais jovem da população também pode ter alguma relação, já que a doença é mais branda em jovens, o que pode fazer com que menos pessoas busquem tratamento, ficando de fora dos números oficiais. Há alguns estudos que sugerem tal explicação, além de outras.\nVemos na Oceania poucos casos na Austrália e na Nova Zelândia. Os dois países adotaram políticas altamente restritivas e questionáveis buscando zerar novos casos e se veem forçados a afrouxar tais políticas por não terem tido o efeito desejado e estarem quebrando suas economias.\nIdade e PIB per capita # Para verificar se o número de casos possui alguma relação com o PIB per capita do país ou a idade da população, vamos criar um gráfico interativo buscando avaliar como os casos variam com a expectativa de vida e o PIB per capita:\nNo gráfico vemos claramente que os países do continente africano possuem, em sua maioria, menores expectativas de vida e menores PIB per capita (menores círculos no gráfico). No entanto, Seicheles, país africano com maior PIB per capita e uma das maiores expectativas de vida do continente, lidera os dados mundiais em total de casos por milhão.\nVemos uma tendência similar em outros continentes, maiores expectativas de vida e PIB per capita com mais casos. Obviamente que países mais ricos tendem a ter populações mais velhas ou, melhor dizendo, maior parcela da população com idade avançada e, como a doença afeta mais pessoas idosas, é de se esperar maior notificação de casos nesses países. No entanto, cabe destacar que há notáveis exceções à essa tendência como, por exemplo, o Japão.\nUma maior expectativa de vida, no entanto, não necessariamente significa que a população atual possui mais idosos que jovens. Assim, vamos repetir o gráfico substituindo o eixo de expectativa de vida por mediana de idade:\nVemos a mesma tendência: população mais velha, mais casos notificados.\nNovos casos # Até o momento, focamos em avaliar a evolução do total de casos no mundo e em cada país. Agora, vamos verificar a evolução de novos casos, à medida que foram sendo reportados. Assim, podemos verificar em quais momentos houve maior notificação, as popularmente chamadas \u0026ldquo;ondas\u0026rdquo; de casos.\nA base de dados apresenta as entradas na forma de dados diários e na forma de média móvel de 7 dias. A média móvel ajuda a visualizar melhor a tendência dos dados, visto que há grande variação dos dados diários. Vamos começar com os casos em todo mundo:\nVemos que está surgindo um padrão de aceleração de casos e máximos. Em 2020 vimos três grandes saltos em novos casos, por volta de março/abril, por volta de junho/julho e por volta de outubro/novembro. Em 2021, já vimos novamente saltos em abril e julho, ficando a expectativa de novo crescimento de casos na parte final do ano.\nPodemos verificar se há algum indício de relação entre novos casos e as variantes:\nEm 2020, vemos que o aumento de casos entre junho e julho ocorre após o surgimento da variante beta. De forma similar, após o surgimento da variante delta, ocorre o aumento significativo de casos entre outubro e novembro. Isso corrobora as afirmações veiculadas frequentemente na mídia que tal variante, assim como as que surgiram posteriormente, são mais transmissíveis.\nAgora, sabemos que em estações mais frias usualmente há mais casos de resfriados e gripes. Será que há alguma relação entre inverno e casos de COVID-19? Vejamos:\nVemos que há uma possível relação, repare os períodos entre junho e setembro de ambos os anos e o período entre dezembro de 2020 e março de 2021. No entanto, o máximo entre abril e maio de 2021 não encaixa muito bem nessa explicação.\nVamos comparar os dados consolidados mundialmente com os dados individuais dos países que vimos anteriormente possuir mais casos:\nAqui vemos mais claramente como o pico entre abril e maio de 2021 possui grande influência da Índia e talvez seja decorrente de algo específico deste país. Na época, notícias também demonstravam uma certa dúvida nos motivos que levaram a Índia a ter esse surto de casos, suspeitando-se de novas variantes ou de espalhamento para os grandes centros urbanos.\nVamos verificar o perfil de cada continente, ainda comparando com o acumulado mundial:\nAqui percebemos que o perfil da Ásia não acompanha fielmente o da Europa e o da América do Norte, mesmo estando todos estes continentes no mesmo hemisfério. Mas, como vimos, há grande efeito dos números da Índia no continente asiático e há diversos países suspeitos de subnotificação no mesmo continente, de forma que a comparação pode ser prejudicada.\nQuanto as continentes do hemisfério sul, não se pode afirmar claramente se há alguma tendência conjunta.\nA dificuldade em encontrar padrões entre continentes é resultado da grande diferença de população entre os mesmos, além da posição geográfica e de possíveis subnotificações já citadas. Não necessariamente pertencer ao mesmo hemisfério significa ter estações do ano similares. Além de haver diversos fatores relacionados ao microclima de cada país/região e, obviamente, aspectos políticos e econômicos muito distintos. Apenas de forma ilustrativa, vejamos a população de cada continente:\nContinente População Oceania 43.219.954 América do Sul 434.260.138 América do Norte 596.581.283 Europa 747.747.396 África 1.373.486.472 Ásia 4.679.660.580 Já vimos que aparentemente há um caráter sazonal nos casos de COVID-19. Vamos criar um mapa que apresente esse perfil para cada país. Assim como já discutido para o total de casos, talvez seja mais elucidativo comparar os novos casos por milhão de habitantes, para diminuir eventuais efeitos de países com grandes populações:\nCaso queira interagir com o mapa, clique na animação que você será redirecionado para uma plataforma onde pode verificar mais detalhes. Mas termine de ler o texto primeiro ;-)\nObserve como as cores oscilam para os países enquanto o tempo passa, e como as oscilações não são sincronizadas. Compare, por exemplo, os Estados Unidos e o Brasil para perceber essa falta de sincronia.\nAgora, será que há alguma forma de medir a velocidade de transmissão da doença?\nTaxa efetiva de reprodução (R) # A taxa efetiva de reprodução (R) é o número médio de pessoas infectadas em determinado momento por um indivíduo infectado introduzido em uma população parcialmente imune. Atenção ao \u0026ldquo;parcialmente imune\u0026rdquo;, pois no início da pandemia muito se falava do R0, que é um conceito análogo mas para uma população completamente suscetível, ou seja, sem indivíduos imunizados seja por contágio prévio ou por vacinação.\nA interpretação do valor calculado de R é simples:\nR \u0026gt; 1: o número de casos da doença está aumentando. Epidemia R = 1: cada infectado causa uma nova infecção. Endemia R \u0026lt; 1: cada vez menos indivíduos se infectam e o número dos contágios retrocede. Vamos verificar se podemos visualizar alguma relação entre mudanças no valor de R e as diversas variantes:\nValores elevados aparecem apenas no início do período. É possível perceber leves aumentos coincidentes com os períodos de máximos de novos casos discutidos anteriormente. Como se trata dos valores de todo o mundo, a curva pode estar sendo balanceada entre países com taxas elevadas e países com taxas baixas. Vamos refazer o gráfico com os dados dos cinco países com mais casos:\nAqui vemos mais flutuações, especialmente no caso do Reino Unido. Os períodos de maiores valores coincidem com os períodos de aumento de novos casos vistos anteriormente.\nEm um primeiro momento, podemos pensar se há alguma relação entre a taxa de reprodução efetiva e a densidade populacional de um país. Afinal, mais pessoas próximas pode levar à uma maior transmissibilidade. Vamos verificar os países com maiores taxas de reprodução efetiva ao fim de setembro de 2021 e verificar se há algum sinal de correlação:\nVemos que Singapura, localidade com segunda maior densidade populacional do mundo, apresentava ao final de setembro de 2021 a maior taxa de reprodução. No entanto, Mônaco, maior densidade, está com valor de R \u0026lt; 1. Ao menos pelo gráfico, não parece haver uma correlação tão direta entre as duas variáveis mas, como são dinâmicas, o ideal é fazer uma análise temporal e não estática como no caso. Perceba, também, que a variável escolhida para o tamanho dos círculos foi o total de casos por milhão em cada localidade. Veja que há localidades com grande quantidade de casos acumulados mas com R \u0026lt; 1, indicando que já tiveram momentos de maior contágio no passado mas que, em setembro de 2021, estavam em momentos de retração de contágio.\nEvolução do número de mortes # Infelizmente alguns casos acabam levando a mortes. Vamos analisar como foi a evolução dos números.\nTotal de mortes # Começando pelo total de mortes no mundo:\nObserve que a ordem de grandeza dos eixos é bem menor que a vista no gráfico análogo referente ao número de casos. Voltaremos a esse ponto posteriormente.\nVamos verificar os países que possuem os maiores totais de óbitos até setembro de 2021:\nVemos que o Brasil aparece em segundo, atrás apenas dos Estados Unidos. Também observamos a presença de dois outros países da América do Sul entre os 10 países: o Peru e a Colômbia. Como tais países não possuem populações tão numerosas quanto os primeiros colocados, é um sinal que a proporção de mortes por milhão em tais países é alta, o que veremos mais adiante.\nComo já discutido ao apresentar os dados referentes a casos de COVID-19, números absolutos por vezes distorcem nossa percepção sobre os impactos reais em cada localidade. Faz mais sentido avaliar os números por milhão de habitantes.\nPercebe-se claramente que a situação do Peru é diferenciada. E tal situação vem chamando a atenção da mídia mundial e de periódicos especializados. As condições precárias em regiões mais pobres do país e problemas no setor de saúde parecem contribuir para o alto número de óbitos. Da mesma forma, a situação do leste europeu tem gerado manchetes nos principais veículos de mídia mundiais.\nVamos analisar a situação de cada país por continente:\nJá fiz uma pequena discussão na parte de casos acerca de países que provavelmente estão com dados abaixo dos números reais. Mas aqui cabem mais algumas observações sobre este tópico.\nComeçando pela América do Sul, percebemos a quase ausência da Venezuela, com um número muito abaixo de seus vizinhos. Obviamente que tal fato chamou a atenção a ponto de a Nature e o periódico BMJ irem verificar a situação. Como é de se esperar de regimes ditatoriais, há grande opressão governamental para abafar os casos e óbitos, além de falta de recursos básicos para controle da situação, conforme descrito nos links.\nNa América do Norte, apesar de boa parte da atenção midiática ser destinada aos Estados Unidos, vemos que o México possui maior número de óbitos por milhão de habitantes.\nPor fim, um pouco sobre a África e a Ásia. De acordo com as Nações Unidas parte significativa dos países africanos e asiáticos não possuem registros de mortes eficientes, conforme figura abaixo, retirada do site da instituição. Desta forma, cuidado deve ser tomado ao se fazer comparações com estes países.\nHá também esta notícia a respeito dos problemas de registro de óbitos em países africanos.\nVejamos um mapa interativo da evolução das mortes por milhão em cada país:\nCaso queira interagir com o mapa, clique na animação que você será redirecionado para uma plataforma onde pode verificar mais detalhes. Mas termine de ler o texto primeiro ;-)\nNovas mortes # Até o momento focamos em avaliar a evolução do total de óbitos no mundo e em cada país. Agora, vamos verificar a evolução de novos óbitos, à medida que foram sendo reportados. Assim, podemos verificar em quais momentos ocorreram as popularmente chamadas \u0026ldquo;ondas\u0026rdquo;.\nA base de dados apresenta as entradas na forma de dados diários e na forma de média móvel de 7 dias. A média móvel ajuda a visualizar melhor a tendência dos dados, visto que há grande variação dos dados diários. Vamos começar com as mortes em todo mundo:\nVemos que os novos óbitos acompanham o perfil de novos casos já discutido anteriormente, notando-se apenas uma grande diminuição na ordem de grandeza. Desta forma, as mesmas discussões e relações observadas com as datas de variantes e épocas de inverno se mantêm.\nDa mesma maneira, as comparações com os países com mais casos e com os continentes individuais feitas na discussão sobre os casos continuam válidas para os óbitos. Assim como a sazonalidade observada para novos casos. Para o artigo não ficar muito longo, retirei os gráficos desta parte. Caso queira verificar todos os gráficos e análises, veja o repositório linkado ao fim do artigo.\nEvolução no número de vacinados # Certamente um dos pontos mais discutidos recentemente no contexto da pandemia. Vamos verificar a evolução.\nTotal de vacinados # Começando pelo total de vacinados:\nOs gráficos começam em dezembro de 2020, quando as primeiras doses foram aplicadas ao redor do mundo. Vemos que, até setembro de 2021, cerca de 3,5 bilhões de pessoas já receberam ao menos uma dose da vacina, praticamente metade da população mundial. Os saltos nos gráficos se devem a questões de disponibilização dos dados.\nVejamos quantas pessoas já receberam todas as doses protocolares:\nAgora, quais países possuem mais pessoas vacinadas com ao menos uma dose:\nVemos aqui que a Índia, considerando sua imensa população, já vacinou com ao menos uma dose cerca de metade das pessoas. Brasil e Estados Unidos também possuem quantidades significativas de pessoas vacinadas. Lembrando que não necessariamente o número a ser buscado é 100 % tendo em vista que os protocolos atuais não preveem vacinações em crianças.\nAssim como para casos e óbitos, análises comparativas fazem mais sentido com números relativos ao total da população de cada localidade. Vejamos, então, os locais com maior percentual da população vacinada:\nObviamente que o valor para Gibraltar está equivocado. De acordo com a OWID, valores maiores do que 100 % podem ocorrer quando os valores para população estão desatualizados e/ou quando pessoas não residentes nos locais acabam entrando na conta como, por exemplo, turistas. No caso de Gibraltar, o aspecto turístico pode estar causando essa distorção.\nComo era de se esperar, vemos o predomínio de localidades relativamente pequenas no que diz respeito ao número de habitantes. Vejamos um gráfico de países por continente:\nObserve que o gráfico acima possui menos países que os mostrados anteriormente para casos e óbitos. Isto se deve ao fato de que nem todos os países possuem registros oficiais de vacinados de onde a OWID possa obter dados. O intervalo de disponibilização dos dados também é distinto para cada país, de forma que comparações devem ser feitas com cautela.\nVejamos se há alguma relação entre quantidade de vacinados e PIB per capita e se países com pessoas mais velhas estão se vacinando mais:\nComo já discutido anteriormente, países com maior PIB per capita tendem a ter uma população mais velha e, pelo gráfico, uma maior parcela da população vacinada. Faz sentido se considerarmos que há custo envolvido em adquirir as vacinas, de forma que países mais ricos tendem a conseguir adquirir vacinas mais facilmente e a ter melhores condições de realizar grandes campanhas de vacinação.\nNovas vacinações # Já vimos a evolução dos números totais, vejamos agora a evolução de novas vacinações:\nVemos que há uma tendência decrescente. Podemos considerar algumas hipóteses para este declínio que, provavelmente, ocorrem em conjunto:\na mais evidente é que à medida que mais pessoas completam o protocolo de vacinação, menos vacinas são tomadas; países mais pobres estão tendo dificuldades de adquirir vacinas. Conforme o artigo do link, há pressão para que as patentes das tecnologias aplicadas pelas grandes farmacêuticas sejam quebradas para que empresas locais possam fabricar as vacinas a um menor custo. Ou que sejam feitas colaborações com as tais empresas; menos pessoas querendo se vacinar, por diversos motivos como (evidências nos links): a crescente percepção pública e de cientistas de que as vacinas são menos eficazes do que inicialmente se pensava, especialmente devido ao surgimento de variantes; crescente desconfiança quanto a potenciais conflitos de interesse que eventualmente contribuíram para a aprovação emergencial das vacinas com triagem diferenciada e para o boicote a medicamentos utilizados no que ficou conhecido como tratamento precoce; crescente revolta entre a população de diversos países frente à imposição dos chamados passaportes de vacinação. Exemplos aqui e aqui. Qual dos motivos apontados contribui mais ou se há mais algum motivo é difícil de avaliar com base nos dados disponíveis.\nComparações e correlações # Já analisamos casos, óbitos e vacinações de forma separada. Vamos começar a buscar comparações e correlações. Primeiro, vamos comparar a ordem de grandeza entre casos, mortes e vacinações:\nComo já abordado brevemente anteriormente, há uma diferença de cerca de duas ordens de grandeza entre casos e mortes. Podemos ver isto também em um gráfico com os mesmos dados por milhão de habitantes:\nEsta observação está coerente com estudos que indicam que a mortalidade da COVID-19 fica em torno de 1 a 2 %. Cabe ressaltar que há diferentes formas de cálculo e interpretações para mortalidade como mostra esse material da OMS, especialmente com a pandemia em andamento. E já vimos que há diversas questões envolvendo a disponibilização de dados por parte de alguns países.\nNo entanto, se confirmada essa faixa de mortalidade, a pandemia de COVID-19 seria proporcionalmente menos fatal que outras pandemias no último século. O que diferencia a COVID-19, segundo estudos, é sua alta transmissibilidade que a espalhou por todo o planeta, de forma que a contagem total de mortos se tornou elevada. Cabe ressaltar que, como toda comparação, cuidados devem ser tomados e há estudos que abordam tais cuidados, que fogem ao escopo deste trabalho.\nDurante a análise, em alguns momentos correlações de casos e óbitos com idade da população e PIB per capita foram estudadas. Vamos avaliar, através de matrizes de correlação, se há correlações positivas ou negativas entre variáveis. Comecemos procurando relações entre totais de casos/óbitos com vacinação, indicadores de riqueza e indicadores de idade:\nPodemos criar matriz similar mas para novos casos/óbitos/vacinações e suas relações com índices que variam no tempo:\nNas figuras acima temos algumas correlações mais óbvias e que já foram discutidas no decorrer do estudo, que são:\ncorrelação positiva entre idades mais avançadas e maior PIB per capita; correlação positiva entre mais pessoas vacinadas e maior PIB per capita; como consequência das anteriores, correlação positiva entre pessoas vacinadas e idades mais avançadas Outras correlações:\ncorrelação positiva entre pessoas vacinadas e casos por milhão; correlação negativa entre pessoas vacinadas e mortes por milhão; correlação positiva entre o índice de restrição e a taxa de reprodução efetiva; correlação positiva entre o índice de restrição e novos casos; correlação positiva entre o índice de restrição e novas mortes; Estas três últimas correlações, embora fracas, encontram respaldo em algumas publicações científicas recentes, como esta e esta, que parecem indicar ineficácia ou mesmo piora no número de casos e óbitos devido ao uso de medidas restritivas.\nMuito se fala sobre o efeito de comorbidades, vamos verificar se há correlações envolvendo as variáveis referentes a doenças:\nCuriosamente, há correlação negativa entre taxa de mortalidade por doenças cardiovasculares (lembrando que os dados são de 2017) e casos e óbitos. E há correlação positiva entre mulheres fumantes e casos e óbitos, assim como para homens mas com valores menores. Não se pode fazer análises muito profundas com base nestes dados pois não significam que as pessoas que tiveram os casos ou morreram tinham as doenças ou fumavam. Os dados de fumantes e doenças são para cada localidade e não para cada indivíduo.\nBrasil # Para terminar, vamos abordar um pouco da situação brasileira. Em alguns momentos durante o estudo, comentários já foram feitos acerca do país, então apenas complementaremos com mais informações.\nComecemos verificando como a evolução de novos casos se relaciona com as datas de surgimento de novas variantes e com os períodos de inverno:\nNo gráfico há um aumento significativo de casos logo após a variante gama, cuja primeira amostra foi no país. No entanto, cabe ressaltar que as variantes podem demorar um certo tempo para se espalhar pelo mundo, de forma que as datas das outras variantes não necessariamente são estas no país.\nHá picos de casos nos invernos, porém o maior pico foi entre março e maio de 2021. E no último inverno tivemos um pico no início da estação mas, um perfil decrescente na parte final.\nVejamos o perfil de novos óbitos:\nVemos que o perfil de novos óbitos segue o de novos casos, mas em menor ordem de grandeza.\nInfelizmente a base de dados é bem incompleta para o Brasil. Há ausência de diversos dados referentes a hospitalizações e testes. Em breve farei um estudo focado no país utilizando dados oficias governamentais. Acompanhe meu perfil no LinkedIn para saber quando eu divulgar.\nConclusões # Foi uma longa análise, mas espero que tenha sido proveitoso e que tenha trazido novas visões a respeito da pandemia. Busquei colocar links para diversas notícias e estudos com o intuito de embasar afirmações e facilitar a compreensão por parte dos leitores. Vamos fazer uma breve recaptulação do que foi mostrado:\nevolução de casos e mortes e possíveis relações com variantes sazonalidade dos casos e mortes e possível relação com períodos de inverno importância de avaliar os dados por milhão de habitantes ao invés dos totais correlações existentes entre diversas variáveis Caso tenha dúvidas, comentários e/ou críticas construtivas me procure:\nLinkedIn GitHub Site Telegram Veja o repositório no GitHub para ter acesso ao código e à análise completa. Ou, se preferir, clique no ícone abaixo para abrir o trabalho completo no Google Colab:\nConheça meu portfolio.\n","externalUrl":null,"permalink":"/portfolio/2021-10-projeto_covid/","section":"Portfolio","summary":"It has been almost 2 years since the emergence of the COVID-19 virus.\nThe pandemic control measures adopted by governments around the world have\nsignificantly affected everyone’s routine. With that in mind, it is of great\ninterest to follow and evaluate the evolution of the pandemic to know its real\neffects and to consider the return to normal life.","title":"Global overview of COVID-19","type":"portfolio"},{"content":" Use of Python and Pandas package to evaluate the students’ performance in a Chemistry Olympiad at an educational institution.\nThe project is open to the institution staff and students. The aim is to show how data analysis can be made with Python and how it can provide useful insights.\nProject highlights:\ndescriptive statistics in a real-world project the data can be used in the statistics courses of the institution demonstration of data analysis using Pandas demonstration of high-quality visualizations using Matplotlib chicolucio/estatisticas-oiq-2019 Projeto de análise estatística da Olimpíada Interna de Química de uma instituição de ensino. Jupyter Notebook 0 0 ","externalUrl":null,"permalink":"/portfolio/2019-estatisticas-oiq/","section":"Portfolio","summary":"Use of Python and Pandas package to evaluate the students’ performance in a\nChemistry Olympiad at an educational institution.","title":"Statistical analysis of student grades with Python","type":"portfolio"},{"content":" Managed the Central Analytical Facility of the Chemistry Institute at UFF - Universidade Federal Fluminense, a Brazilian federal university. Increased the availability of the laboratory equipment. Automated the scheduling and usage report processes. Launched training courses.\nHighlights:\nAutomated the analyses scheduling process with Google Suite Increased the availability of laboratory equipment by 100 % Automated the equipment usage report with Python Launched equipment training and data analysis courses More than one hundred students, technicians, and teachers trained Built and implemented the standardization and process workflow for access and training on each laboratory and all equipment of the Facility Training courses offered by me:\nData analysis with Excel Data analysis with Origin Zeta potential and particle size analyses - Malvern Zetasizer Nano ZS90 Thermogravimetric analyses - Shimadzu DTG-60 Spectrophotometric analyses - Varian Cary 50 Spectrophotometric analyses - Varian Cary 5000 Spectrophotometric analyses - FTIR Varian 660 ","externalUrl":null,"permalink":"/portfolio/2014-2015-quimico_uff/","section":"Portfolio","summary":"Manager of Central Analytical Facility at the Chemistry Institute at UFF.\nI worked in the automation of the analyses scheduling process using Google\nSuite. I have also implemented the standardization and process workflow\nfor access and training on each laboratory and all equipment of the Facility.","title":"Laboratory manager","type":"portfolio"},{"content":" Environmental Analyst at GEAG (acronym for Management of Water Quality Assessment in Portuguese). I worked in the automation of reports and forms using Excel spreadsheets, besides collaborated with implementation of ISO/IEC 17025 in Environmental Analysis Laboratory.\nHighlights:\nPhysical-chemical analyses of industrial wastewater and natural water bodies Automated environmental indicator reports with Excel Improved team productivity by 25 % Collaborated in the implementation process of ISO/IEC 17025 at Environmental Analysis Laboratory ","externalUrl":null,"permalink":"/portfolio/2014-2014-inea/","section":"Portfolio","summary":"Environmental Analyst at GEAG (acronym for Management of Water Quality\nAssessment in Portuguese). I worked in the automation of reports and forms\nusing Excel spreadsheets, besides collaborated with implementation of ISO/IEC\n17025 in Environmental Analysis Laboratory.","title":"Environmental analyst at INEA","type":"portfolio"},{"content":" During my bachelor\u0026rsquo;s, I was the pioneer in the line of research Synthesis and characterization of coordination compounds as prototypes of bioreductive prodrugs. I work on this line until the end of my college years and during my master\u0026rsquo;s. In common language, the research aims to develop compounds that, in a tumor microenvironment, would release drugs to cancer treatment.\nIt is a multidisciplinary research. I developed:\nspectrophotometric and electrochemical methods to follow the release of the drug computational studies to model the electronic configuration of the compounds new synthetic routes a great experience using Excel, Origin and computational chemistry tools Related papers:\nComplexes activated by hypoxia: a strategy against cancer Isomerism and nuclearity control in bis(lawsonato)zinc(II) complexes Lawsone Dimerization in Cobalt(III) Complexes toward the Design of New Prototypes of Bioreductive Prodrugs A study on the properties and reactivity of naphthoquinone–cobalt(III) prototypes for bioreductive prodrugs ","externalUrl":null,"permalink":"/portfolio/2008-2013-pesquisa/","section":"Portfolio","summary":"Project developed during my bachelor’s and master’s degree programs. During\nthe development I acquired a vast knowledge in experimental data analysis\nusing Excel and Origin, besides a great experience in synthesis techniques and\ncharacterization of organic and inorganic compounds. As a result, 4 papers\nwere published in scientific journals and I received the Laureate Academic\nAward of my university.","title":"Synthesis and characterization of anticancer compounds","type":"portfolio"},{"content":" Full Name Email Address Message ","externalUrl":null,"permalink":"/contact/","section":"Francisco Bustamante","summary":"","title":"Contact","type":"page"},{"content":" Abstract # Senior Data Scientist specialized in building end-to-end ML solutions, from Big Data processing to deployment. Currently leveraging Generative AI to optimize recommendations at LuizaLabs (via TeclaT). Experience includes delivering analytics for Uber, predictive modeling for Climatempo (both via Necto Systems), and teaching Data Science. Former academic researcher with a strong scientific background.\nProfessional Experience # 2025 - Present: Senior Data Scientist at LuizaLabs (via TeclaT) # TeclaT (Contract) — Assigned to LuizaLabs, the technology arm of Magazine Luiza (Magalu), a leading Brazilian omnichannel retailer, as a Senior Data Scientist in the Recommendations team, improving search and product discovery at scale.\nAdapted and productionized a multi-interest two-tower deep learning recommendation model generating user/item embeddings for approximate nearest neighbor (ANN) retrieval. The model yielded a 33% lift in clicks, multiplying generated orders by 2.5x and overall revenue by over 3x in a key personalized interest recommendation showcase. Improved “Buy It Again” repurchase recommendations with up to 10% Recall@10 lift and up to 20% coverage increase (category-dependent) by shifting to a curated, entity-based consumables scope. Designed full MLOps pipelines: PySpark feature engineering orchestrated via Airflow DAGs, distributed PyTorch training on Kubernetes (GPU cluster, Helm-charted CronJobs, deployed via ArgoCD/GitOps), model export, and experiment/artifact tracking with MLflow. Designed and launched online A/B tests to evaluate models\u0026rsquo; recommendation performance. Built GenAI intent/semantic feature extraction for ranking models using vLLM + LangChain + Llama. 2025: Data Scientist at NECTO Systems # Worked at Climatempo, a major weather intelligence company in Brazil, via NECTO Systems. Delivered a full-cycle data science solution:\nReplaced experience-based heuristics with a data-driven outage risk scoring framework, grounding decisions in meteorological signals rather than prior-year occurrence patterns alone. Integrated weather time series (rainfall, wind, temperature) with grid/asset and historical incident data; engineered spatiotemporal features to capture storm intensity and exposure. Trained and validated predictive models (e.g., tree-based ML) with time-based backtesting; delivered interpretable drivers to support operational decision-making. Operationalized outputs into monitoring/decision workflows (dashboards/alerts), standardizing risk assessment and reducing subjectivity across shifts. Delivered reproducible code with full documentation, assisted in technical transfer, and supported initial deployment in internal pipelines Click here for a more detailed description of the project.\nAdditionally, worked on a short-term assignment at Ball Corporation, a global leader in sustainable aluminum packaging, where I:\nDesigned an analytics solution to integrate packaging-material inventories, production capacity, and sales plans into a unified planning view Developed Python (pandas) and SQL ETL pipelines plus advanced Excel automation to consolidate and standardize multiple data sources Built Power BI dashboards to monitor stock coverage and capacity vs. demand, reducing manual reporting effort and supporting data-driven decisions 2023 - 2025: Python and Data Science Instructor at Hashtag Treinamentos # Hashtag Treinamentos is one of Brazil’s largest online education providers, having trained over 80,000 students in Python and Data Science.\nLed the creation and review of comprehensive teaching materials on Python libraries (NumPy, Pandas, Matplotlib, Seaborn, Scikit-Learn, TensorFlow, PyTorch, Streamlit, Plotly/Dash), ensuring up-to-date and industry-aligned content. Produced video tutorials on SQL, Git, virtual environments, and Python best practices. Improved the Net Promoter Score (NPS) of Data Science courses by 30% through continuous feedback loops and content optimization. Introduced real-world projects to the curriculum, covering fraud detection, customer churn prediction, marketing campaign optimization, price optimization, and computer vision. Developed 15 hands-on projects simulating practical industry scenarios. Provided ongoing support to students by answering questions, reviewing code, and offering additional resources to facilitate comprehension of complex topics. Click here for a more detailed description of this entry, with a list of projects specially tailored for educational purposes and that have a hands-on approach towards real-world applications.\n2022 - 2023: Data Analyst at Uber (through NECTO Systems) # Allocated to Uber via NECTO Systems — a company specializing in bespoke software solutions — focusing on accounting reconciliation and improving fiscal processes.\nUtilized SQL, Python (Pandas), Hive, and Presto for large-scale data analysis and processing. Cleaned and standardized data from multiple sources, ensuring data accuracy and integrity. Reviewed and optimized existing data pipelines, improving overall efficiency and reducing error rates by 20%. Validated reconciled data for compliance with international accounting standards. Assisted Uber in adopting compatible accounting practices and meeting fiscal requirements. Implemented automated data search and reconciliation pipelines using data engineering techniques, reducing processing time by 15%. Click here for a more detailed description of the project.\nIn addition to my project responsibilities, I contributed to NECTO Systems' blog, authoring articles on the application of analysis and data science in industrial and business environments, thereby sharing insights on leveraging data for informed decision-making and operational efficiency.\n2020 - Present: Science communicator at Ciência Programada # Created personal projects aimed at combining science communication with programming.\nPublished over 100 articles and created video content explaining programming concepts, Python libraries (Pandas, Matplotlib, etc.), and data-driven approaches to scientific problems. Covered coding best practices, Git, and testing methodologies. Attracted thousands of monthly visitors, broadening understanding of science and programming. To see the project website click here (Brazilian Portuguese)\n2015 - 2022: Researcher and Professor at IFRJ - Instituto Federal de Educação, Ciência e Tecnologia do Rio de Janeiro (Brazil) # Launched a research group on educational software for chemistry, leveraging Python for data visualization (Matplotlib, Plotly), data analysis (Pandas, NumPy, SciPy), and version control (Git). Supervised 3 undergraduate research students, coordinating projects using Trello. Delivered Physical Chemistry lectures to over 500 students, integrating hands-on experience with Excel and Python to boost employability skills. To see the projects I\u0026rsquo;ve developed related to this experience click here\n2014 - 2015: Chemist - Laboratory manager at UFF - Universidade Federal Fluminense (Brazil) # Oversaw the Central Analytical Facility, scheduling equipment usage and training. Increased equipment availability by 100% through improved resource management. Automated laboratory usage reports using Python and Excel, significantly streamlining workflows. Designed and launched training programs for laboratory equipment operations and data analysis, training over 100 participants. To see the projects I\u0026rsquo;ve developed related to this experience click here\n2014: Environmental analyst at INEA - Instituto Estadual do Ambiente do Rio de Janeiro (Brazil) # Automated environmental indicator reports in Excel, improving team productivity by 25%. Contributed to implementing ISO/IEC 17025 standards at the Environmental Analysis Laboratory. To see the projects I\u0026rsquo;ve developed related to this experience click here\n2012 - 2014: Researcher and Professor at UFF - Universidade Federal Fluminense (Brazil) # Supervised two projects focused on creating low-cost educational resources. Taught chemistry classes and implemented exercises integrating real-world chemical data analysis. Education # Licenses \u0026amp; certifications # 2020 Course: Python Pro Skills: Python; Django framework; Test Driven Development (TDD); Heroku; Docker. Course: Data Science Pro Skills: Python data science tools such as Pandas; Jupyter Notebooks; Google Colab; Matplotlib. 2019 Course: Data Science by Data Bootcamp Skills: Python data science tools such as Pandas; Jupyter Notebooks; Google Colab; Matplotlib. 2018 Introduction to Computer Science and Programming Using Python by MITx at edX Academic experience # To see the projects I\u0026rsquo;ve developed during my education click here.\nMaster\u0026rsquo;s Degree in Chemistry, Universidade Federal Fluminense - 2010-2012 # Conducted extensive data analysis using Excel and Origin. Published three research papers in international peer-reviewed journals. Served on organizing committees for two scientific symposia. Bachelor\u0026rsquo;s Degree in Chemistry, Universidade Federal Fluminense - 2006-2010 # Published one scientific paper in a national peer-reviewed journal. Winner of the Alumni Laureate Award due to high academic performance ","externalUrl":null,"permalink":"/about/","section":"Francisco Bustamante","summary":"","title":"Curriculum Vitae","type":"page"},{"content":"I\u0026rsquo;m a Senior Data Scientist with solid experience in Python, SQL, machine learning, and Generative AI. I specialize in building end-to-end data solutions — from big data processing and cleaning to modeling and deployment — with a strong focus on turning data into actionable insights.\nCurrently, I am part of the recommendations team at LuizaLabs (via Tecla T), leveraging LLMs and BigQuery to enhance the e-commerce experience. Previously, I developed predictive models for meteorology and energy infrastructure at Necto Systems (including work with Climatempo), supported accounting analytics at Uber, and taught Python and Data Science at Hashtag Treinamentos.\nBefore moving into the tech industry, I spent over a decade in academia. I founded a research group focused on developing visual tools to teach abstract chemistry concepts, and held roles as a lab manager, environmental analyst, and scientific researcher.\nI’m also the creator of Ciência Programada, a science communication project (in Brazilian Portuguese) that uses Python to explain scientific ideas and methods.\n","externalUrl":null,"permalink":"/","section":"Francisco Bustamante","summary":"","title":"Francisco Bustamante","type":"page"},{"content":"Here you can find projects I have worked on with a brief description. Follow the links to more details about each one.\n","externalUrl":null,"permalink":"/portfolio/","section":"Portfolio","summary":"","title":"Portfolio","type":"portfolio"}]