<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sheenal Srivastava on Medium]]></title>
        <description><![CDATA[Stories by Sheenal Srivastava on Medium]]></description>
        <link>https://medium.com/@sheenalsrivastava?source=rss-42bf180d6f14------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*yG0f3skzMkw6d09K.</url>
            <title>Stories by Sheenal Srivastava on Medium</title>
            <link>https://medium.com/@sheenalsrivastava?source=rss-42bf180d6f14------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 16:10:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sheenalsrivastava/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Harnessing Analytics for ESG: Navigating Australia’s New Sustainability Landscape]]></title>
            <link>https://medium.com/@sheenalsrivastava/harnessing-analytics-for-esg-navigating-australias-new-sustainability-landscape-69d4622f8ee5?source=rss-42bf180d6f14------2</link>
            <guid isPermaLink="false">https://medium.com/p/69d4622f8ee5</guid>
            <category><![CDATA[esg-reporting]]></category>
            <category><![CDATA[esg-strategy]]></category>
            <category><![CDATA[esg-analytics]]></category>
            <dc:creator><![CDATA[Sheenal Srivastava]]></dc:creator>
            <pubDate>Mon, 11 Nov 2024 23:29:06 GMT</pubDate>
            <atom:updated>2024-11-11T23:29:06.909Z</atom:updated>
            <content:encoded><![CDATA[<p>Leveraging Data Insights to Meet Regulatory Demands and Drive Sustainable Growth</p><p>In recent years, Environmental, Social, and Governance (ESG) reporting has gained significant traction in Australia. This shift is largely driven by new legislation and policies aimed at enhancing transparency and accountability in corporate sustainability practices. The Australian government has introduced <a href="https://treasury.gov.au/consultation/c2023-402245">mandatory ESG reporting </a>for major companies and financial institutions, starting from 2024. This move aligns with the country’s commitment to achieving <a href="https://www.businessthink.unsw.edu.au/articles/esg-standards-changing-impact-business">net-zero emissions by 2050</a> and is part of a broader effort to integrate sustainable practices into the financial system. The Australian Accounting Standards Board (AASB) has also finalized the <a href="https://kpmg.com/au/en/home/insights/2024/09/24ru-12-australian-sustainability-reporting-standards-legislation-finalised.html">Australian Sustainability Reporting Standards (ASRS),</a> which include <a href="https://www.pwc.com.au/assurance/esg-reporting/australian-sustainability-reporting-standards.html">mandatory climate-related disclosures</a>. These regulations ensure that companies disclose their climate-related plans, financial risks, and opportunities, providing investors and the public with a clearer understanding of corporate sustainability strategies.</p><h3>Why ESG Data Matters?</h3><p>ESG data encompasses various aspects, including energy consumption, carbon emissions, water usage, waste management, working conditions, diversity, and more.</p><p>Companies need to track and report these metrics to demonstrate their commitment to sustainability and responsible practices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*fDQmDuygfNsuTEUIef4BAw.png" /><figcaption>Image taken from <a href="https://sigmaearth.com/what-is-an-esg-statement/">https://sigmaearth.com/what-is-an-esg-statement/</a></figcaption></figure><h3>The Role of Analytics</h3><p><strong><em>Data Collection and Integration: </em></strong>Analytics enables efficient data collection from various sources, including structured (ERP systems, performance data) and unstructured (media, satellite imagery) data.</p><p><strong><em>Risk Management: </em></strong>By analysing ESG data, companies can identify risks related to climate change, social issues, and governance. For example, stress testing climate scenarios helps assess portfolio vulnerabilities.</p><p><strong><em>Performance Monitoring: </em></strong>Robust metrics reporting allows companies to track progress toward ESG goals and identify areas for improvement.</p><h3><strong>The Benefits of Analytics in ESG Reporting</strong></h3><p>Analytics plays a crucial role in ESG reporting by transforming raw data into actionable insights. Here are some key benefits:</p><ul><li><em>Enhanced Decision-Making:</em> Analytics helps organizations make informed decisions by providing a comprehensive view of their ESG performance. This includes identifying areas for improvement and tracking progress over time.</li><li><em>Risk Management:</em> By analyzing ESG data, companies can identify potential risks related to environmental impact, social responsibility, and governance practices. This proactive approach helps mitigate risks before they escalate.</li><li><em>Regulatory Compliance:</em> With the introduction of mandatory ESG reporting standards, analytics ensures that companies comply with regulatory requirements by accurately tracking and reporting relevant data.</li><li><em>Investor Confidence:</em> Transparent and reliable ESG reporting, backed by robust analytics, enhances investor confidence. Investors are increasingly considering ESG factors in their investment decisions, and comprehensive analytics can provide the necessary assurance.</li></ul><h3>Examples of ESG Analytics</h3><ol><li><strong>Carbon Footprint Analysis</strong>: This involves measuring and analyzing a company’s greenhouse gas emissions. By understanding their carbon footprint, companies can implement strategies to reduce emissions and improve their environmental impact.</li><li><strong>Social Impact Assessment</strong>: Analytics can evaluate the social impact of a company’s operations, such as employee welfare, community engagement, and diversity and inclusion initiatives. This helps companies enhance their social responsibility efforts.</li><li><strong>Governance Metrics</strong>: Analyzing governance data, such as board diversity, executive compensation, and ethical practices, provides insights into a company’s governance structure and effectiveness. This can lead to improved governance practices and greater accountability.</li><li><strong>Supply Chain Sustainability</strong>: ESG analytics can assess the sustainability of a company’s supply chain by evaluating factors like supplier environmental practices, labor conditions, and ethical sourcing. This ensures that the entire supply chain aligns with the company’s ESG goals.</li></ol><p>By leveraging analytics, companies can not only meet regulatory requirements but also drive meaningful improvements in their ESG performance, ultimately contributing to a more sustainable and equitable future.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69d4622f8ee5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Fiction to Function: The Real Benefits of Synthetic Data]]></title>
            <link>https://medium.com/@sheenalsrivastava/from-fiction-to-function-the-real-benefits-of-synthetic-data-6f202ec50eda?source=rss-42bf180d6f14------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f202ec50eda</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[synthetic-data]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Sheenal Srivastava]]></dc:creator>
            <pubDate>Mon, 11 Nov 2024 23:04:10 GMT</pubDate>
            <atom:updated>2024-11-11T23:04:10.471Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Innovate with Confidence: The Synthetic Data Advantage</strong></p><p>In a recent client project, I faced the challenge of working with a limited dataset, where increasing the sample size to introduce sufficient variation was essential. Although I had previously used techniques like SMOTE to address imbalances in classification datasets, I had not yet explored the use of synthetic data for non-classification problems. This experience led me to investigate how synthetic data could improve the accuracy of regression models. I hope you find this blog post valuable, as synthetic data offers numerous benefits beyond merely solving the issue of small datasets.</p><h3>What is Synthetic Data?</h3><p><strong>Synthetic data</strong> is information that has been artificially generated to mimic the underlying statistical properties and patterns of existing real-world data. It is created using statistical algorithms and simulations, and is a valuable resource when businesses are concerned with scarcity of data, private or sensitive information, or data integrity. Synthetic data provides a solution to the challenges outlined above by providing a flexible and scalable alternative. It offers a controlled and customisable dataset that can be tailored to specific business needs; thereby enabling users to generate diverse and representative data, improving the robustness and performance of machine learning (ML) and artificial intelligence (AI) models.</p><h3>Advantages of Synthetic Data</h3><p>Leveraging synthetic data provides significant advantages as outlined below.</p><ol><li><strong>Privacy and Compliance:</strong> Synthetic data eliminates the risk of exposing sensitive information, making it easier to comply with privacy regulations.<br>2. <strong>Cost-Effective: </strong>Generating synthetic data is often cheaper and faster than collecting and processing real data.<br>3. <strong>Bias Reduction</strong>: Synthetic data can be designed to reduce or eliminate biases present in real data, leading to fairer AI models.<br>4. <strong>Scalability: </strong>Synthetic data can be produced in large quantities on demand, providing ample data for training and testing.<br><strong>5. Flexibility: </strong>It allows for the creation of data that may be rare or difficult to capture in the real world, enhancing the diversity of training datasets.</li></ol><p>Synthetic data offers enhanced privacy, scalability, and improved model accuracy, making it a powerful tool for modern data-driven applications.</p><h3>10 Use Cases for Synthetic Data</h3><p>Synthetic data has a wide range of applications across various industries. Here are 10 common use cases.</p><ol><li><strong>Training Machine Learning Models:</strong> Synthetic data is often used to train machine learning models, especially when real data is scarce or imbalanced. It helps in creating diverse and representative datasets, improving model accuracy and robustness.<br><strong>2. Data Augmentation:</strong> In scenarios where existing datasets are limited, synthetic data can be used to augment the data, providing additional samples that help in better training and validation of models3.<br><strong>3. Testing and Validation:</strong> Synthetic data is valuable for testing and validating software and algorithms. It allows developers to simulate a wide range of scenarios and edge cases without the need for real data4.<br><strong>4. Privacy and Security:</strong> Synthetic data helps in protecting privacy by generating data that mimics real data without containing any actual personal information. This is crucial for complying with data privacy regulations like GDPR.<br><strong>5. Healthcare:</strong> In healthcare, synthetic data can be used to simulate patient data for research and development, enabling studies and trials without compromising patient privacy.<br><strong>6. Financial Services:</strong> Synthetic data is used in financial services for fraud detection, risk assessment, and customer behavior analysis. It allows for the creation of realistic transaction data without exposing sensitive information.<br><strong>7. Autonomous Vehicles:</strong> Companies like Waymo use synthetic data to train and test self-driving car algorithms, simulating various driving conditions and scenarios.<br><strong>8. Natural Language Processing (NLP):</strong> Synthetic data is used to train NLP models, such as chatbots and virtual assistants, by generating diverse conversational data.<br><strong>9. Retail and E-commerce:</strong> Synthetic data helps in analyzing customer behavior, optimizing inventory, and personalizing marketing strategies without relying on real customer data.<br>10. <strong>Robotics: </strong>In robotics, synthetic data is used to train robots in simulated environments, allowing them to learn and adapt to different tasks and conditions.</li></ol><h3>Synthetic Data Generators (Open-sources)</h3><p>The tools mentioned below can generate synthetic data for various applications, ensuring privacy and compliance while enabling robust data analysis and machine learning model training.</p><ol><li><strong>Synthetic Data Vault (SDV):</strong> SDV is a comprehensive library that provides tools for generating synthetic data for tabular, relational, and time series data. It uses various models, including generative adversarial networks (GANs), to create realistic synthetic datasets.</li><li><strong>CTGAN (Conditional Table GAN):</strong> CTGAN is a deep learning-based synthetic data generator specifically designed for tabular data. It excels at handling complex datasets with intricate relationships and dependencies among features.</li><li><strong>DoppelGANger:</strong> DoppelGANger uses GANs to generate synthetic time-series data. It’s particularly useful for applications in finance and IoT, capturing intricate patterns and dependencies found in real-world data.</li><li><strong>Copulas:</strong> Copulas is a Python library for modeling multivariate distributions and sampling from them using copula functions. It allows for the generation of synthetic data that preserves the statistical properties of the original dataset.</li><li><strong>Faker:</strong> Faker is a Python package that generates fake data for various purposes, such as testing and development. While it doesn’t generate synthetic data in the traditional sense, it provides dummy data for a wide range of fields.</li><li><strong>Synthea:</strong> Synthea is an open-source synthetic patient generator that models the medical history of synthetic patients. It’s widely used in healthcare research to simulate realistic patient data.</li><li><strong>YData-synthetic:</strong> YData-synthetic is a Python package that provides tools for generating synthetic structured data. It supports various data types and is designed to help with data augmentation and privacy-preserving data sharing.</li></ol><h3>Challenges from using Synthetic Data</h3><p>Creating realistic synthetic data comes with several challenges.<br><strong>1. Accuracy :</strong> Ensuring that synthetic data accurately represents the statistical properties and patterns of real-world data is difficult. If the synthetic data is not realistic enough, it can lead to misleading or biased results when used for training AI models.<br><strong>2. Complexity of Real-World Data</strong>: Real-world data is often complex and varied, containing intricate relationships and dependencies. Capturing these nuances in synthetic data requires sophisticated algorithms and models.<br><strong>3. Privacy Concerns:</strong> While synthetic data is designed to protect privacy, there is still a risk that it could inadvertently reveal sensitive information if not properly anonymized. Ensuring that synthetic data is both useful and privacy-preserving is a significant challenge.<br><strong>4. Bias and Representativeness:</strong> Synthetic data can inherit biases present in the real data it is based on. Additionally, if the synthetic data generation process is not carefully managed, it can introduce new biases. Ensuring that synthetic data is representative and unbiased is crucial for fair and accurate AI models.<br><strong>5. Validation and Verification: </strong>Verifying the quality and reliability of synthetic data is challenging. There are limited standardised methods for assessing how well synthetic data mimics real data. This makes it difficult to ensure that synthetic data is suitable for its intended use.<br><strong>6. Resource Intensive: </strong>Generating high-quality synthetic data can be resource-intensive, requiring significant computational power and expertise. This can make it less accessible for smaller organizations or those with limited resources.<br><strong>7. Acceptance and Trust:</strong> There can be skepticism and resistance to using synthetic data, especially in critical applications like healthcare and finance. Building trust in the reliability and effectiveness of synthetic data is essential for its broader adoption.</p><p>Addressing these challenges requires ongoing research and development to improve the methods and technologies used for generating synthetic data. By overcoming these hurdles, synthetic data can become a more reliable and widely accepted tool in AI and data science.</p><h3>Validating Synthetic Data</h3><p>Despite the challenges that arise from the use of synthetic data, there are several common methods organisations use to validate the information.</p><ol><li><strong>Statistical Comparison:</strong> Compare the statistical properties of synthetic data with real data. This includes checking means, variances, distributions, and correlations to ensure they match closely.<br><strong>2. Visual Inspection: </strong>Use visualization techniques like histograms, scatter plots, and heatmaps to visually compare synthetic data with real data. This helps in identifying any obvious discrepancies.<br><strong>3. Machine Learning Performance: </strong>Train machine learning models on both synthetic and real data, then compare their performance. If the models perform similarly, it indicates that the synthetic data is of high quality.<br><strong>4. Domain Expert Review: </strong>Have domain experts review the synthetic data to ensure it makes sense within the context of the specific application. Their insights can help identify any unrealistic patterns or anomalies.<br><strong>5. Privacy and Security Checks: </strong>Ensure that synthetic data does not inadvertently reveal any sensitive information. This involves checking for any potential re-identification risks and ensuring compliance with privacy regulations.<br><strong>6. Automated Tools:</strong> Use automated tools and software designed for synthetic data validation. These tools can perform various checks and provide detailed reports on the quality and reliability of the synthetic data.<br><strong>7. Benchmarking: </strong>Compare synthetic data against established benchmarks or datasets to evaluate its accuracy and consistency.</li></ol><p>By employing these methods, businesses can ensure that their synthetic data is accurate, reliable, and suitable for its intended use.</p><h3>Ethical Considerations and Future Outlook</h3><p>While synthetic data offers numerous benefits, it also raises ethical considerations. Ensuring the accuracy and representativeness of synthetic data is crucial to avoid misleading results. Additionally, the potential for misuse, such as generating fake data for malicious purposes, must be addressed. As the technology evolves, establishing guidelines and standards for the ethical use of synthetic data will be essential.<br>Looking ahead, synthetic data is expected to play an increasingly important role in AI and data science. Advances in generative models and deep learning techniques will enhance the quality and realism of synthetic data, making it an indispensable tool for innovation and research. By addressing ethical challenges and leveraging its advantages, synthetic data can drive significant progress in AI development and application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f202ec50eda" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Eliminating AI Bias]]></title>
            <link>https://medium.com/data-science/eliminating-ai-bias-5b8462a84779?source=rss-42bf180d6f14------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b8462a84779</guid>
            <category><![CDATA[editors-pick]]></category>
            <category><![CDATA[ai-bias]]></category>
            <category><![CDATA[algorithmic-bias]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[fairness-and-bias]]></category>
            <dc:creator><![CDATA[Sheenal Srivastava]]></dc:creator>
            <pubDate>Fri, 15 Oct 2021 12:32:48 GMT</pubDate>
            <atom:updated>2021-10-18T20:50:38.742Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsdatascience.com/tagged/fairness-and-bias">Fairness and Bias</a></h4><h4>Identifying AI Bias and knowing how to prevent it from occurring within the AI/ML pipeline</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GA72awdxof6MnhLRoySPug.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@sushilnash?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Sushil Nash</a> on <a href="https://unsplash.com/s/photos/discrimination?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Evidence of AI Bias</h3><p>The primary purpose of Artificial Intelligence (AI) is to reduce manual labour by using a machine’s ability to scan large amounts of data to detect underlying patterns and anomalies in order to save time and raise efficiency. However, AI algorithms are not immune to bias. AI Bias has presented itself in several forms, with some examples highlighted below:</p><ul><li>In 2018, Amazon stopped using its AI Hiring Tool for being biased against women¹.</li><li>In July 2018, AI tools used in the US judicial system (e.g. COMPAS) were reviewed for showing racial bias when used to predict recidivism².</li><li>In November 2019, claims were made against Apple’s credit card for being inherently biased against women over men by providing different credit limits based on gender³.</li><li>In 2020, there was a rise in the number of councils in England using AI algorithms for decision-making about public welfare⁴.</li><li>Most recently, in September 2021, a report by Harvard Business School and Accenture found that approximately 27 million workers in the United States are filtered out of job applications by automated technology. These workers include caregivers and immigrants⁵.</li></ul><p>As AI algorithms can have long-term impacts on an organisation’s reputation and severe consequences for the public, it is important to ensure that they are not biased towards a particular subgroup within a population. In layman’s terms, algorithmic bias within AI algorithms occurs when the outcome is a lack of fairness or a favouritism towards one group due to a specific categorical distinction, where the categories are ethnicity, age, gender, qualifications, disabilities, and geographic location.</p><h3>How does AI Bias occur?</h3><p>AI Bias takes place when assumptions are made incorrectly about the dataset or the model output during the machine learning process, which subsequently leads to unfair results. Bias can occur during the design of the project or in the data collection process that produces output that unfairly represents the population. For example, a survey posted on Facebook asking about people’s perceptions of the COVID-19 lockdown in Victoria finds that 90% of Victorians are afraid of travelling interstate and overseas due to the pandemic. This statement is flawed because it is based upon individuals that access social media (i.e., Facebook) only, could include users that are not located in Victoria, and may overrepresent a particular age group (i.e. aged between 20–30 years old over those aged 50 and above), race, or gender that is dictated by their use of Facebook.</p><p>To effectively identify AI Bias, we need to look for presence of bias across the AI Lifecycle shown in Figure 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ON6R8ndWW_4rS_6f" /><figcaption><em>Figure 1: The Five Stages of the AI/ML Pipeline and associated AI bias (</em>Image by author)</figcaption></figure><h3>Sources of AI Bias in the AI/ML Pipeline</h3><p>A typical AI/ML pipeline starts with a business problem that requires the use of data and analytics to understand the drivers of the issue. This business problem is typically converted into one or many data hypotheses. A study is then designed to determine the data that needs to be collected, the process to carry out its collection, annotation, preparation, and transformation into a format that can then be used for model development.</p><p>Let us have a look at how different types of bias can be introduced at each stage within the pipeline.</p><h4>Study design and hypotheses formulation</h4><p><em>Sampling bias</em> occurs when the study is designed in such a manner that only a subset of the population is sampled, or the sample selected from the population is non-random (see Figure 2). This type of bias is often prevalent in surveys and online polls where only a subset of the population is sampled because they have access to the poll or have willingly completed the survey or poll, resulting in voluntary bias, a type of sampling bias.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vxSRNU4JuK_FRFoP" /><figcaption><em>Figure 2: Evidence of sampling bias where only individuals that have access to paper-based surveys are considered (</em>Image by author)</figcaption></figure><h4>Data collection, pre-processing and exploration</h4><p>Once the study has been designed, data is then collected, pre-processed, and explored in the form of preliminary graphs and tables summarising the dataset.</p><p>Data that is usually collected is a sample that is used to represent a typical target population. However, due to <em>design bias</em>, the sample may be misrepresentative of the population due to an imbalance in the dataset. For instance, machine learning models used in the Google search engine struggled to distinguish between human images and those of gorillas⁶. This is because the dataset did not include a fair representation of gorilla, chimpanzee, and monkey images.</p><p>When there is an imbalance in the dataset due to under-representation of the minority dataset, the algorithm performed well on the overrepresented classes such as pandas and poodles in this case, but performed poorly on the minority class (those belonging to the monkey family). This problem was further heightened by the fact that the labelling technology used in the pre-processing phase was not perfect. As such, this resulted in incorrect annotation of the dataset, which is a form of <em>label bias</em> called <em>recall bias.</em></p><p><em>Measurement bias</em> is a type of label bias that occurs when the training dataset differs from real-world datasets as the data has been distorted due to faulty measurements. An example of this occurred in a project where different brands of spectrometers were used to collect wavelength data for plant samples in the training set and the test set. These spectrometers recorded data on different wavelength ranges. Moreover, the older spectrometers, that were used for the training set, due to low battery power did not use a light source when capturing plant sample wavelength. As such, the test dataset needed to be adjusted to remove a light effect.</p><p><em>Exclusion bias</em> occurs in the data cleaning step where the Data Scientist may remove features considered to be irrelevant. For instance, a dataset for a supermarket consists of sales data in both Australia and New Zealand. During the data exploration phase, it is found that 95% of the customers are from Australia. Thinking that the location field is irrelevant, this field is then deleted from the dataset. This means that the model may not pick up on differences between the Australian and New Zealand customers such as the latter spending more on online shopping.</p><h3>Model development</h3><p>Before developing models, datasets are often split into training, validation and test sets. This can result in <em>time-interval bias</em>, where the Data Scientist intentionally selects a specific timeframe to support hypotheses. An example is forming a conclusion that a particular swimwear line is profitable because only sales during the summer months were considered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/0*5Rx4cFQ5zMnS4e4C" /><figcaption><em>Figure 3: Evidence of time-interval bias where only Australian summer months are considered when evaluating profit for swimwear line (</em>Image by author)</figcaption></figure><p><em>Survivorship bias </em>is another bias that occurs during the model development phase when the Data Scientist only includes data that has ‘survived’ a selection process. A good example is where researchers working for Naval Analyses during World War II were asked to identify the weakest spots within the military’s fighter planes. To answer this problem, the researchers only examined planes returning from a combat mission for points where bullets had penetrated the aircraft (<em>see Figure 4</em>). Using this information, they made recommendations regarding reinforcing these precise spots in the fighter planes. The issue with this analysis is that the sample excluded planes that did not return from a combat mission. These planes would have provided more useful information than planes that returned as they had suffered extensive damage⁷.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*20Svd8gcrUOpTY-O" /><figcaption><em>Figure 4: Evidence of survivorship bias where only returned fighter planes were used to analyse information on weakest spots on planes during World War II (Image by author)</em></figcaption></figure><p><em>Omitted variable bias</em> takes place when Data Scientists exclude one or more features from their model. This typically occurs in predictive machine learning models. An example is where a model was developed to predict how much nitrogen-based fertilizer should be given to wheat, barley, and canola plants. When developing the training set for this model, only features such as the type of plant, the date the plant was planted, the date the plant yield was measured, and UV light wavelengths emitted by the plant were considered for training the machine learning algorithm. The <em>xgboost</em> model (gradient-boosted tree regression model) that is known to perform well on most supervised learning problems produced a negative R-squared (goodness-of-fit statistic) value for model accuracy. The problem here is that the model only considered features that the stakeholders wanted to include. After some brainstorming on which other features could make the model better, additional features such as the amount of rainfall, amount of sunlight, wind speed, air temperature, and soil content were added to the model. This resulted in a remarkable improvement in model accuracy.</p><p><em>Confounding bias</em> occurs because of having confounders in the model, which are variables that are correlated to both the response variable and the predictor variables. Confounders can significantly affect model accuracy. For example, in linear regression models, confounders can change the slope and direction of the regression line.</p><h4>Model interpretation and communication</h4><p><em>Confirmation bias</em> or observer bias occurs during the model interpretation phase, where the Data Scientist interprets or looks for information that is consistent with their beliefs. For instance,<strong> </strong>in<strong> </strong>a model, a Data Scientist may assign higher weightage to features that they believe are better predictors rather than basing the weighting upon model results, or they may even go as far as excluding data that disagrees with their assumptions regarding certain features.</p><p><em>Funding bias</em> occurs when the results of a model are biased in a way to support the financial sponsor of a project. It is a type of <em>observer bias</em>, which is the tendency to see what the observer wants to see.</p><p>This is quite often the case when communicating machine learning models to business stakeholders who are sometimes unwilling to accept the results from the model as it does not meet their expectations. For instance, the results of a customer churn model suggested that the recent marketing campaign had been ineffective at preventing customers from leaving the insurance company as it had targeted the wrong customer demographic group. This analysis was not looked upon favourably by the Head of the Marketing Department. As the results of the customer churn model did not support the funding initiative of the marketing team, the Data Scientist was asked to try different techniques and explore additional features until an “acceptable outcome” was achieved.</p><p><em>Cause-effect bias</em> is the most common type of bias seen in data analytics. This is when correlation is mistaken for causation. A popular example is about an academic in the 1980s that was researching crime rates in New York city and found a strong correlation between the amount of ice-cream sold by street vendors and crime rates. A fallacy would be committed if it was concluded that eating ice-cream leads to an increase in crime rates. Rather, it makes more sense that crime rates are higher in the summer as it is the season when ice-cream sales are the highest. However, ice-cream sales do not cause an increase in crime⁸.</p><h4>Model validation, testing, and monitoring</h4><p>During the model validation and testing steps, the model output is analysed. Model underfitting occurs when there are not enough features in the model and as such performs badly on the training set. These models have less <em>statistical variance</em> (i.e., the model’s sensitivity to specific sets of data) and high <em>statistical bias </em>(i.e., the model has limited flexibility to learn the true underlying pattern of the dataset). Regression, Naive Bayes, linear, and parametric algorithms are prone to underfitting.</p><p>Culprits for overfitting are tree-based models, nearest neighbours’ algorithms, non-linear models, and non-parametric models. Overfitting occurs when the model can accurately predict almost all the values in the training set. However, when it comes to predictions for the test set, the model fails. This indicates that the model is unable to generalise, and as new observations are added to the dataset, it is likely to fail indicating that it has high statistical variance but low statistical bias.</p><p><em>Data leakage </em>occurs when information is shared between the training and test datasets. Typically, when a sample dataset is split into training and testing, no data should be shared between the two. An example is where a predictive model used historical data (from January 2005 to July 2021) to predict product sales from August to October 2021. However, if the training dataset includes observations from the period that it is being used to predict, then temporal data leakage has been committed. This type of bias can easily be identified during the model validation phase as the model is likely to output very high model accuracy scores.</p><h3>How to prevent AI Bias?</h3><p>So, what can be done about AI Bias? The below sections detail how AI bias can be prevented during each of the phases of the AI/ML pipeline. This information has been summarised in Figure 5.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TPUAY73peRhxw-0k" /><figcaption><em>Figure 5: AI bias mitigation strategies in each phase of the AI/ML pipeline (Image by author)</em></figcaption></figure><h4>Study design and hypotheses formulation</h4><p>When deciding on what data and features to include in your research, focus on the design of the study. Aim to make the sample dataset representative of the target population. For instance, when running a survey to measure satisfaction of UberEats in metropolitan Melbourne, ensure accounting for individuals from diverse age groups, both genders, diverse cultural, linguistic, and educational backgrounds, all postcodes of metropolitan Melbourne, and customers that respond to email, postal, and social media surveys. The survey should also be administered online at different times of the day and various days of the week to be inclusive. Additionally, it is a good idea to run the survey multiple times during a year as customer satisfaction may change over a year.</p><p>The next step is to select a random and representative dataset from the sample of respondents to ensure that each respondent has an equal chance of being selected in the study. This type of research design eliminates <em>sampling, voluntary, and time-interval biases</em>.</p><h4>Data collection, pre-processing, and exploration</h4><p>The output from machine learning algorithms can be relied upon if the underlying statistical assumptions are satisfied. For many algorithms, the Central Limit Theorem assumption requires that the sample and population is normally distributed. A large enough sample size or transformation of variables can usually be used to affirm this assumption. So, if after the data collection step, it is found that the sample size is too small, it is recommended that the Data Scientist endeavour to increase the sample size, where possible.</p><p>To determine if a sample size is large enough, <em>power analysis</em> can be conducted that provides the minimum sample size needed to meet a predetermined statistical significance level.</p><p>During the data pre-processing step, it is important to document all data cleansing and transformation steps, this will help identify sources of bias such as exclusion of certain features (<em>exclusion bias</em>) and incorrect labelling of data (<em>label bias</em>).</p><p>Exclusion bias can also be prevented by investigating each feature before discarding them. This can be done through the assistance of Subject Matter Experts (SMEs) that can identify redundant features or by using machine learning methods such as Random Forests that output a variable importance list.</p><p><em>Measurement bias</em> can be reduced by checking for outliers, which are abnormally small or large values and differ widely from the average, and calculating their degree of influence on the outcome variable using methods such as Cook’s Distance or Mahalanobis Distance.</p><p>During the data exploration stage, the Data Scientist may discover that the sample of respondents from a survey for example is imbalanced as there are more female than male respondents, resulting in <em>design bias.</em> The datasets can be balanced by considering down-sampling or over-sampling methods. Examples of <em>python</em> packages that do this automatically are SMOTE for over-sampling or imblearn that does both.</p><p>It is good practice to calculate pairwise correlations between all variables that are included in the model during the data exploration step, which is a statistical technique used to identify multicollinearity. This will assist in identifying confounding variables leading to <em>confounding bias.</em> Correlation thresholds can be set to determine which features to exclude from the model.</p><p>When confounders are found, it is best to engage with SMEs from the business to determine whether the variables should be included in the model. An example where confounders were avoided is during the development of a predictive model that used sensor data in an LNG (Liquefied Natural Gas) plant to predict LNG production. In the first few model runs, a very high model accuracy score was generated by the model. After looking at the top predictor variables during a model presentation, the production engineer identified a confounding variable. This variable in an LNG plant varies after LNG has been produced and as such is a proxy dependent variable. By removing this variable from the model, the model was able to generate more reliable results.</p><p>The removal of <em>label bias</em> may involve some in-depth data exploration. For instance, several university students were used to label plant samples as either wheat, barley, or canola. The predictive model output generated very low model accuracy scores. Unsupervised clustering (k-means clustering) on all features that were entered in the model was used to determine if the algorithm would cluster wheat, barley, and canola samples as separate clusters. The model output accurately classified most of the observations, but a few observations were found in the wrong cluster. This was attributed to one of the features that was entered in the model. The relationship between this feature and the probability of belonging to a specific class was used to re-label the dataset.</p><h3>Model development</h3><p>Feature selection is key when developing good models as it is important to filter out irrelevant or redundant features from the dataset. This can prevent <em>omitted variable bias</em> from occurring. Some supervised algorithms have built-in feature selection such as Regularised Regression and Random Forests.</p><p>Without in-built feature selection (e.g. nearest-neighbours), Data Scientists can employ <em>variance thresholds</em>. Features whose values remain constant should be excluded from a model as they do not have enough variance to explain the outcome variable. For example, a continuous variable with 95% of values as 1 is unlikely to be useful. Likewise, a categorical variable where all observations belong to one category will not provide information for the model.</p><p>When the dataset has a high number of features, <em>Principal Component Analysis (PCA) </em>can be used to reduce the number of features into principal components (linear combinations of features). However, this changes the scale of the output features. Principal components are also difficult to interpret.</p><p>Another option is Genetic Algorithms (GAs) that are a type of search algorithm that use mutation and crossover (biology and natural selection principles) to efficiently traverse large solution spaces; thereby, assisting in the selection of features from very high-dimensional datasets. Unlike PCAs, GAs preserve the output features.</p><h4>Model interpretation and communication</h4><p>When a model is being interpreted, it is important for Data Scientists to look at all of the information resulting from a model and present this information factually, even though it may disagree with the business hypotheses. Likewise, when communicating model output, it is important to have a fact-based conversation with the stakeholders.</p><p>To ensure that the audience can comprehend and trust the model output, rather than seeing it as a black box, Data Scientists should use techniques that can improve transparency and model explainability.</p><p>Models can be explained using <em>global or local explainability⁹.</em> Global explainability displays a high-level view of the model and how the features in the data collectively influence the result. An example is using the coefficients of a multiple linear regression model to explain the magnitude and direction of the features in explaining the variability of the outcome variable. Local explainability is used to explain each observation within the dataset using one feature at a time.</p><p><em>Partial Dependence Plots (PDPs)</em> provide a global visual representation of how one or two features influence the predicted value of the model, whilst holding other features constant. These plots help identify whether the relationship between the outcome variable and selected feature is linear or complex. PDPs are model-agnostic.</p><p><em>Individual Condition Expectations (ICE) Plots</em> provide a local display of the individual effect of a model’s feature with respect to the outcome feature. Unlike PDP, ICE plots are used to show separate predictions of the dependence of the outcome variable’s values on the feature’s value, by providing a visual representation of the individual observations within the sample. Like PDPs, ICE plots are also model-agnostic.</p><p><em>Accumulated Local Effects (ALE)</em> plots are another type of plot used for local explainability. Unlike PDP, the approach focuses on a small range of values for each feature, varying the value of this feature whilst holding all other features constant. The differences in predictions between the start and end of this range are calculated. ALE plots are a faster and less biased alternative to PDPs as they focus on individual predictions rather than averaged predictions used in PDPs.</p><p>Another approach is <em>Leave One Column Out (LOCO)</em> that retrains a model after excluding one column. It then calculates the differences of each LOCO model prediction score to the original model prediction score. If the score changes significantly, it indicates that a feature important to the model was left out.</p><p>Finally, LIME (Local Interpretable Model-Agnostic Explanations) is another local explainability techniques that performs multiple perturbations on a feature’s values and measures the resulting impact on the output prediction.</p><p>There are several other techniques that assist with model explainability such as Shapley Values, Anchors, DeepLift, and ProfWeight. High model explainability can assist with interpretation and communication of model output leading to model transparency and trust.</p><p>When stakeholders are educated in common machine learning techniques and their pitfalls, they are more likely to look at model output in a critical manner. To educate stakeholders, change management within an organisation is required, where all employees within a business, ranging from graduate analysts to CEOs are encouraged to take online learning modules and attend workshops that can assist them with model output assessment.</p><h4>Model validation, testing, and monitoring</h4><p>Whilst validating and testing models, overfitting may be observed. It can be identified by a very high goodness-of-fit statistic on the training set but a low value on the test set. Underfitting can be spotted by a poor goodness-of-fit statistic on the training and test sets.</p><p>One powerful preventative measure against overfitting is <em>cross-validation</em>, where the initial training data is used to generate multiple train-test splits that are then used to tune the model (i.e., <em>k-fold cross-validation</em>). Increasing the size of the sample can also assist in generalising the model’s predictions to the real-world.</p><p>Techniques that are used to simplify models are classed as <em>regularisation</em>. The method used is dependent upon the algorithm used. Pruning a decision tree is one way to make it less complex and prevent overfitting. A <em>penalty parameter</em> can be added to the cost function in regression to shrink the value of coefficients, assisting in the prevention of overfitting. Dilution, which is the process of randomly excluding units (Both hidden and visible) during the training process of a neural network, is also known to prevent overfitting. <em>Early stopping</em> is another way to prevent model overfitting, where the model is stopped after a certain number of runs because additional iterations do not improve the model accuracy. These techniques are often available as parameters in model development that can be hyper-tuned.</p><p><em>Ensemble learning</em> is a technique where predictions from multiple models are combined. Two most common techniques are bagging, which attempts to reduce overfitting by training many “strong” learners (high model accuracy models) in parallel and combining their predictions to provide final predictions of an ensemble model. Boosting aims to improve the predictive flexibility of simple models (i.e. where underfitting is an issue) by training a large number of “weak” learners in sequence, where weak learners are defined as constrained models (i.e. tree depth is limited in tree-based classifiers). Each consecutive model learns from the errors made by the previous one. The final step involves combining all the weak learners into a single strong learner.</p><p>After models are built, they need to be <em>monitored</em> on an ongoing basis to ensure they are still valid for the dataset that is being modelled. For instance, over time, the business may stop capturing some features or include new features within the dataset. Moreover, the distribution of a feature may change which will prevent the model from predicting outcomes that are outside of a pre-determined range of values. All these instances require new models to be built to replace the existing model, which will begin to perform poorly on any new data.</p><h3>What tools are there to prevent AI Bias?</h3><p>There are several existing tools, including Python packages, that can assist with AI Bias prevention¹⁰.</p><p>The What-if Tool (WIT) developed by the TensorFlow team within Google is a visual interactive interface that displays datasets and models. Users can explore model results without having to write code and can view plots such as PDPs¹¹.</p><p>FairML is another useful tool that audits the various types of bias in predictive modelling by quantifying a model’s relative predictive dependence on the input features. The relative importance of the model’s features are then utilised to assess the extent of discrimination or fairness of the model¹².</p><p>IBM’s AI Fairness 360 contains a comprehensive set of metrics, metric explanations, and algorithms to mitigate bias in datasets and models¹³.</p><p>Microsoft’s Fairlearn identifies model biases that impact people in the form of allocation harms and quality-of-service harms. The prior occurs when AI systems extend or withhold information, opportunities, or resources. Some use cases are in hiring, admission to schools or universities, and bank lending. The latter refers to whether a system works equally for all individuals, even if no information, opportunities, or resources are withheld or extended. This tool can be used to alleviate prejudicial and racial biases¹⁴.</p><p>Finally, Aequitas is another well-known open-source bias audit toolkit that can be used to audit machine learning models for discrimination and bias.</p><p>In addition to toolkits, there are various Python libraries for AI bias detection. Python libraries that are algorithm-specific when it comes to detecting AI bias are Fair Classification¹⁵, Fair Regression¹⁶, and Scalable Fair Clustering¹⁷. There are also python packages like Bias Detector¹⁸ and Gender Bias¹⁹ for detecting gender, ethnicity, and racial bias in models that can exist due to sample imbalances and lack of representation of the target population.</p><h3>Conclusion</h3><p>The blog post has identified several types of bias that can occur within the AI/ML pipeline and measures that can be used to reduce or eliminate them. Rather than reinventing the wheel, there are existing toolkits that can assist with AI bias mitigation. However, it is important that individuals throughout a business, from graduate employees to C-level executives, are trained in critically assessing model output to enable their understanding of AI/ML algorithms and question their validity.</p><h4>References</h4><p>[1] Dastin, J. (2018), “Amazon scraps secret AI recruiting tool that showed bias against women”, <a href="https://www.reuters.com/article/us-amazon-com-jobs-automation-insight/amazon-scraps-secret-ai-recruiting-tool-that-showed-bias-against-women-idUSKCN1MK08G">https://www.reuters.com/article/us-amazon-com-jobs-automation-insight/amazon-scraps-secret-ai-recruiting-tool-that-showed-bias-against-women-idUSKCN1MK08G</a></p><p>[2] Thomas (2019),“How can we eliminate bias from AI algorithms? The pen-testing manifesto”, <a href="https://fastdatascience.com/how-can-we-eliminate-bias-from-ai-algorithms-the-pen-testing-manifesto/">https://fastdatascience.com/how-can-we-eliminate-bias-from-ai-algorithms-the-pen-testing-manifesto/</a></p><p>[3] BBC News (2019), “Apple’s ‘sexist’ credit card investigated by US regulator”, <a href="https://www.bbc.com/news/business-50365609">https://www.bbc.com/news/business-50365609</a></p><p>[4]The Guardian (2020), “Nearly half of councils in Great Britain use algorithms to help make claims decisions”, <a href="https://www.theguardian.com/society/2020/oct/28/nearly-half-of-councils-in-great-britain-use-algorithms-to-help-make-claims-decisions">https://www.theguardian.com/society/2020/oct/28/nearly-half-of-councils-in-great-britain-use-algorithms-to-help-make-claims-decisions</a></p><p>[5] Jones, S (2021), “Automated hiring systems are ‘hiding’ candidates from recruiters — how can we stop this?”, <a href="https://www.weforum.org/agenda/2021/09/artificial-intelligence-job-recruitment-process/">https://www.weforum.org/agenda/2021/09/artificial-intelligence-job-recruitment-process/</a></p><p>[6] Simonite, T (2018), “When It Comes to Gorillas, Google Photos Remains Blind”, <a href="https://www.wired.com/story/when-it-comes-to-gorillas-google-photos-remains-blind/">https://www.wired.com/story/when-it-comes-to-gorillas-google-photos-remains-blind/</a></p><p>[7] Agarwal, R (2020), “Five Cognitive Biases In Data Science (And how to avoid them)”, <a href="https://towardsdatascience.com/five-cognitive-biases-in-data-science-and-how-to-avoid-them-2bf17459b041">https://towardsdatascience.com/five-cognitive-biases-in-data-science-and-how-to-avoid-them-2bf17459b041</a></p><p>[8] Agarwal, R (2020), “Five cognitive biases in data science and how to avoid them”, <a href="https://towardsdatascience.com/five-cognitive-biases-in-data-science-and-how-to-avoid-them-2bf17459b041">https://towardsdatascience.com/five-cognitive-biases-in-data-science-and-how-to-avoid-them-2bf17459b041</a></p><p>[9] Onose (2021), “Explainability and Auditability in ML: Definitions, Techniques, and Tools”, <a href="https://neptune.ai/blog/explainability-auditability-ml-definitions-techniques-tools">https://neptune.ai/blog/explainability-auditability-ml-definitions-techniques-tools</a></p><p>[10] “Most Essential Python Fairness Libraries Every Data Scientist Should Know”, <a href="https://techairesearch.com/most-essential-python-fairness-libraries-every-data-scientist-should-know/">https://techairesearch.com/most-essential-python-fairness-libraries-every-data-scientist-should-know/</a></p><p>[11] <a href="https://pair-code.github.io/what-if-tool/">What-If Tool</a>, <a href="https://pair-code.github.io/what-if-tool/">https://pair-code.github.io/what-if-tool/</a></p><p>[12] Adebayo, Julius, “FairML : ToolBox for diagnosing bias in predictive modelling”, <a href="https://dspace.mit.edu/handle/1721.1/108212">https://dspace.mit.edu/handle/1721.1/108212</a></p><p>[13] AI Fairness 360, <a href="https://aif360.mybluemix.net/">https://aif360.mybluemix.net/</a></p><p>[14] Fairlearn, <a href="https://github.com/fairlearn/fairlearn">https://github.com/fairlearn/fairlearn</a></p><p>[15] Fair Classification, <a href="https://github.com/mbilalzafar/fair-classification">https://github.com/mbilalzafar/fair-classification</a></p><p>[16] Fair Regression, <a href="https://github.com/jkomiyama/fairregresion">https://github.com/jkomiyama/fairregresion</a></p><p>[17] Scalable Fair Clustering, <a href="https://github.com/talwagner/fair_clustering">https://github.com/talwagner/fair_clustering</a></p><p>[18] Bias Detector, <a href="https://pypi.org/project/bias-detector/">https://pypi.org/project/bias-detector/</a></p><p>[19] Gender Bias, <a href="https://github.com/gender-bias/gender-bias">https://github.com/gender-bias/gender-bias</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b8462a84779" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/eliminating-ai-bias-5b8462a84779">Eliminating AI Bias</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with R Shiny]]></title>
            <link>https://medium.com/data-science/getting-started-with-r-shiny-821eb0328e73?source=rss-42bf180d6f14------2</link>
            <guid isPermaLink="false">https://medium.com/p/821eb0328e73</guid>
            <category><![CDATA[r]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[r-shiny]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Sheenal Srivastava]]></dc:creator>
            <pubDate>Fri, 15 Oct 2021 03:19:21 GMT</pubDate>
            <atom:updated>2021-10-15T03:19:21.733Z</atom:updated>
            <content:encoded><![CDATA[<h4>Take the first steps towards becoming an R shiny expert</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mpyrgqwMjfclV2oN1U2VIA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@lukechesser?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Luke Chesser</a> on <a href="https://unsplash.com/s/photos/analysis?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Intro to R Shiny</h3><p>Shiny is an R package that allows programmers to build web applications within R. For someone like me, who found building GUI applications in Java really hard, Shiny makes it much easier.</p><p>This blog article will get you building Shiny apps straight away with working examples. First things first, make sure you install the shiny package.</p><pre>install.packages(&quot;shiny&quot;)</pre><h3>Shiny App Structure</h3><p>Like R files, Shiny apps also end with a <em>.R extension.</em> The app structure consists of three components, which are:</p><ol><li>A user interface object <strong>(ui)</strong></li><li>A server function</li><li>A function call to shinyApp</li></ol><p>The user interface (ui) object is used to manage the appearance and layout of the app, such as radio buttons, panels, and selection boxes.</p><pre><em># Define UI for app </em><br>ui &lt;- fluidPage(<br><br>  <em># App title ----</em><br>  titlePanel(&quot;!&quot;),<br><br>  <em># Sidebar layout with input and output definitions ----</em><br>  sidebarLayout(<br><br>    <em># Sidebar panel for inputs </em><br>    sidebarPanel(<br><br>     <br><br>    )</pre><pre><em># Allow user to select input for a y-axis variable from drop-down</em><br>       selectInput(&quot;y_varb&quot;, label=&quot;Y-axis variable&quot;,choices=names(data)[c(-1,-3,-4)]),</pre><pre><em># Output: Plot</em><br>      (&quot;plot&quot;, dblclick = &quot;plot_reset&quot;)</pre><pre>)</pre><p>The server function contains information that is required to build the app. This includes instructions to generate a plot or table and react to user clicks for example.</p><pre><em># Define server logic here ----</em><br>server &lt;- <strong>function</strong>(input, output) {<br><br> <br>  <em># 1. It is &quot;reactive&quot; and therefore updates x-variable based on y-        variable selection</em></pre><pre>  <em># 2. Its output type is a plot</em><br>  output$distPlot &lt;- renderPlot({<br><br>    remaining &lt;- reactive({<br>    names(data)[c(-1,-3,-4,-match(input$y_varb,names(data)))]<br>  })<br>  <br>  observeEvent(remaining(),{<br>    choices &lt;- remaining()<br>    updateSelectInput(session = getDefaultReactiveDomain(),inputId = &quot;x_varb&quot;, choices = choices)<br>  })<br><br>}</pre><pre>output$plot &lt;- renderPlot({<br>    #ADD YOUR GGPLOT CODE HERE<br>    subset_data&lt;-data[1:input$sample_sz,]<br>    ggplot(subset_data, aes_string(input$x_varb, input$y_varb))+<br>      geom_point(aes_string(colour=input$cat_colour))+<br>      geom_smooth(method=&quot;lm&quot;,formula=input$formula)</pre><pre>}, res = 96)<br>}</pre><p>Lastly, the shinyAppfunction builds Shiny app objects based on the UI/server pair.</p><pre>library(shiny)<br><em># Build shiny object<br></em>shinyApp(ui = ui, server = server)<br><em># Call to run the application</em><br>runApp(&quot;my_app&quot;)</pre><h3>What is Reactivity?</h3><p>Reactivity is all about linking user inputs to app outputs; so that the display in the Shiny app is dynamically updated based on user input or selection.</p><h3>The building blocks of reactive programming</h3><h4><strong>Input</strong></h4><p>The input object, which is passed to the shinyServerfunction allows the user to access the app’s input fields. It is a list-like object that contains all the input data sent from the browser, named according to the input ID.</p><p>Unlike a typical list, input objects are read-only. If you attempt to modify an input inside the server function, you’ll get an error. The input can only be set by the user. This is done by creating a reactive expression, where a normal expression is passed into reactive. To read from an input, you must be in a reactive context created by a function like renderText() or reactive().</p><h4>Output</h4><p>To allow reactive values or inputs to be viewed in an app, they need to be assigned to the output object. Like the input object, it is also a list-like object. It typically works with a renderfunction like renderTable.</p><p>The renderfunction performs the following two operations:</p><ol><li>It sets up a reactive context that is used to automatically associate inputs with outputs.</li><li>It converts the R code output into HTML code to allow it to be displayed on an app.</li></ol><h4>Reactive Expressions</h4><p>Reactive expressions are used to split the code within the app into sizeable code chunks that not only reduce code duplication but also avoid re-computation.</p><p>In the below example, the reactive code receives four inputs from the user, which are then used to output results from an independent-samples t-test.</p><pre>server &lt;- function(input, output) {</pre><pre>x1 &lt;- reactive(rnorm(input$n1, input$mean1, input$sd1))</pre><pre>x2 &lt;- reactive(rnorm(input$n2, input$mean2, input$sd2))</pre><pre>output$ttest &lt;- renderPrint({</pre><pre>t.test(x1(), x2())</pre><pre>})</pre><pre>}</pre><h3>Shiny App Examples</h3><p>Now, that we know some basics let’s build some apps.</p><h4>App One</h4><p>The app uses a dummy dataset that includes three continuous variables. The requirements for the app are as follows:</p><ol><li>Produce a scatterplot between two of the three continuous variables in the dataset, where the first variable can’t be graphed against itself.</li><li>User can select the x and y-variables for plotting</li><li>User can select the formula for plotting (“y~x”, “y~poly(x,2)”, “y~log(x)”).</li><li>The categorical variable selected is used to colour the points the scatterplot</li><li>The user can select the number of rows (sample size), ranging from 1 to 1,000 for plotting.</li></ol><pre><em>#Load libraries</em><br>library(shiny)<br>library(ggplot2)</pre><pre><strong><em>#Create dummy dataset</em></strong><br>k&lt;-1000<br>set.seed(999)<br>data&lt;-data.frame(id=1:k)<br>data$gest.age&lt;-round(rnorm(k,34,.5),1)<br>data$gender&lt;-factor(rbinom(k,1,.5),labels=c(&quot;female&quot;,&quot;male&quot;))<br>z =  -1.5+((((data$gest.age-mean(data$gest.age)))/sd(data$gest.age))*-1.5)<br>pr = 1/(1+exp(-z))<br>data$mat.smoke = factor(rbinom(k,1,pr))<br>data$bwt&lt;- round(-3+data$gest.age*0.15+<br>                   ((as.numeric(data$mat.smoke)-1)*-.1)+<br>                   ((as.numeric(data$mat.smoke)-1))*((data$gest.age*-0.12))+<br>                   (((as.numeric(data$mat.smoke)-1))*(4))+<br>                   ((as.numeric(data$gender)-1)*.2)+rnorm(k,0,0.1),3)<br>data$mat.bmi&lt;-round((122+((data$bwt*10)+((data$bwt^8)*2))/200)+<br>                      rnorm(k,0,1.5)+(data$gest.age*-3),1)</pre><pre>rm(z, pr, k)</pre><pre><strong><em>#Define UI</em></strong><br>ui &lt;- fluidPage(<br>  <br>  <br><strong><em>  #1. Select 1 of 3 continuous variables as y-variable and x-variable</em></strong><br>  selectInput(&quot;y_varb&quot;, label=&quot;Y-axis variable&quot;,choices=names(data)[c(-1,-3,-4)]),<br>  selectInput(&quot;x_varb&quot;, label=&quot;X-axis variable&quot;, choices=NULL), </pre><pre>  <strong><em>#2. Colour points using categorical variable (1 of 4 options)</em></strong><br>  selectInput(&quot;cat_colour&quot;, label=&quot;Select Categorical variable&quot;, choices=names(data)[c(-1,-2,-5,-6)]), </pre><pre> <strong><em> #3. Select sample size</em></strong><br>  selectInput(&quot;sample_sz&quot;, label = &quot;Select sample size&quot;, choices = c(1:1000)),<br>  #4. Three different types  of linear regression plots<br>  selectInput(&quot;formula&quot;, label=&quot;Formula&quot;, choices=c(&quot;y~x&quot;, &quot;y~poly(x,2)&quot;, &quot;y~log(x)&quot;)),<br>  #5. Reset plot output after each selection<br>  plotOutput(&quot;plot&quot;, dblclick = &quot;plot_reset&quot;)<br>  <br>)<br>server &lt;- function(input, output) {<br> <br>  <strong><em>#1. Register the y-variable selected, the remaining variables are now options for x-variable</em></strong><br>  remaining &lt;- reactive({<br>    names(data)[c(-1,-3,-4,-match(input$y_varb,names(data)))]<br>  })<br>  <br>  observeEvent(remaining(),{<br>    choices &lt;- remaining()<br>    updateSelectInput(session = getDefaultReactiveDomain(),inputId = &quot;x_varb&quot;, choices = choices)<br>  })<br>  <br>  <br>  output$plot &lt;- renderPlot({<br>    <strong><em>#Produce scatter plot</em></strong><br>    subset_data&lt;-data[1:input$sample_sz,]<br>    ggplot(subset_data, aes_string(input$x_varb, input$y_varb))+<br>      geom_point(aes_string(colour=input$cat_colour))+<br>      geom_smooth(method=&quot;lm&quot;,formula=input$formula)</pre><pre>}, res = 96)<br>}</pre><pre><strong><em># Run the application </em></strong><br>shinyApp(ui = ui, server = server)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*ccpzE1GVG7hgD3hAhTbD2A.png" /><figcaption>Figure 1: User has to select from 5 different inputs</figcaption></figure><p>Once the user has selected the inputs, the scatter plot below is generated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pHRroV_tuB8O3EFui1xTdw.png" /><figcaption>Figure 2: Output graph from App One</figcaption></figure><p>There you go, that’s your first web app built. However, let’s break the code down further.</p><p><strong>App One Explanation</strong></p><p>The function selectInputis utilised to display the drop-down menus for a user to select the variables for plotting, the variable for colouring the points in the scatter plot, and the sample size.</p><p>Within the serverfunction, based on the user’s selection for the y-variable, the user’s choices are updated for the x-variable. The observeEventfunction is used to perform an action in response to an event. In this example, it updates the list of x-variables that can be selected for the x-axis; so that the same variable can not be plotted on both the y-axis and the x-axis.</p><p>The function renderPlotis then used to take all the inputs, x-variable, y-variable, categorical-variable, sample size, and formula to generate or ‘render’ a plot.</p><p>There you have it, your first Shiny App.</p><p>Now, what if we wanted the drop-down to be a slider instead. You can modify the code by adding this code snippet in.</p><pre>ui &lt;- fluidPage(<br>  <br> <br>  #3. Select sample size<br>  # numericInput(&quot;sample_sz&quot;, &quot;Input sample size&quot;, 10000),<br>  sliderInput(inputId = &quot;sample_sz&quot;,<br>              label = &quot;Select sample size:&quot;,<br>              min = 1,<br>              max = 10000,<br>             value = 1)<br>)</pre><p>The output will then look like what’s displayed in</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VE5u4CYah3KlysyQokDZJg.png" /><figcaption>Figure 3: Output from App One showing a slider for sample size</figcaption></figure><p>Now, let’s move onto the next example which is slightly more complicated.</p><h4>App Two</h4><p>In this app, we are looking at a dataset that looks at five life-threatening outcomes as a result of the COVID-19 infection. We want the app to do the following:</p><ol><li>Allow the user to select one of the five outcomes as an input</li><li>Compare the different counties by the selected outcome in a forest plot</li><li>If a user selects a county in the plot, then another forest plot should be generated that shows all five outcomes for the selected country.</li><li>Display an error message for missing values.</li></ol><pre>#Load libraries<br>library(shiny)<br>library(ggplot2)<br>library(exactci)</pre><pre>#import the data and restrict the data to variables and patients of interest<br><br>patient.data&lt;-read.csv(&quot;Synthea_patient_covid.csv&quot;, na.strings = &quot;&quot;)<br>cons.data&lt;-read.csv(&quot;Synthea_conditions_covid.csv&quot;, na.strings = &quot;&quot;)<br>data&lt;-merge(cons.data, patient.data)<br>data&lt;-data[which(data$covid_status==1),] <br>data&lt;-data[,c(12,14,65,96,165,194)]</pre><pre>#Get the state average for each outcome<br>state.average&lt;-apply(data[,-6],MARGIN=2,FUN=mean)</pre><pre>#Make better names for the outcomes<br>names&lt;-c(&quot;pulmonary embolism&quot;, &quot;respiratory failure&quot;, &quot;dyspnea&quot;, &quot;hypoxemia&quot;, &quot;sepsis&quot;)</pre><pre>#Calculate and aggregate the obs and exp by outcome and county<br>data$sample.size&lt;-1<br>list&lt;-list()<br>for (i in 1:5) {<br>  list[[i]]&lt;-cbind(outcome=rep(names[i],length(unique(data$COUNTY))),<br>                   aggregate(data[,i]~COUNTY, sum,data=data),<br>                   exp=round(aggregate(sample.size~COUNTY, sum,data=data)[,2]<br>                             *state.average[i],2))<br>}<br>plot.data&lt;-do.call(rbind,list)<br>names(plot.data)[3]&lt;-&quot;obs&quot;</pre><pre>#Lastly, obtain the smr (called est), lci and uci for each row<br>#Add confidence limits<br>plot.data$est&lt;-NA<br>plot.data$lci&lt;-NA<br>plot.data$uci&lt;-NA<br>#Calculate the confidence intervals for each row with a for loop and add them to the plot.data<br>for (i in 1:nrow(plot.data)){<br>  plot.data[i,5]&lt;-as.numeric(poisson.exact(plot.data[i,3],plot.data[i,4],<br>                                           tsmethod = &quot;central&quot;)$estimate)<br>  plot.data[i,6]&lt;-as.numeric(poisson.exact(plot.data[i,3],plot.data[i,4],<br>                                           tsmethod = &quot;central&quot;)$conf.int[1])<br>  plot.data[i,7]&lt;-as.numeric(poisson.exact(plot.data[i,3],plot.data[i,4],<br>                                           tsmethod = &quot;central&quot;)$conf.int[2])<br>}</pre><pre># Define UI for application <br>ui &lt;- fluidPage(<br>  selectInput(&quot;outcome_var&quot;, label=&quot;Outcome&quot;,unique(plot.data$outcome)),<br>  plotOutput(&quot;plot&quot;, click = &quot;plot_click&quot;),<br>  plotOutput(&quot;plot2&quot;)<br>)<br>server &lt;- function(input, output) {<br>  <br>  output$plot &lt;- renderPlot({</pre><pre>#Output error message for missing values<br>    validate(<br>      need( nrow(plot.data) &gt; 0, &quot;Data insufficient for plot&quot;)<br>    )<br>    ggplot(subset(plot.data,outcome==input$outcome_var), aes(x = COUNTY,y = est, ymin = pmax(0.25,lci), <br>                               ymax = pmin(2.25,uci))) +<br>      geom_pointrange()+<br>      geom_hline(yintercept =1, linetype=2)+<br>      coord_flip() +<br>      xlab(&quot;&quot;)+ ylab(&quot;SMR (95% Confidence Interval)&quot;)+<br>      theme(legend.position=&quot;none&quot;)+ ylim(0.25, 2.25)<br>  }, res = 96)<br>  <br>  #Output error message for missing values<br>  #modify this plot so it&#39;s the same forest plot as above but shows all outcomes for the selected county<br>  <br>  output$plot2 &lt;- renderPlot({</pre><pre>validate(<br>      need( nrow(plot.data) &gt; 0, &quot;Data insufficient for plot as it contains a missing value&quot;)<br>    )<br>    #Output error message for trying to round a value when it doesn&#39;t exist/missing<br>    validate(<br>      need( as.numeric(input$plot_click$y), &quot;Non-numeric y-value selected&quot;)<br>    )<br>    <br>    <br>    forestp_data&lt;-plot.data[which(plot.data$COUNTY==names(table(plot.data$COUNTY))[round(input$plot_click$y,0)]),] <br>    ggplot(forestp_data, aes(x = outcome,y = est, ymin = pmax(0.25,lci), ymax = pmin(2.25,uci))) +<br>      geom_pointrange()+<br>      geom_hline(yintercept =1, linetype=2)+<br>      coord_flip() +<br>      xlab(&quot;&quot;)+ ylab(&quot;SMR (95% Confidence Interval)&quot;)+<br>      theme(legend.position=&quot;none&quot;)+ ylim(0.25, 2.25)<br>  })  <br>  <br>}</pre><pre># Run the application <br>shinyApp(ui = ui, server = server)</pre><p><strong>App Two Explanation</strong></p><p>In this app, like App One, the user makes a selection for an outcome from the drop-down box. This results in a forest plot. The calculations for this forest plot are done outside of the Shiny user interface. The tricky bit in this application is to build a reactive second plot in response to the user clicked county in the first plot.</p><p>This reactivity happens in the server function using this line</p><pre>plot.data[which(plot.data$COUNTY==names(table(plot.data$COUNTY))[round(input$plot_click$y,0)]),]</pre><p>where we checked to see which county had been selected in order to display the second forest plot for all five outcomes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*J11ky4eAr4OPl0xJ7cHJKw.png" /><figcaption>Figure 4: First forest plot in App 2 is generated based on selected outcome</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*88mQET7MP5GiEY2PTC6Jgg.png" /><figcaption>Figure 5: Clicking on the first forest plot for a given county, generates a second plot below showing all five outcomes for the selected county</figcaption></figure><p>In the app, an error message is displayed using the validatefunction where if there is missing data, then there is an error displayed due to this piece of syntax:</p><p>[round(input$plot_click$y,0)],]</p><h4>App Three</h4><p>The final web app’s objective is to allow the user to plot the relationship between the variables in the data set. Some variables are categorical, while others are continuous. When plotting two continuous variables, the user should only be able to plot them on a scatter plot. When one continuous variable and one categorical variable is selected, the user should only be able to make a box plot. The user should not be able to make a plot with two categorical variables. The app should only display one plot at a time, based on the user’s selection.</p><pre>#Load libraries<br>library(shiny)<br>library(ggplot2)</pre><pre>#import data<br>setwd(&quot;C:/Users/User/Desktop/Synthea&quot;)<br>patient.data&lt;-read.csv(&quot;Synthea_patient_covid.csv&quot;, na.strings = &quot;&quot;)<br>obs.data&lt;-read.csv(&quot;Synthea_observations_covid.csv&quot;, na.strings = &quot;&quot;)</pre><pre>patient.data$dob&lt;-as.Date(patient.data$BIRTHDATE, tryFormats = &quot;%d/%m/%Y&quot;)<br>patient.data$enc.date&lt;-as.Date(patient.data$DATE, tryFormats = &quot;%d/%m/%Y&quot;)<br>patient.data$age&lt;-as.numeric((patient.data$enc.date-patient.data$dob)/365.25)<br>data&lt;-merge(obs.data, patient.data)<br>data&lt;-na.omit(data[,c(4,5,10:12,20,24,32,18,15,23,31,33,48:51,60)])<br>names(data)&lt;-substr(names(data),1,10)<br>data$covid_stat&lt;-as.factor(data$covid_stat)<br>data$dead&lt;-as.factor(data$dead)</pre><pre># Define UI for application <br>ui &lt;- fluidPage(<br>  #1. Select 1 of many continuous variables as y-variable <br>  selectInput(&quot;y_varb&quot;, label=&quot;Y-axis variable&quot;,choices=names(data)[c(-1,-2,-14,-15,-16,-17)]),<br>  <br>  #2 Select any variable in dataset as x-variable<br>  selectInput(&quot;x_varb&quot;, label=&quot;X-axis variable&quot;, choices=names(data)),<br>  <br>  <br>  #3. Reset plot1 output after each selection<br>  plotOutput(&quot;plot&quot;, dblclick = &quot;plot_reset&quot;)</pre><pre>)<br>server &lt;- function(input, output) {<br>  <br>  remaining &lt;- reactive({<br>    names(data)[-match(input$y_varb,names(data))]<br>  })<br>  <br>  observeEvent(remaining(),{<br>    choices &lt;- remaining()<br>    updateSelectInput(session = getDefaultReactiveDomain(),inputId = &quot;x_varb&quot;, choices = choices)<br>  })<br>  <br>  output$plot &lt;- renderPlot({</pre><pre>if ( is.numeric(data[[input$x_varb]]) ) {<br>      ggplot(data, aes_string(input$x_varb, input$y_varb)) + geom_point()  <br>    } else {<br>      ggplot(data, aes_string(input$x_varb, input$y_varb)) + stat_boxplot()<br>    }</pre><pre>})<br>    <br>   <br>}</pre><pre># Run the application <br>shinyApp(ui = ui, server = server)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*yd-IWBgj9GHFL2U1Wi8tkQ.png" /><figcaption>Figure 6: Boxplot displayed if a categorical and a continuous variable are selected</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*BQgI1OzBRk4mC4yUiQ0aJg.png" /><figcaption>Figure 7: Scatter plot is displayed if two continuous variables are selected</figcaption></figure><p><strong>App Three Explanation</strong></p><p>The tricky bit in this app is using the if-else condition within renderPlotso that only one of the two types of plots (scatter plot or box plot) can be selected. Furthermore, when you want to check the class of the input$x_varb the use of double square brackets (list) is required, data[[input$x_varb]],otherwise the output will always be character.</p><h3>Conclusion</h3><p>So, there you have it, three simple apps. Let’s recap very quickly on what was covered in this blog article.</p><ul><li>Structure of an R Shiny app</li><li>Linking inputs and outputs</li><li>Creating a dynamic user interface by using reactive() and observeEvent</li><li>Displaying error messages using validate</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=821eb0328e73" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/getting-started-with-r-shiny-821eb0328e73">Getting Started with R Shiny</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Natural Language Processing (NLP) for all Levels in Python]]></title>
            <link>https://medium.com/data-science/natural-language-processing-nlp-for-all-levels-in-python-18b2dc3070c1?source=rss-42bf180d6f14------2</link>
            <guid isPermaLink="false">https://medium.com/p/18b2dc3070c1</guid>
            <category><![CDATA[text-analytics]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Sheenal Srivastava]]></dc:creator>
            <pubDate>Fri, 11 Dec 2020 17:53:45 GMT</pubDate>
            <atom:updated>2020-12-11T17:53:45.182Z</atom:updated>
            <content:encoded><![CDATA[<h4>NLP in Python — in a Nutshell</h4><h3>Background</h3><p>Natural Language Processing or NLP is all the rage currently and it can sound quite confronting to someone who is new to Data Science or new to the Python coding language. Having always written code in R, people often tend to dismiss me for not being a ‘real Data Scientist’ or probably not knowing anything about NLP. However, this is very far from reality.</p><p>NLP is literally the processing of textual data to gain insights from it. The beauty of programming languages like R and Python is that they have a variety of packages that can derive meaning from human languages. This includes, but is not limited to, grammar, translation, and sentiment analysis.</p><p>This article goes through the basics of NLP in Python with code examples to complete common NLP tasks.</p><h3>Packages required</h3><p>The most common packages used for NLP in Python are SPACY and NLTK. To import these packages into your script, refer to the below code block.</p><p>NLTK is a large package and as such you need to download various components of it (such as <em>stopwords</em>) for text processing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SddQhCEuhyOP01pbUq5GJw.png" /><figcaption>Figure 1: Python packages for NLP — Image by Author</figcaption></figure><p>Now, let’s look at common tasks that you may need to carry out when dealing with text.</p><h3>Text Pre-Processing</h3><p>It is always a good idea to <strong>pre-process</strong> text to get rid of special characters, punctuation, replace empty strings, remove numbers, and convert everything to the same case (lowercase for example) so that identical words are not seen as distinct words because of their case. The following code block can be useful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QQBtwtsxjARg27uiMLI87w.png" /><figcaption>Figure 2: Text pre-processing — Image by Author</figcaption></figure><h3>Summarizing text</h3><p>Often, we may want to summarize the text by determining the average number of words and average number of characters for all strings in a given column.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U5aiVe6rem1lCohq61k1bw.png" /><figcaption>Figure 3: Summarizing text — Image by Author</figcaption></figure><h3>Finding particular words or phrases in a string</h3><p>Regular expression matching or looking for words or phrases within a string is a common function that is performed. We can do this by simply checking to see if one string is within another. I have done this within a function below where my score allocation is based on the number of substrings that are found within “my_string”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ldmnn5lNZL3og8H7YPwZfg.png" /><figcaption>Figure 4: Checking for substrings within a string — Image by Author</figcaption></figure><p>We can also look for exact matches of strings using the “<em>findall</em>” function. In the code below, I am looking for bi-grams (phrases consisting of two words) within my column of interest. I use “<em>set</em>” to only retain unique matches. The function “<em>len</em>” is used to count these matches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3UrPOv7a9c8yka6-JxtCIg.png" /><figcaption>Figure 5: Checking for exact matches within a string — Image by Author</figcaption></figure><h3>Measuring the similarity between text fields</h3><p>There are smart ways to check whether two strings are similar and Python has an entire package devoted to it called <em>textdistance. </em>The package contains more than 30 algorithms that allows one to compare strings. In the example below, I have used cosine similarity to measure the similarity between the summary text between two documents. This metric calculates the dot product between the vectors of two strings in order to find the cosine angle between them. It judges similarity based on the orientation between the strings rather than magnitude/length of the strings.</p><p>Cosine similarity requires a string to be split into tokens or words in a sentence for comparison.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gNvIPLvKVY3sJo_zKLXx1A.png" /><figcaption>Figure 6: Calculating cosine similarity between strings — Image by Author</figcaption></figure><h3>Counting word frequencies</h3><p>I often get asked to determine word frequencies. Yes, word clouds are good for visualisation, but what if you wanted to list this information and store it in .csv file.</p><p>In the code below, I take a column called “Description” and join all the text into one long list. I then remove stop words (commonly used words that do not carry meaning such as “a”, “the”, “then” etc). I also perform lemmatization. This is to remove words that are identical in their purest form such as typing and type, organizations and organization.</p><p>I then use the “Collections” package to find the top 200 words and bi-grams by their frequency, which I then output into a csv file. Python is nifty in that it has functions that allow you to measure the frequency of n-grams (unigrams, tri-grams, etc).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rAElR8Q_CdLKCZfBBTNyXA.png" /><figcaption>Figure 7: Counting word and bi-gram frequencies — Image by Author</figcaption></figure><h3>Summary</h3><p>Hopefully, you can now successfully do the following:</p><ol><li>Process text to get a clean version</li><li>Summarize text</li><li>Find substrings within long strings</li><li>Match text strings</li><li>Measure the similarity between text</li><li>Calculate the frequency of words or bi-grams within a string</li></ol><p>Let me know what you think of this blog post and other common NLP functions that you have come across. Please note that I did not cover word clouds and sentiment analysis because I go over that in my article here: <a href="https://towardsdatascience.com/social-listening-via-twitter-feed-analysis-23fb4fbe7531">https://towardsdatascience.com/social-listening-via-twitter-feed-analysis-23fb4fbe7531</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18b2dc3070c1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/natural-language-processing-nlp-for-all-levels-in-python-18b2dc3070c1">Natural Language Processing (NLP) for all Levels in Python</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Social listening via twitter feed analysis]]></title>
            <link>https://medium.com/data-science/social-listening-via-twitter-feed-analysis-23fb4fbe7531?source=rss-42bf180d6f14------2</link>
            <guid isPermaLink="false">https://medium.com/p/23fb4fbe7531</guid>
            <category><![CDATA[twitter-analysis]]></category>
            <category><![CDATA[text-analytics]]></category>
            <category><![CDATA[r-programming]]></category>
            <category><![CDATA[topic-modeling]]></category>
            <category><![CDATA[social-listening]]></category>
            <dc:creator><![CDATA[Sheenal Srivastava]]></dc:creator>
            <pubDate>Tue, 29 Sep 2020 06:04:55 GMT</pubDate>
            <atom:updated>2020-10-05T13:49:05.026Z</atom:updated>
            <content:encoded><![CDATA[<h3>Social listening via Twitter feed analysis</h3><h4>Customer sentiment analysis of twitter feed</h4><h3>What is social listening and why is it important?</h3><p>Social media is now being used extensively for individuals to praise or vent about various topics, individuals and businesses. A good way for a business to determine how its brand is perceived by its customers is via social listening, where businesses consider what their customers are saying about them online and utilise this information to 1) changes to their products and services, 2) create better customer engagement and 3) design its marketing campaigns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*susCa3AmawfvELulnX48wQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@gpthree?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">George Pagan III</a> on <a href="https://unsplash.com/s/photos/social-media?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Using R to programmatically analyse social media data</h3><p>One social media channel that we can scrape quite easily is Twitter as R contains available packages to scrape Twitter data, and the Twitter platform allows users to create a developer account for research purposes.</p><h4>Getting started with a Twitter Developer Account</h4><p>I am not going into detail on how to create a Twitter Developer account as this blog post is more about using R to carry out analysis, but I found the link below quite helpful.</p><p><a href="https://cran.r-project.org/web/packages/rtweet/vignettes/auth.html">Obtaining and using access tokens</a></p><p>Once you have created an account, make sure you save your API keys in a safe place (i.e. some R code) as these will be used for authentication and to allow for tweet scraping.</p><p>As per the below code snippet, I have saved my API keys and then used them to connect to the browser.</p><pre>#### 2. Set parameters for twitter app access ####<br>## store api keys (replace with your own keys)<br>api_key &lt;- &quot;aHGiOIWCubjkMmitanwyIiPaDA&quot;<br>api_secret_key &lt;- &quot;WlbDGVZU8zy6frwvUlxY2j0aBNMTLsutp9VL0z6EsxOzC8SgjXmNTY&quot;<br>access_token &lt;- &quot;1310431451433360898-ry6VoVI6CpzVA5dix7J3gzsvhQLHtw&quot;<br>access_token_secret &lt;- &quot;MZiVtV4dddCGF9LSQ7qvRj35B46BI0RflEKUZYx00AHiuX&quot;</pre><pre>## authenticate via web browser<br>token &lt;- create_token(<br>  app = &quot;rexploretweets&quot;,<br>  consumer_key = api_key,<br>  consumer_secret = api_secret_key,<br>  access_token = access_token,<br>  access_secret = access_token_secret)</pre><pre>setup_twitter_oauth(api_key, api_secret_key, access_token, access_token_secret)</pre><pre>## Check to see if token is loaded</pre><pre>get_token()</pre><h3>Scraping Twitter</h3><p>I am going to pretend that I am a luxury car brand that is thinking of expanding my range to <strong>self-driving cars</strong>. However, I am unsure whether this is a good idea. There are both positive and negative comments in the media, which I find quite confusing. I want to somehow find what people are saying about self-driving cars without reading pages of Twitter feed.</p><p>As I am interested in a particular topic or a # (hashtag), I use the following code to get all tweets related to self-driving cars. Unfortunately, with my Twitter Developer Account, I am restricted to tweets from the past 6–9 days only.</p><p>The <em>include_rts </em>option is to remove <strong>retweets</strong>. I also want to remove <strong>replies </strong>to tweets as I want to include individual or <strong>organic </strong>tweets only in my analysis.</p><pre>sd_cars&lt;- rtweet::search_tweets(<br>                        q = &quot;#selfdrivingcars&quot;,<br>                        n=5000,<br>                        include_rts = FALSE) # exclude retweets</pre><pre>sd_cars_organic &lt;- sd_cars</pre><pre>## Remove replies<br>sd_cars_organic &lt;- subset(sd_cars_organic,is.na(sd_cars_organic$reply_to_status_id))</pre><h3>Exploratory analysis of tweets</h3><p>I then do some preliminary analysis of the tweets to understand some basic information.</p><p>My Twitter feed that I extracted was mainly organic tweets. Retweets as expected are not within the scraped dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/1*bmyWZZDEDwoOZ-Ju7wgeRw.png" /><figcaption>Figure 1: Tweet type pie chart (Image by Author)</figcaption></figure><p>A bar chart of the unique location of Twitter users by usage shows that most people are tweeting from USA, followed by Paris (some cleaning up required to avoid duplication).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4R_k5Hddz6dgMKPqtvWVhA.png" /><figcaption>Figure 2: Twitter users by unique location (Image by Author)</figcaption></figure><p>The frequency of tweets at 3-hour intervals shows when people were most likely to tweet about self-driving cars in the past 9 days. It also shows the most popular days. If I had data for a longer duration, as the business owner of a luxury car brand, I could determine if interest in self-driving cars was increasing or diminishing over time based on the frequency of tweets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z7e8M1QDS8x_6OgfTf97SA.png" /><figcaption>Figure 3: Tweets by time tweeted (Image by Author)</figcaption></figure><p>As I’m a very important and busy person, I can’t be bothered reading individual tweets, so I want to find out what people are talking about, i.e. what are the most frequent words used in the tweets. This requires a bit of data cleaning.</p><h3>Text analytics on Twitter Feed</h3><p>I used the <strong><em>tm </em></strong>package in R to clean the dataset as shown below.</p><pre>## most frequent words ##<br>sd_cars_organic$text &lt;- gsub(&quot;https\\s*&quot;,&quot;&quot;,sd_cars_organic$text)<br>sd_cars_organic$text &lt;- gsub(&quot;@\\s*&quot;,&quot;&quot;,sd_cars_organic$text)<br>sd_cars_organic$text  &lt;-gsub(&quot;amp&quot;,&quot;&quot;,sd_cars_organic$text)<br>sd_cars_organic$text &lt;-gsub(&quot;[[:punct:]]&quot;,&quot;&quot;,sd_cars_organic$text)</pre><pre>#draw out only the text column because we are interested in cleaning it with tm<br>text_corpus&lt;-Corpus(VectorSource(sd_cars_organic$text))</pre><pre>#remove words like car, selfdriving cars, autonomous vehicles as they are synonyms of selfdriving cars<br>#rt = retweet, re = reply<br>text_corpus&lt;-tm_map(text_corpus,removeWords, c(&quot;selfdrivingcars&quot;,&quot;driverlesscars&quot;,&quot;autonomousvehicles&quot;,&quot;cars&quot;,&quot;car&quot;,&quot;rt&quot;,&quot;re&quot;,&quot;vehicle&quot;,&quot;selfdriving&quot;,&quot;driverless&quot;,&quot;autonomous&quot;))</pre><pre>#remove stop words<br>text_corpus&lt;-tm_map(text_corpus,removeWords,stopwords(&quot;english&quot;))</pre><p>I then wanted to visualise the most frequent words, but in order for them to be frequent, they needed to appear at least 10 times. The word cloud that was generated is shown in Figure 4.</p><p>I find word clouds really cool as they always come up with information I would have never thought about, but makes a lot of sense. I had never thought about self-driving trucks or self-driving airplanes (though I believe they already exist). Obviously, I expect IoT to come up as self-driving cars require sensors that are likely to generate lots of data; hence, big data and data analytics. The tweets also show that people associate Uber and Tesla with self-driving cars.</p><p>Additionally, it appears that my stop words removal didn’t work very well, but you get the gist. :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*DyICIFV332Df19tQsGPyPQ.png" /><figcaption>Figure 4: Word cloud #self-drivingcars (Twitter Data) — Image by Author</figcaption></figure><p>Now for understanding Twitter users’ perceptions towards self-driving cars.</p><h3><strong>Sentiment analysis using R</strong></h3><p>I had to do further data transformation in order to plot user sentiments as shown in the code snippet below.</p><p>The results of the sentiment analysis are shown in Figure 5. Again, I like how data analysis confirms my hypothesis. Most people have a positive perception of self-driving cars. They also have trust in it and are waiting in anticipation of self-driving cars. Maybe I should start manufacturing self-driving cars, but before I do that, I want to understand the content of negative tweets.</p><pre>##Converting tweets to ASCII To get rid of strange characters<br>sd_cars_tweets$text_clean&lt;-iconv(sd_cars_tweets$text_clean,from=&quot;UTF-8&quot;,to=&quot;ASCII&quot;,sub=&quot;&quot;)</pre><pre>#removing mentions, in case needed<br>sd_cars_tweets$text_clean&lt;-gsub(&quot;@\\w+&quot;,&quot;&quot;,sd_cars_tweets$text_clean)<br>tweet_sentiment&lt;-get_nrc_sentiment((sd_cars_tweets$text_clean))<br>sentimentscores&lt;-data.frame(colSums(tweet_sentiment[,]))<br>names(sentimentscores)&lt;-&quot;Score&quot;<br>sentimentscores&lt;-cbind(&quot;sentiment&quot;=rownames(sentimentscores),sentimentscores)<br>rownames(sentimentscores)&lt;-NULL</pre><pre>ggplot2::ggplot(data=sentimentscores)+<br>  geom_bar(mapping=aes(x=sentiment,y=Score),stat=&quot;identity&quot;)+<br>  theme(legend.position=&quot;none&quot;)+<br>  xlab(&quot;Sentiments&quot;)+ylab(&quot;Scores&quot;)+<br>  ggtitle(&quot;Total sentiment based on scores&quot;)+<br>  theme_minimal()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*hrLTwKXupCa-fAz9yiJWnw.png" /><figcaption>Figure 5: Twitter users’ sentiment analysis for #selfdrivingcars (Image by Author)</figcaption></figure><h3>Tweets — topic analysis</h3><p>One way to look at tweets associated with negative sentiment is by looking at each individual word; however, as language is complex, sometimes it helps to cluster words into topics. There are various complicated packages to do topic analysis, but I wanted to use a quick and dirty way, which is via exploratory graph analysis.</p><p>Exploratory graph analysis is a technique that groups words into clusters or topics. I used the R package <strong><em>ega </em></strong>for this. My code is shown below.</p><p>First, I used the <em>analyzeSentiment </em>command to compare the tweets with several dictionaries in order to match them with positively or negatively categorized words in order to give each tweet a corresponding sentiment score.</p><p>Second, I only retained a subset of the measures. The command gives 13 sentiment scores.</p><p>Third, I calculated the mean value of each sentiment and removed all positive sentiments (scores &gt; 0). To check that I had retained only negative sentiments, I had a quick look at the resulting data frame (see Figure 6).</p><p>I had to convert my data frame back into a document term matrix in order to carry out further text cleaning steps. As tweets can contain special characters like emojis, I converted the strings into “ASCII”.</p><p>I lowered the <em>sparsity </em>in my document term matrix to speed up the analysis by using a threshold of 0.98.</p><pre>## Only look at negative sentiment ##</pre><pre>sd_cars_sentiments&lt;-analyzeSentiment(sd_cars_tweets$text_clean)</pre><pre>##select subset of measures<br>sd_cars_sentiments_subset&lt;-dplyr::select(sd_cars_sentiments,<br>                                         SentimentGI,SentimentHE,<br>                                         SentimentLM,SentimentQDAP,<br>                                         WordCount)</pre><pre>#create a mean value for each tweet&#39;s sentiment level, leaving us with a single sentiment value for each tweet<br>sd_cars_sentiments_subset &lt;-dplyr::mutate(sd_cars_sentiments_subset,<br>                                          mean_sentiment=rowMeans(sd_cars_sentiments_subset[,-5]))</pre><pre># remove unnecessary sentiment measures<br>sd_cars_sentiments_subset&lt;-dplyr::select(sd_cars_sentiments_subset,<br>                                         WordCount,<br>                                         mean_sentiment)</pre><pre>sd_cars_df&lt;-cbind.data.frame(sd_cars_tweets,sd_cars_sentiments_subset)</pre><pre>#only keep negative sentiments<br>sd_cars_df_negative&lt;-filter(sd_cars_df,mean_sentiment&lt;0)</pre><pre>nrow(sd_cars_df_negative)</pre><pre>#topic analysis of negative sentiments<br>sd_cars_tokenized_list&lt;-tokens(sd_cars_df_negative$text_clean)</pre><pre>sd_cars_dfm&lt;-dfm(sd_cars_tokenized_list)</pre><pre>#turn this list object into a document feature matrix with the dfm command. <br>#use the colsums command to get the count of use for every word, which we assign to the vector &quot;word_sums&quot;<br>word_sums&lt;-colSums(sd_cars_dfm)</pre><pre>length(word_sums)#number of words</pre><pre>#which are the most frequent words<br>freq_negative_words&lt;-data.frame(word=names(word_sums),<br>                                freq=word_sums,<br>                                row.names=NULL,<br>                                stringsAsFactors = FALSE)</pre><pre>sorted_freq_neg&lt;-freq_negative_words[order(freq_negative_words$freq,decreasing=TRUE),]</pre><pre>#remove odd characters<br>sd_cars_df_negative$text_clean&lt;-sapply(sd_cars_df_negative$text_clean,<br>                                       function(row) iconv(row,&quot;latin1&quot;,&quot;ASCII&quot;,sub=&quot;&quot;))</pre><pre>neg_corpus_tm&lt;-Corpus(VectorSource(sd_cars_df_negative$text_clean))</pre><pre>neg_tm&lt;-DocumentTermMatrix(neg_corpus_tm)</pre><pre>neg_tm&lt;-removeSparseTerms(neg_tm,0.98)</pre><pre>neg_df_cluster&lt;-as.data.frame(as.matrix(neg_tm))</pre><pre>#Create clusters using exploratory graph analysis</pre><pre>ega_neg_sd_cars&lt;-EGA(neg_df_cluster)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*bcbpAfdxiRVLmraMM83rYg.png" /><figcaption>Figure 6: Negative sentiments for #selfdrivingcars (Image by Author)</figcaption></figure><p>My resulting exploratory graph is shown in Figure 7 with 15 clusters. The clusters are labelled with abbreviated words which can be quite confusing. Also, 15 clusters is a bit much.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*0BG3nMmZGUXRMhGh_YZdvg.png" /><figcaption>Figure 7: Exploratory graph of #selfdrivingcars negative tweets (Image by Author)</figcaption></figure><p>To better understand which words make up each cluster and to create my own topics or themes, I had a quick look at the words belonging to each cluster. This is shown in Figure 8. Looking at the below table, I can tell that the tweets relating to a crash make up Cluster 3. So, perhaps, the topic for this cluster could be safety.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*CSIg1_VI3IPlp5MH0jZkGg.png" /><figcaption>Figure 8: Words in each cluster (Image by Author)</figcaption></figure><h3>Next steps</h3><p>To further hone this analysis, I could do the following:</p><ul><li>Remove more stop words to get better output</li><li>Re-run my analysis next month and maybe repeat this over several months so that I have many samples to make my decision around self-driving cars</li><li>Play around with parameters of the EGA function to reduce the number of clusters</li><li>Try other related topics (#) or even aim to get data from Twitter accounts related to self-driving cars and combine this with my existing analysis to make an enriched decision about user sentiment towards self-driving cars.</li></ul><h3><strong>Summary</strong></h3><p>In this blog post, I have successfully used R to web scrape Twitter data to better understand how Twitter users feel about self-driving cars. Based on my analysis, it appears that most feel positively towards self-driving cars. There is a concern about driver and passenger safety related to fatal accidents amongst other concerns.</p><p>If you would like to analyse Twitter data, my R code is found below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91e78a95f443869530ab60f07bff744f/href">https://medium.com/media/91e78a95f443869530ab60f07bff744f/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23fb4fbe7531" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/social-listening-via-twitter-feed-analysis-23fb4fbe7531">Social listening via twitter feed analysis</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Supervised learning — the What, When, Why, Good and Bad (Part 1)]]></title>
            <link>https://medium.com/data-science/supervised-learning-the-what-when-why-good-and-bad-part-1-f90e6fe2a606?source=rss-42bf180d6f14------2</link>
            <guid isPermaLink="false">https://medium.com/p/f90e6fe2a606</guid>
            <category><![CDATA[supervised-learning]]></category>
            <category><![CDATA[regression-analysis]]></category>
            <category><![CDATA[r-programming]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[regression]]></category>
            <dc:creator><![CDATA[Sheenal Srivastava]]></dc:creator>
            <pubDate>Mon, 31 Aug 2020 03:17:41 GMT</pubDate>
            <atom:updated>2020-08-31T03:17:41.636Z</atom:updated>
            <content:encoded><![CDATA[<h3>Supervised learning — the What, When, Why, Good and Bad (Part 1)</h3><h4>Deep-dive into regression</h4><h3>Deep learning is not always the answer to a big data problem</h3><p>Often times in the workplace, business stakeholders and managers associate machine learning and big data with deep learning. They will often think that the best solution to all data problems is deep learning, AI or neural networks or some combination of the prior (insert your favourite buzzword). As someone with a statistics background, I find this view quite frustrating as the type of machine learning algorithm chosen should be based upon five key considerations:</p><h4>5 Key Considerations when selecting a machine learning algorithm</h4><ol><li>Type of data problem — i.e. supervised vs unsupervised</li><li>The variable types within the dataset — i.e. categorical or numerical</li><li>The validation of underlying assumptions of the statistical model</li><li>The resulting model accuracy</li><li>The balance between precision vs. recall and sensitivity vs. specificity (<em>for classification</em>)</li></ol><p>In the next few sections and over a couple of blog posts, I am going to go through the different types of models for supervised learning and apply the above considerations to each one.</p><h3>Supervised learning</h3><p>Most of the time, data problems require the application of supervised learning. This is when you know exactly what you want to predict — <em>the target or dependent variable</em>, and have a set of <em>independent </em>or <em>predictor </em>variables that you want to better understand in terms of their influence on the target variable. Then, the selection of a model is based on mapping the underlying pattern in the data to a function which is dependent upon the data’s distribution and variable types.</p><p>The name “<em>supervised learning</em>” is used to describe these types of models because the model learns the underlying pattern on a training set. The number of iterations/rounds determines the number of times the model has a chance to learn from its past. In each subsequent round, the model tries to improve on model accuracy (accuracy metric selected by user) based on what it has learnt in previous runs. The model stops running either after its maximum number of runs has been achieved or when it can no longer improve the model accuracy (specified by <em>early stopping</em> in some models).</p><p>There are two types of supervised learning algorithms as shown in the figure below where the type of outcome variable determines whether you select regression or classification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*16XpXsQFhlLzJl582CPkkg.png" /><figcaption>Figure 1: Types of supervised learning models</figcaption></figure><p>Let’s delve into regression first.</p><h3>Regression</h3><p>It is common for people to think everything is a linear regression problem, but this is not the case. R<em>egression </em>algorithms<em> </em>have a very strict set of assumptions that have to be met in order for the final results to be statistically <em>reliable </em>(<em>*Note: I did not write statistically significant</em>).</p><h4>Why Regression?</h4><p>Regression analysis is a predictive algorithm that is often used in time series analysis and forecasting. This is because it models the underlying relationship between predictor variables and the dependent variable and determines how the variation in the values of the predictor variables explains the variation in the outcome variable.</p><p>There are several types of regression algorithms, but I will focus on the ones below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HS8DxjEKps1brKTGbipTdg.png" /><figcaption>Figure 2: Types of regression</figcaption></figure><p>Before I explore the above regression techniques further. Let’s gain an understanding of the assumptions associated with regression techniques.</p><h4>Regression Assumptions</h4><ol><li><strong>Residuals of the regression line are normally distributed — </strong>To ensure that the result from the regression model are valid, the <em>residuals </em>(difference between observed and predicted values) should follow a normal distribution (with mean zero and constant standard deviation). The residuals are also called error terms and their distribution can be observed on a normal probability plot (Q-Q). If the majority of the residuals are located on the diagonal normality line, then we can assume their normality.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*qKdT4vpwTkj8Ga8pFH81Dw.png" /><figcaption>Figure 3: Density plots used to check for normality</figcaption></figure><p><strong>2. Variables in the dataset come from normally distributed populations </strong>— all variables in the data should also arise from normally distributed populations. Typically, in statistics if the sample size is large enough, then normality can be assumed according to the Central Limit Theorem. In some textbooks it is also low as n = 30.</p><p><strong>3. Residuals are independent — </strong>This assumption is checked to avoid <em>auto-correlation</em> amongst the residuals. When auto-correlation is present within the dataset, it can lead to underestimating the standard error which in turn can make predictors look statistically significant even when they aren’t.</p><ul><li>The <em>Durbin-Watson Test</em> can be utilised to check for auto-correlation. The Null Hypothesis is that the residuals are not linearly auto-correlated. <em>Durbin-Watson’s d</em> can take on any value between 2 and 4, but rule of thumb values of <em>d</em> that are between 1.5 and 2.5 are are used to indicate lack of auto-correlation in the residuals.</li><li><em>Note: The Durbin-Watson test can only vouch for linear auto-correlation between direct neighbors (first-order effects).</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z6YcEixGDel2g2BvC3fRPw.png" /><figcaption>Figure 4: Random distribution of residuals (homoscedastic)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1z1XpmK0ukx4SCfCRzMjSA.png" /><figcaption>Figure 5: Fanning of residuals (heteroscedastic)</figcaption></figure><p><strong>4. Data shows homoscedasticity — </strong>Homoscedasticity in the data occurs when the residuals are equally distributed along the line of best fit rather than show a pattern (residuals have constant variance). When heteroscedasticity is present, the shape of the residuals may show fanning (cone-like shape) or even a linear trend.</p><ul><li>Homoscedasticity can be assessed by plotting the residuals (y-axis) against the predicted values (x-axis) onto a scatterplot and looking for a random scatter of the points rather than any clusters or patterns. A statistical test for heteroscedascticity is the <em>Goldfeld-Quandt Test</em>. It involves dividing the dataset into two groups and checking to see if the variances of the residuals between the two groups are similar.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B5sEMfhT29fwYXPAsZ0bPA.png" /><figcaption>Figure 6: Positive linear relationship shown</figcaption></figure><p><strong>5. Relationship is linear </strong>— When carrying out linear regression (simple or multiple), the relationship between the independent variable(s) and the dependent variable must be linear. Visually, this can be ascertained by creating a scatterplot between each independent variable and dependent variable pair and checking to see if there is a straight line that can be drawn through the points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*s7aBto272dpUjxbTkzvkLw.png" /><figcaption>Figure 7: Outliers are indicated by the solid circles</figcaption></figure><p>5. <strong>There are no significant/influential outliers </strong>— Outliers are typically points within the dataset that are +/- 3 standard deviations from the mean or are beyond the whiskers of a boxplot. As outliers are extreme values they can have a significant effect on the slope of the best-fit line.</p><ul><li>Outliers can be visually identified in boxplots (points that lie outside the whiskers) or from skewness in histograms.</li><li>To determine if the outliers are <em>influential, </em>there are two statistical metrics that can be used: <em>1) Cook’s Distance and 2) Mahanalobis Distance</em></li><li><em>Cook’s Distance </em>checks to see how the regression coefficients vary as each observation in the dataset is removed thereby checking their influence. Each value in the dataset is assigned a Cook’s Distance value. The larger the Cook’s distance, the more influential the observation. A typical heuristic used to determine if a value is an outlier is by checking to see if it’s <em>Cook’s D value</em> is greater than <em>4/n</em> (where <em>n</em> is the size of the dataset).</li><li><em>Mahanalobis Distance </em>measures how far (how many standard deviations) is each observation from the majority of the data points (or mean) and is often used for multivariate datasets. This distance can be approximated using a <em>chi-squared distribution</em> with <em>n </em>degrees of freedom. Compute the <em>p-value </em>for each observation in the dataset. Check to see if the p-value is less than the level of significance (i.e. 0.01) to determine if they are extreme.</li></ul><p>6. <strong>There is no multicollinearity* amongst the independent variables </strong>— <em>Multicollinearity </em>occurs when the independent variables are related to each other. If this is the case, typically you want to include only one of the variables within the pair into the regression model. This assumption can be checked using three methods.</p><p><em>*Does not apply to simple linear regression</em></p><ul><li><strong><em>Variance Inflation Factor (VIF)</em>: </strong>Variables are multicollinear if their VIF value is greater than 10.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*qYWNWoQIGKnOi5TPITcR8A.png" /><figcaption>Figure 7: Correlation plot of the Boston Housing dataset</figcaption></figure><ul><li><strong><em>Correlation Coefficient (r)</em></strong>: Create a correlation matrix between all pairs of variables. If the correlation coefficient is greater than or equal to -/+ 0.7, the the variables are highly correlated.</li><li><strong><em>Tolerance</em></strong><em> — </em>This metric measures the how each independent variable influences all the other independent variables and is defined by the equation <em>T = 1 — R-squared</em>. R-squared (Coefficient of Determination) can be calculated for each independent variable by regressing it against the remaining independent variables. A tolerance factor of 0.1 is commonly used, where when <em>T &lt; 0.1</em>, this indicates the presence of multicollinearity in the dataset.</li></ul><h4>Recap of Regression Assumptions</h4><p>Let’s test some of the concepts we have learnt by running regression diagnostics on the Boston Housing data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mUbgKppBkqNQNCwHz062Xw.png" /><figcaption>Figure 8: Diagnostics plot for residuals</figcaption></figure><ol><li><strong>Residuals vs Fitted — </strong>This plot is used to check for linearity. Given that the line is horizontal without any distinct patterns, we can assume a linear relationship.</li><li><strong>Normal Q-Q</strong>. This plot is used to check for normality of residuals. As most of the residuals are on the diagonal line, this assumption is satisfied.</li><li><strong>Scale-Location</strong> (or Spread-Location) — this plot is used to examine whether the variance of the residuals is homogeneous (homoscedastic). We are looking for a horizontal line with equally distributed residuals below and above this line. In this case, the line has some curvature which means we have some heteroscedascticity.</li><li><strong>Residuals vs Leverage</strong>. This plot is used to determine influential observations or those that have leverage. The points that are labelled in the plot appear to be influential. By removing these, we may also resolve the heteroscedasctic problem as the same observations are labelled in the previous plot.</li></ol><p>Now let’s look at statistics that are commonly used to evaluate model performance.</p><h3>Evaluating model performance</h3><p>There are a couple of metrics that can be used to measure the accuracy of a regression model. I have described the ones I have commonly used when building models.</p><ul><li><strong><em>R-squared</em></strong>: The coefficient of determination measures how much variation in the outcome variable can be explained by the variation in the independent variables. Higher <em>R-squared</em> values are seen as being reflective of higher model accuracy. However, <em>R-squared </em>is not to be trusted when there are multiple predictors in the model. This is because each predictor influences the R-squared value. In these instances, it is more reliable to use the <em>adjusted R-squared</em>. When deciding whether or not to trust the <em>R-squared</em> value, subject matter expertise in the area is required. For instance, <em>R-squared </em>can be quite high (close to 90%) in controlled environments such as chemical plants; however, when modelling human behaviour, a high <em>R-squared</em> value can be representative of <em>overfitting</em>. In these instances, it is better to use any of the below metrics to validate your model.</li><li><strong><em>RMSE (Root-Mean Squared Error):</em></strong> It is calculated as the squared root of the variance between the predicted and observed values (<em>residuals</em>). the lower the value, the better the model fit. <em>RMSE </em>is a better metric in some cases because it penalizes large errors (residuals).</li><li><strong><em>MAE (Mean Absolute Error):</em></strong>This metric is simpler than the <em>RMSE </em>and just sums the absolute value of the residuals. It is less influenced by outliers. Each residual has a proportionate contribution to the total error in the equation. Once again, lower values are better.</li></ul><p>We can finally delve into understanding the various types of regression algorithms.</p><h3>Least-squares regression</h3><p>Linear regression, also called, least-squares regression, uses independent variables to approximate the best fit line for the outcome variable. It is a weighted equation that tries to minimize the sum of squared differences and is denoted by the following equation, where <em>y</em> is the predicted dependent variable, each <em>β </em>is a coefficient corresponding to each independent variable or <em>x, β₀ </em>is the y-intercept, and <em>e </em>is the error term.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*TPOQVnZ1M7RSpvVcK0VLJg.png" /><figcaption>Representation of least-squares regression equation in mathematical form</figcaption></figure><p>In <em>simple linear regression</em>, there is only one coefficient and one independent variable. A coefficient term (<em>β) </em>is added for each independent variable (<em>x) </em>included in multiple linear regression.</p><h4>Interpreting a linear regression equation</h4><p>Let’s start with the y-intercept or constant, <em>β₀. </em>It is the value predicted for <em>y </em>if all the independent variables (<em>X) </em>were zero. It is also typically the average value of the predicted <em>y.</em></p><p>For <em>coefficients </em>of continuous predictor variables, they are interpreted as follows. Keeping all other variables constant, for every 1 unit of increase in <em>X</em>₁, <em>y </em>will increase (if <em>β</em>₁<em> is positive) </em>or decrease (if <em>β</em>₁<em> is negative) </em>by <em>β</em>₁<em> units </em>on average.</p><p>Categorical independent variables are coded as 0 or 1 (dummy variables) for linear regression. So when interpreting their coefficient, which is the difference in the predicted value of <em>y, </em>a one unit difference is a representation of switching from one category to the other while keeping all other variables constant.</p><h3>Polynomial regression</h3><p>When the relationship between the independent variable and dependent variable is non-linear in nature and includes curvature, polynomial regression can be considered an option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4eiuVcZBH9N9aQndosBrKA.png" /><figcaption>Figure 6: Polynomial regression example</figcaption></figure><p>In the graph on the left, we can see that polynomial regression (to the order of 2) fits slightly better than straight line.</p><p>A polynomial regression equation for each independent variable is expressed below. For each order that the variable is raised to, an additional term is added for the variable into the equation.</p><p>It can be tempting to continue to raise the equation to higher degree polynomials to get the best fit; however, this can lead to <strong>over-fitting</strong>. <em>Overfitting </em>occurs when an attempt is made to try and explain as many points as possible, including the random errors, in the dataset (i.e. training set) making it difficult to generalise for other datasets (i.e. test sets).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*r5Fg8O8TwQzRb6T1Ev4JzQ.png" /><figcaption>Representation of polynomial regression equation in mathematical form</figcaption></figure><h3>Stepwise Regression</h3><p>Stepwise regression likes its name involves adding (forward selection starting with no independent variables in the model) or removing (backward selection starting with a full model or all independent variables in the model) independent variables in the linear model to find the best subset of predictors for the dependent variable based on the model evaluation metric.</p><p><em>Forward selection </em>stops when there is no longer an improvement in the model evaluation metric (i.e. R-squared stops increasing), whereas b<em>ackward selection</em> halts after the least influential (i.e. those that contribute to R-squared) independent variables have been removed.</p><h3>Regression in R</h3><h4>Linear regression</h4><p>Sticking to the Boston housing dataset, I have run linear regression (“lm”) of all predictor variables against the median house price. <em>Please note, that I did not “deal” with the multicollinearity, normality, and outlier issues prior to running the model.</em></p><pre>&gt; linearMod &lt;- lm(medv ~ ., data=Boston) <br>&gt; summary(linearMod)</pre><pre>Call:<br>lm(formula = medv ~ ., data = Boston)</pre><pre>Residuals:<br>    Min      1Q  Median      3Q     Max <br>-15.595  -2.730  -0.518   1.777  26.199</pre><pre>Coefficients:<br>              Estimate Std. Error t value Pr(&gt;|t|)    <br>(Intercept)  3.646e+01  5.103e+00   7.144 3.28e-12 ***<br>crim        -1.080e-01  3.286e-02  -3.287 0.001087 ** <br>zn           4.642e-02  1.373e-02   3.382 0.000778 ***<br>indus        2.056e-02  6.150e-02   0.334 0.738288    <br>chas         2.687e+00  8.616e-01   3.118 0.001925 ** <br>nox         -1.777e+01  3.820e+00  -4.651 4.25e-06 ***<br>rm           3.810e+00  4.179e-01   9.116  &lt; 2e-16 ***<br>age          6.922e-04  1.321e-02   0.052 0.958229    <br>dis         -1.476e+00  1.995e-01  -7.398 6.01e-13 ***<br>rad          3.060e-01  6.635e-02   4.613 5.07e-06 ***<br>tax         -1.233e-02  3.760e-03  -3.280 0.001112 ** <br>ptratio     -9.527e-01  1.308e-01  -7.283 1.31e-12 ***<br>black        9.312e-03  2.686e-03   3.467 0.000573 ***<br>lstat       -5.248e-01  5.072e-02 -10.347  &lt; 2e-16 ***<br>---<br>Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1</pre><pre>Residual standard error: 4.745 on 492 degrees of freedom<br>Multiple R-squared:  0.7406, Adjusted R-squared:  0.7338 <br>F-statistic: 108.1 on 13 and 492 DF,  p-value: &lt; 2.2e-16</pre><p>Above, we can see that the <em>adjusted R-squared value is 73.38%</em>, which means that this amount of variation in the median house price can be explained by the predictor variables in the model. This is a pretty good R-squared value and the <em>p-value &lt; 0.05</em> indicating statistical significance.</p><p>Next, I would determine which variables contribute to this R-squared statistic. I can see that all except <em>indus </em>and <em>age </em>are non-significant contributors (p-values &gt; 0.05).</p><p>Let’s see what happens if I run stepwise regression.</p><h4>Stepwise regression</h4><p><strong>Backward</strong></p><p>Let’s try and interpret the call to the the model first.</p><ul><li>My dependent variable (medv) has been regressed against all independent variables (.)</li><li>I have used backward regression</li><li>The model is going to be tuned to try models consisting of 1 to 13 variables.</li></ul><pre># Set seed for reproducibility<br>&gt; set.seed(123)<br>&gt; # Set up repeated k-fold cross-validation (10 fold)<br>&gt; train.control &lt;- trainControl(method = &quot;cv&quot;, number = 10)<br>&gt; # Train the model<br>&gt; step.model &lt;- train(medv ~ ., data=Boston,<br>+                     method = &quot;leapBackward&quot;, <br>+                     tuneGrid = data.frame(nvmax = 1:13),<br>+                     trControl = train.control<br>+ )<br>&gt; step.model$results<br>   nvmax     RMSE  Rsquared      MAE    RMSESD RsquaredSD     MAESD<br>1      1 6.190699 0.5542196 4.512277 0.6480792 0.03585104 0.5143497<br>2      2 5.537331 0.6393649 3.975099 0.6194193 0.08470812 0.4184383<br>3      3 5.216943 0.6757786 3.675974 0.7844579 0.09606216 0.3282287<br>4      4 5.144946 0.6843838 3.621869 0.6838151 0.08435306 0.3033078<br>5      5 4.998163 0.7010740 3.543459 0.7416779 0.08756225 0.2999431<br>6      6 5.048162 0.6953426 3.520865 0.7245789 0.08673190 0.2717374<br>7      7 5.049469 0.6952020 3.500608 0.6987592 0.08276566 0.2597508<br>8      8 5.008368 0.7004709 3.497253 0.6740135 0.08021108 0.2756674<br>9      9 5.012961 0.7018661 3.490065 0.6963818 0.08564270 0.2683468<br>10    10 4.947244 0.7098667 3.447318 0.6896883 0.08705085 0.2222943<br><strong>11    11 4.809318 0.7249622 3.359429 0.6861143 0.08341394 0.2409937</strong><br>12    12 4.825967 0.7231964 3.365846 0.6808653 0.08309689 0.2442360<br>13    13 4.829796 0.7227732 3.368084 0.6796633 0.08336179 0.2455718<br>&gt; step.model$bestTune<br>   nvmax<br>11    11</pre><pre>&gt; summary(step.model$finalModel)<br>Subset selection object<br>13 Variables  (and intercept)<br>        Forced in Forced out<br>crim        FALSE      FALSE<br>zn          FALSE      FALSE<br>indus       FALSE      FALSE<br>chas        FALSE      FALSE<br>nox         FALSE      FALSE<br>rm          FALSE      FALSE<br>age         FALSE      FALSE<br>dis         FALSE      FALSE<br>rad         FALSE      FALSE<br>tax         FALSE      FALSE<br>ptratio     FALSE      FALSE<br>black       FALSE      FALSE<br>lstat       FALSE      FALSE<br>1 subsets of each size up to 11<br>Selection Algorithm: backward<br>          crim zn  indus chas nox rm  age dis rad tax ptratio black lstat<br>1  ( 1 )  &quot; &quot;  &quot; &quot; &quot; &quot;   &quot; &quot;  &quot; &quot; &quot; &quot; &quot; &quot; &quot; &quot; &quot; &quot; &quot; &quot; &quot; &quot;     &quot; &quot;   &quot;*&quot;  <br>2  ( 1 )  &quot; &quot;  &quot; &quot; &quot; &quot;   &quot; &quot;  &quot; &quot; &quot;*&quot; &quot; &quot; &quot; &quot; &quot; &quot; &quot; &quot; &quot; &quot;     &quot; &quot;   &quot;*&quot;  <br>3  ( 1 )  &quot; &quot;  &quot; &quot; &quot; &quot;   &quot; &quot;  &quot; &quot; &quot;*&quot; &quot; &quot; &quot; &quot; &quot; &quot; &quot; &quot; &quot;*&quot;     &quot; &quot;   &quot;*&quot;  <br>4  ( 1 )  &quot; &quot;  &quot; &quot; &quot; &quot;   &quot; &quot;  &quot; &quot; &quot;*&quot; &quot; &quot; &quot;*&quot; &quot; &quot; &quot; &quot; &quot;*&quot;     &quot; &quot;   &quot;*&quot;  <br>5  ( 1 )  &quot; &quot;  &quot; &quot; &quot; &quot;   &quot; &quot;  &quot;*&quot; &quot;*&quot; &quot; &quot; &quot;*&quot; &quot; &quot; &quot; &quot; &quot;*&quot;     &quot; &quot;   &quot;*&quot;  <br>6  ( 1 )  &quot; &quot;  &quot; &quot; &quot; &quot;   &quot; &quot;  &quot;*&quot; &quot;*&quot; &quot; &quot; &quot;*&quot; &quot; &quot; &quot; &quot; &quot;*&quot;     &quot;*&quot;   &quot;*&quot;  <br>7  ( 1 )  &quot; &quot;  &quot; &quot; &quot; &quot;   &quot; &quot;  &quot;*&quot; &quot;*&quot; &quot; &quot; &quot;*&quot; &quot;*&quot; &quot; &quot; &quot;*&quot;     &quot;*&quot;   &quot;*&quot;  <br>8  ( 1 )  &quot;*&quot;  &quot; &quot; &quot; &quot;   &quot; &quot;  &quot;*&quot; &quot;*&quot; &quot; &quot; &quot;*&quot; &quot;*&quot; &quot; &quot; &quot;*&quot;     &quot;*&quot;   &quot;*&quot;  <br>9  ( 1 )  &quot;*&quot;  &quot; &quot; &quot; &quot;   &quot; &quot;  &quot;*&quot; &quot;*&quot; &quot; &quot; &quot;*&quot; &quot;*&quot; &quot;*&quot; &quot;*&quot;     &quot;*&quot;   &quot;*&quot;  <br>10  ( 1 ) &quot;*&quot;  &quot;*&quot; &quot; &quot;   &quot; &quot;  &quot;*&quot; &quot;*&quot; &quot; &quot; &quot;*&quot; &quot;*&quot; &quot;*&quot; &quot;*&quot;     &quot;*&quot;   &quot;*&quot;  <br>11  ( 1 ) &quot;*&quot;  &quot;*&quot; &quot; &quot;   &quot;*&quot;  &quot;*&quot; &quot;*&quot; &quot; &quot; &quot;*&quot; &quot;*&quot; &quot;*&quot; &quot;*&quot;     &quot;*&quot;   &quot;*&quot;</pre><p>In the example above, I have run backwards stepwise regression with 10-fold cross-validation and 13 maximum variables. I didn’t use all of them because we know two were not significant from running a full-linear model previously. We can see that the best model consists of 11 variables (lowest RMSE, lowest MAE, and highest R-squared).</p><p>The asterisk (*) indicates that a variable was included in the corresponding model. The best 11-variables model includes all variables except indus and age, just like the full linear model.</p><p>Forward stepwise regression gives us similar results to the full linear model and backward regression.</p><pre>&gt; set.seed(123)<br>&gt; train.control &lt;- trainControl(method = &quot;cv&quot;, number = 10)<br>&gt; step.model &lt;- train(medv ~ ., data=Boston,<br>+                     method = &quot;leapForward&quot;, <br>+                     tuneGrid = data.frame(nvmax = 1:13),<br>+                     trControl = train.control<br>+ )<br>&gt; step.model$results<br>   nvmax     RMSE  Rsquared      MAE    RMSESD RsquaredSD     MAESD<br>1      1 6.190699 0.5542196 4.512277 0.6480792 0.03585104 0.5143497<br>2      2 5.537331 0.6393649 3.975099 0.6194193 0.08470812 0.4184383<br>3      3 5.216943 0.6757786 3.675974 0.7844579 0.09606216 0.3282287<br>4      4 5.243481 0.6736566 3.658219 0.7510340 0.08224804 0.3304744<br>5      5 5.098698 0.6904107 3.568604 0.7354806 0.08392928 0.2726078<br>6      6 5.045755 0.6953140 3.512300 0.7223225 0.08606320 0.2787373<br>7      7 4.969144 0.7036333 3.448631 0.7542104 0.08842114 0.2944921<br>8      8 4.985899 0.7027153 3.456932 0.7099500 0.08432911 0.2895184<br>9      9 4.985690 0.7030156 3.466382 0.6879376 0.08295944 0.2782166<br>10    10 4.912877 0.7137519 3.421565 0.6865803 0.07813425 0.2716994<br>11    11 4.809318 0.7249622 3.359429 0.6861143 0.08341394 0.2409937<br>12    12 4.825967 0.7231964 3.365846 0.6808653 0.08309689 0.2442360<br>13    13 4.829796 0.7227732 3.368084 0.6796633 0.08336179 0.2455718<br>&gt; step.model$bestTune<br>   nvmax<br>11    11</pre><h3>Regularization</h3><p>Regularization is a technique that is often used to solve the over-fitting and multicollinearity issues that may occur with regression. It does this via the addition of a penalty term to the objective function which aims to reduce standard error.</p><h4>Ridge Regression</h4><p>In ridge regression, a penalty term (shrinkage parameter), λ, is added to reduce the large variation in the <em>β </em>coefficient terms. <em>L2 regularization</em> is used in ride regression, where the objective is to minimize the s<strong>um of squares of coefficients</strong> by trying to bring the coefficients closer to zero.</p><p>Ridge regression is good for small datasets with a large number of variables with small to medium effect.</p><h4>Lasso Regression</h4><p>Lasso (Least Absolute Shrinkage and Selection Operator) regression uses <em>L1 regularization</em> where λ is added to the <strong>sum of absolute squares of the coefficients.</strong></p><p>Lasso regression is good for datasets with fewer variables with medium to large effect on the dependent variable.</p><h4>ElasticNet Regression</h4><p>ElasticNet combines both Lasso and Ridge Regression techniques where both L1 and L2 regularization are applied.</p><h4>Selecting the Regularization Parameter</h4><p>When deciding on which regularization parameter to use, we can base this on two methods — 1) where we choose λ where the information criterion is minimised (such as AIC or BIC) focusing on model fit or 2) where we run the model with cross-validation and select the value of λ that minimize the cross-validated residuals focusing on prediction accuracy.</p><h3>Pros and Cons of Regression</h3><p><strong>Pros</strong></p><ul><li>Easy to understand and present to stakeholders</li><li>Can be used for explainability — i.e relative influence of each predictor on outcome variable</li></ul><p><strong>Cons</strong></p><ul><li>Important to standardize (scale and center) all independent variables to avoid multicollinearity</li><li>Requires checking of strict model assumptions</li></ul><p>That was all I had on regression. My next blog post will be on classification algorithms.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f90e6fe2a606" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/supervised-learning-the-what-when-why-good-and-bad-part-1-f90e6fe2a606">Supervised learning — the What, When, Why, Good and Bad (Part 1)</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Data Science?]]></title>
            <link>https://medium.com/data-science/what-is-data-science-4dfee08b744f?source=rss-42bf180d6f14------2</link>
            <guid isPermaLink="false">https://medium.com/p/4dfee08b744f</guid>
            <category><![CDATA[data-science-job]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-scientist]]></category>
            <category><![CDATA[data-science-interview]]></category>
            <category><![CDATA[data-science-skills]]></category>
            <dc:creator><![CDATA[Sheenal Srivastava]]></dc:creator>
            <pubDate>Sat, 15 Aug 2020 00:55:29 GMT</pubDate>
            <atom:updated>2020-08-15T03:05:21.646Z</atom:updated>
            <content:encoded><![CDATA[<h4>Interviewing for a Data Scientist position</h4><p>A long time ago, I graduated with a degree in Computer Bioinformatics. When people asked me what I had studied, I would provide them with the name of the major, they would try to pronounce it, stumble a couple of times and then give up. I found it tiresome to explain to them that my major allowed me to write software for biologists to analyze biological data and evaluate it using statistics.</p><p>After I graduated, I struggled to find a job that allowed me to combine my research, programming and statistical skills. I looked far and wide and kept falling into roles that did not deliver what they had promised. One role involved a lot of research, but it involved reading government publications. It also involved some statistics that was possible with the minimum sample size of 30 (allowing me to assume that the central limit theorem was satisfied and the distribution was normal — which it never was).</p><p>I moved from job to job looking for the golden egg and despite the increasing demand for analysts, programmers, and now data scientists and engineers, I couldn’t find a role that allowed me to do much. I ended up managing projects, building dashboards, preparing elaborate PowerPoint presentations with a plethora of pie, bar, and scatter plots, and participating in Hackathons. None of these roles satisfied me and I came home feeling dejected and with a lost sense of purpose. Many a days when people marveled at how lucky I was to be a “Data Scientist” I cynically replied that all I did was refresh my inbox during my work day — which some days and even some weeks and months is all I did as I waited to receive data, waited for those above me to make up their mind, and for the tools to be able to do any work.</p><p>Most recently, I worked as a Data Scientist where all I did was query a database and put together tables. These tables were then changed over a number of weeks to make them more optimal to access. All the field names were changed to meet some obscure formatting requirements. These tables were then loaded and reloaded onto different sections of the database. I felt myself drowning in work that was nothingness leading to despair. People kept remarking that I was lucky to have a job where I was not doing anything. It was relaxed and paid well. But, without a family and friends, the 40 hours of emptiness at work only added to my state of loneliness and gloom.</p><p>I do not want anyone else to go through what I have been through after they have achieved the most touted and sexist job of the century — <em>the Data Scientist</em>. Currently, job descriptions ask for every programming language, data visualisation software, and data ETL tool under the hood as required skills. These job ads also ask for presentation and story-telling skills, statistical knowledge, and ability to explain and carry out machine learning. However, despite completing Kaggle-like case studies, going through 7 rounds of interviews, you might end up in a job where for months and even years, all you ever do is “SELECT * from A”.</p><p>A lot of organisations hiring Data Scientists are only hiring them because everyone else is and they don’t want to fall behind in this rat race. They want the brightest, the smartest, and the most talented individuals to work for them. And they want them right now, before they have an analytics platform, before they even have data that is accessible, and even before they figure out why they need Data Scientists. What are they essentially trying to do, well they are trying to put in no-nonsense terms — “Lipstick on a pig”.</p><blockquote><em>Lipstick on a pig</em></blockquote><p>So how do you avoid succumbing to such glamorous job descriptions which within a few days you quickly find out are nothing but grunt data ETL roles. Well, maybe you first need to take a step back and understand “What is data science” for you.</p><p>For me, it is a scientific way of approaching a business problem. This means that you spend some time trying to understand the situation, the current business context and what is the end goal that the business is trying to achieve. If their aim is to predict customer churn, then understand why so and if yes, how quickly do they want this information and will it be feasible to implement the solution.</p><p>The next task is for you as a Data Scientist to attack this problem by coming up with some data hypotheses, similar to the null or alternate hypotheses you developed in STAT101 at university. An example is, there is no relationship between whether or not a customer will churn and their tenure with the company, their age, and &lt;insert all features&gt;.</p><p>Your next step is to create an analytical dataset with existing variables from the data you have and engineered features based on speaking to the business regarding factors that may influence customer churn. Once you have this engineered dataset, the world is your oyster as you run various machine learning models and tune these models to improve model accuracy. It is an iterative approach as you relay these findings to the business, and add and remove variables from your model before you are ready to have it implemented. Ensure that you keep the tech people within the business in your radar as you will need to liaise with them to ensure that the model can be implemented to provide the business with timely results.</p><p>So, this is my version. Now ask yourself and the people hiring you, whether that is what you will do in the role and whether you can really carry out the above, before you apply for that shiny diamond quality Data Scientist position.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4dfee08b744f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/what-is-data-science-4dfee08b744f">What is Data Science?</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decision trees made easy]]></title>
            <link>https://medium.com/@sheenalsrivastava/decision-trees-made-easy-729467dd14a0?source=rss-42bf180d6f14------2</link>
            <guid isPermaLink="false">https://medium.com/p/729467dd14a0</guid>
            <category><![CDATA[decision-tree]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[r-programming]]></category>
            <category><![CDATA[classifier]]></category>
            <category><![CDATA[classification-algorithms]]></category>
            <dc:creator><![CDATA[Sheenal Srivastava]]></dc:creator>
            <pubDate>Sun, 09 Aug 2020 01:45:18 GMT</pubDate>
            <atom:updated>2020-08-09T01:45:18.501Z</atom:updated>
            <content:encoded><![CDATA[<p>When people hear the words randomForest, xgboost and GBM, it is subsequently followed by the word “blackbox” — a term that is frequently used when people fail to understand the machine learning algorithm.</p><p>However, gone are those days when people did not want to understand randomForest models and blindly trusted the output and this is because ensemble/aggregated decision tree methods (i.e. randomForest) and algorithms that involve series of trees (i.e. xgboost) are prone to overfitting; thus leading to lack of generalisation that then leads to failure in prediction of unseen data.</p><p>Now, everyone (see how I generalised there :) ) wants to understand what’s going on inside the “blackbox”, but articulating the algorithm to “non-data” people can be difficult.</p><p>So, to assist you, I’ve written a blog post that explains decision trees.</p><h3>Decision Making Process by a Child, Adult and Machine</h3><p>Let’s go back in time to when you were a child and may have been faced with the following dilemma.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/0*UFohZ6GEykaNrSAH" /><figcaption>Decision making as a three-year old (Source: <a href="https://www.mommyish.com/terrifying-child-decision-tree/">https://www.mommyish.com/terrifying-child-decision-tree/</a></figcaption></figure><p>To solve the above problem, i.e. make a decision, the following factors need to be considered:</p><ul><li>What is the problem?</li><li>What information or data do I need to make my decision?</li><li>What options do I have?</li><li>Factors influencing me or constraints?</li><li>What is the optimal decision or my choice?</li></ul><p>Now, decision making may have changed as an adult but the basics are still the same as shown in the example below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tY3Y7SH5SGr0pr4V" /><figcaption>Decision making by an adult (Source: <a href="https://www.classtools.net/blog/using-decision-trees-to-categorise-compare-and-contrast-key-factors/">https://www.classtools.net/blog/using-decision-trees-to-categorise-compare-and-contrast-key-factors/</a> )</figcaption></figure><p>So, what’s changed? Well, there are</p><ul><li>More key decision making points which translates to more Nodes</li><li>More levels which translates to the depth of the tree or an increase in complexity</li><li>More final decisions which translates to more leaves or an increase in options</li></ul><p>Now, what would the problem look like if it was solved by a machine or the “blackbox”?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/0*COLhot_Z4SlGcpH3" /></figure><p>Well, unlike a human, the machine has access to multiple cores (processors) that run all at once (in parallel) allowing for speed to explore all possible options, which means there will be more levels (greater depth) and more leaves (more options).</p><p>So, what have we learnt so far:</p><ol><li>Decision trees have nodes (decision points)</li><li>Decision trees have levels (indicates depth of tree)</li><li>Decision trees have leaves (choices / options at the end)</li></ol><p>Now, what else do you know. Well, since it’s a tree, it has branches that splits up each node into two branches each.</p><p>The splitting of each node is based upon a conditional rule or an if-else statement such as</p><ul><li>“If I were to punch her lights out”, “I would be happy”</li><li>else if “I could tell on her”, “She would get into trouble” or</li><li>else “If I lock her in the closet”, “I will never ever see her again”.</li></ul><p>The decision-making process made by the three-year old is slightly more complex than that made by most machine learning algorithms, where the splits are “yes” or “no” based and recursive, which means that at each level of the tree, there is only one of two options or one node. This approach in data science terms is called the <em>greedy approach for binary recursive splitting</em>.</p><p>In application, the above series of statements would be converted into the following if-else statements:</p><ul><li>Level 1: If I punched her “yes” -&gt; Happiness [leaf]</li><li>Level 1: If I did not punch her and Level 2: Told on her -&gt; She would get into trouble [leaf]</li><li>Level 1: If I did not punch her and Level 2: Did not tell on her -&gt; Level 3: Locked her in the closet → I will never see her again [leaf]</li><li>Level 1: If I did not punch her and Level 2: Did not tell on her -&gt; Level 3: Did not lock her in the closet -&gt; Outcome unknown [leaf]</li></ul><h3>Decision Tree — Example</h3><p>Let’s look an example that one might encounter in the retail industry. It is a classification problem to predict whether someone is likely to be a purchaser or non-purchaser. Dataset with the following information has been provided (only 7 rows shown).</p><p><a href="https://gist.github.com/shedoesdatascience/77273e350320c8be8193fc2f2033a3a9">https://gist.github.com/shedoesdatascience/77273e350320c8be8193fc2f2033a3a9</a></p><p>Taking the above information into account we can come up with the following information:</p><ul><li>Problem: How likely is the potential prospect a purchaser or non-purchaser?</li><li>Data collected: 100k customers (unique) over two years</li><li>Features:</li><li>Income level: {&lt;= $75,000, &gt; $75,000}</li><li>Education level: { &lt;= 12 years, &gt; 12 years }</li><li>Number of family members: { &lt;= 4, &gt; 4}</li></ul><p>Let’s use the above information to make our decision tree, noting that we have three possible nodes (equal to three features) and for each node we have two options.</p><p>When a decision tree decides on which node to make its root node, its aim is to choose one that is most effective at minimizing the depth (complexity) of the tree, thus reducing <em>entropy</em> and increasing <em>information gain</em>.</p><p>For a regression tree, the aim is to choose a split that minimizes the<em> mean squared error (MSE)</em>.</p><p>For a classification tree, the <em>Gini purity</em> metric is used which measures the purity of each node (i.e. well can it accurately split the dataset into two unique subsets of data).</p><p>Now back to our decision tree problem. As income has the highest information gain, it is selected as the root node. Number of family members has the second highest information gain and as such it is used to make the next splitting decision.</p><p>The below tree can be translated into the following “human” rules.</p><ul><li>IF income &lt;= $ 75,000 AND individual has &lt;= 4 family members AND individual has &lt;=12 years of education, individual is likely to be a purchaser</li><li>IF income &gt; $75,000 AND individual has &gt; 4 family members AND has &gt; 12 years of education, likely to be a non-purchaser</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Txh5d1oKN1uX367x" /></figure><p>To come up with each “human rule”, all I did was traverse down the right side of the tree and then the left side of the tree until I got to the bottom of the tree. Simple — isn’t it!</p><h3>Let’s Recap</h3><p>Decision tree is a type <strong>of supervised learning algorithm </strong>(having a pre-defined target variable) that is mostly used in classification problems.</p><p>It works for both <strong>categorical</strong> and <strong>continuous</strong> input and output variables.</p><p>In this technique, we split the population or sample into two or more homogeneous sets (or sub-populations) based on the most significant splitter / differentiator in input variables (highest information gain).</p><p>What do we need to build a tree:</p><ul><li>Dataset</li><li>Labelled data</li><li>Method to determine the accuracy of the model (RMSE / R-squared for regression and AUC/ROC curve or F1-score for classification)</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1afa77efd25fa38fe875dc4510abda49/href">https://medium.com/media/1afa77efd25fa38fe875dc4510abda49/href</a></iframe><h3>Applications of Decision Trees</h3><ul><li>Finance — customer churn models, credit risk scoring models</li><li>Industrial — predicting equipment failure</li><li>Healthcare — emergency room prioritization</li><li>Retail — demand forecasting</li></ul><p>Hopefully, this blog post has removed the shroud around decision-tree based methods. Do let me know! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=729467dd14a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using gradient boosting machines for classification in R]]></title>
            <link>https://medium.com/data-science/using-gradient-boosting-machines-for-classification-in-r-b22b2f8ec1f1?source=rss-42bf180d6f14------2</link>
            <guid isPermaLink="false">https://medium.com/p/b22b2f8ec1f1</guid>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[gradient-boosting]]></category>
            <category><![CDATA[r-programming]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[gbms]]></category>
            <dc:creator><![CDATA[Sheenal Srivastava]]></dc:creator>
            <pubDate>Sun, 09 Aug 2020 01:30:04 GMT</pubDate>
            <atom:updated>2020-08-15T21:46:44.520Z</atom:updated>
            <content:encoded><![CDATA[<h4>Classification methods in machine learning</h4><h3>Background</h3><p><strong>Purpose of analysis:</strong></p><p>Understand the factors driving student success so that Open University can allocate resources to improve student success</p><p><strong>Description of dataset:</strong></p><p>The Open University Learning Analytics Dataset is a publicly available dataset containing data about courses, students and their interactions with VLE for seven selected courses (modules).</p><p>As the unique identifiers across all the data tables were student ID, module and course description, data was aggregated at this level. The following variables were used in the analysis:</p><p><strong>Variable NameVariable TypeVariable NameVariable Type</strong>id_student unique identifier/primary keyimd band categorical code_modulecategoricalage band categorical code_presentation categorical num of previous attemptsnumericalgender categorical studied credits categorical region categorical disability categorical highest education categorical final result numerical sum weighted score numerical average module length numerical average submission duration numerical average proportion content accessed numerical average date registration numerical trimmed assessment type categorical</p><h3>Methodology</h3><h3>Data transformation</h3><ul><li>Combine datasets based on unique identifier (student ID, course and code_description)</li><li>Aggregate variables at unique identifier level</li><li>Update nominal variable types from character to factor</li></ul><p><strong>Predictors:</strong></p><ul><li>code module</li><li>code presentation (changed to 1 = B and 2 = J),</li><li>gender, region, highest education, IMD band, Age band, number of previous attempts, studied credits,</li><li>average submission duration (averaged as a single code presentation can have multiple assessments with varying submission durations),</li><li>average module length,</li><li>average proportion content accessed (based on sum of clicks on “ou” content and resources/quiz/glossary divided by total sum of clicks per code description),</li><li>average date registration and</li><li>trimmed assessment type (as a single code description can have multiple assessments and multiple of the same type of assessment. It is important to determine whether the types of assessments per course and description drive student success)</li></ul><p><em>Excluded variables: Student ID and sum weighted score</em></p><p><em>Reason for exclusion: Student ID– identifying information, sum weighted score — correlated to final result</em></p><p><strong>Define “success” target variable</strong></p><ul><li>Response variable: Success (“Pass” or “Distinction” = “Yes”, “Fail” or “Withdrawn” = “No”</li></ul><p><em>Reason for not using “final result” as success factor: There is a disproportionate of “Pass” records within the dataset thus reducing the model accuracy at predicting “Fail”, “Withdrawn” and “Distinction”. As such, the response variable was binarised.</em></p><ul><li><em>Check for nulls, missing values, and outliers for each variable that will be input into the model</em></li></ul><blockquote>Why do we check for missing data? — If a large proportion of data is missing/null, sample is not representative enough to provide accurate results. This is not the case when the missing/null data is missing for a valid reason.</blockquote><h3>Data set-up</h3><p>• Split data into training &amp; test sets for nominal and binary predictors to test for model accuracy</p><blockquote>Why do we split the data into training and test sets — The model is trained on the training set. Model accuracy is tested on the test set to determine how well the model is good at prediction success against non-success on data it has not “seen”.</blockquote><h3>Data modelling</h3><ul><li><strong>Analytical method:</strong> Gradient boosting machine (GBM)</li><li>Alternate methods could have been used but model accuracy was good enough — Distributed Random Forest (DRF) and Generalized Linear Model (GLMNET)</li><li>Check for <strong>model accuracy </strong>using confusion matrix (i.e. proportion that were predicted correctly) and area under curve (how well did we do compared to random chance).</li></ul><h3>Output</h3><ul><li>Top predictors (by variable importance score)</li></ul><h3>Data ETL</h3><p>All data exploration, transformation, and loading of final dataset was done in Alteryx to avoid writing code and test its functionality for basic data transformation steps that would typically be carried out in R such as joins, mutate and group by.</p><p>First, I joined three datasets — assessments.csv, studentAssessments.csv and courses.csv by ID assessments (primary key).</p><p>Next, I engineered two features: weighted_score and submission_duration. Dates are usually meaningless unless they are transformed into useful features. Course description only had two categories, which I converted to 1 and 2 for ease of reference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/0*fZGM4xDxrtAUWLl1" /></figure><p>The next step was to add in data on student interactions with the virtual learning platform (VLE). Some feature engineering was done for ease of analysis such as creating a new variable called activity_type_sum that reduces the number of categories in activity type into two broad categories — content access and browsing. The reason for doing this is that granular categories only result in more features and reduce the number of observations per category. The number of clicks were summed by the activity type feature. Proportion of activity out of total activity that is browsing related and content access related was also calculated. This is a good way to create a feature that is relative to another feature and scaled by total activity thus ensuring that all students are represented on a similar scale by their activity type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CjPu_Vv6vtb9eFsF" /></figure><p>Block 1 was joined to Block 2 using student_id, code_module and code_presentation as the primary key. The resulting output is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cynWyXN75PpVZ25r" /></figure><p>The above output — Block 3 — was joined with student registration data using student_id, code_module, and code_presentation to bring across the data_registered field.</p><p>The <em>date_unregistered </em>field was ignored as it had a lot of missing values. Moreover, students with empty unregistered field cells have <em>withdrawal </em>as the value for their <em>final_result</em>. This variable is our <em>target/response</em> variable. So, the <em>date_unregistered </em>field appears to be a proxy measure for final_result and as such it makes sense to exclude this variable from our analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wR3ox5nkmLLv7EMj" /></figure><p>As shown above, for a given id_student, code_module, and code_presentation, the module_presentation length, proportion_content and date_registration is repeated. As we want to have unique records, we can aggregate the data as follows:</p><ul><li>Summarise weighted score using total sum</li><li>Average submission duration</li><li>Average module presentation (you can also use other aggregates such as minimum, maximum, and median)</li><li>Average of proportion_content_access</li><li>Average of date_registration</li></ul><p>Data is now at student_id, code_module, code_presentation and assessment_type level; however, the target variable — final_result — is at student_id, code_module and code_presentation level. Hence, this data will need to be further aggregated.</p><p>Let’s look at student info first. A unique record here is id_student, code_module, code_presentation. <br> So, we will need to go back a step and summarise a student_id, code_module and code_presentation to represent all assessments taken by an individual. We will still use the previous summary formulas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Me-mHIjbtuVBLb99" /></figure><p>By doing this we have 8 unique assessment types that a student can take for a given code module and code presentation. Assessment types are not repeated (trimmed only) so if at student took 3 TMAs this is not reflected as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/0*oH5pII9f7fF3nofn" /></figure><p>A variable could be created to count the number of assessments per assessment type but it would contain lots of missing values as not all assessments have all three types of assessments.<br> Now, we are ready to join to the student info data with output shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*psNSUkIv9VhlI0yE" /></figure><p>Now, we have 18 columns.<br> We have been told that a presentation may differ if presented in February vs. October. We will assume that it does not differ year on year (i.e. 2013B is same as 2014B). As such, we will recode code_presentation into 1 for B and 2 for J as a binary variable.</p><p>The final output is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KuO-45U0ochaADYT" /></figure><p>It is finally time for some data exploration.</p><h3>Exploratory Data Analysis</h3><p>Categorical variables can be represented with bar charts where the y-axis is the frequency of the occurence of a given category. For example, in the chart below we can see that the most frequently taken code module is <em>FFF </em>followed by <em>BBB. </em>There are seven unique code modules with no missing values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/0*U54G7yjDBMBgsRKE" /></figure><p>Data can also be summarised numerically using a five-point summary for continuous variables and using mode for categorical variables as shown below.</p><p>Insights we can make from the summary below is that the more common student is a Scottish male student presenting without a disability with an Imd_band between 20 to 40% with a typical Pass as their final result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/0*jOZJExj2bewbRgyd" /></figure><p>Now we can move towards modelling the dataset.</p><h3>Machine Learning Model</h3><p>We have been asked to assist Open University in better understanding student success.<br> • We will assume that student success is measured via the final result where pass and distinction are indicators of “success” and withdrawn and fail are indicators of “non-success”.<br> • For the independent variables, we will use all variables from the previoustable except for weighted_score. The reason for this is because weighted score determines the final result for a given student. As such, it is highly correlated (multicollinear) to final result and as such will be excluded.<br> • Student ID is identifying information and as such will not be used as a predictor.</p><p><em>GBM (Gradient Boosted Model) </em>was used as a model of choice. This type of model creates a series of weak learners (shallow trees) where each new tree tries to improve on the error rate of the previous tree. The final tree is one with the lowest error rate. It is an ensemble machine learning method as several trees are created to provide the final results. However, unlike in <em>randomForest</em>, these trees are created in a series rather than in parallel. Furthermore, these trees are not independent and are depenent on the previous tree’s error rate where the following three will try harder to improve prediction for the more difficult cases. This is controlled by a parameter called hte learning rate.</p><p>The model was run with 500 rounds (500 trees) with minimum and maximum depths of 4 for the tree. Typically, it is not good to have very deep trees as this can lead to overfitting where the algorithm tries to explain every observation in the dataset as it increases the depth of the tree leading to leaves containing a very small number of observations that fit the given rule.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/0*eBXRW3Z0fwbxQIKu" /></figure><p>We can see from the above output that the model has a RMSE (root-mean-squared error) value of 0.55 which is quite high. It is particularly bad at predicting <em>Distinction </em>and <em>Fail</em>, which may be due to the imbalance in the dataset where we know from our exploratory data analysis that <em>Pass </em>is the most common final result.</p><p>To counteract this imbalance issue, the target variable was redefined as “success” (distinction and pass) and “failure” (fail and withdrawn). It is common to combine categories to deal with imbalanced datasets. Other ways are to undersample (i.e. reduce the number of instances for the most frequent class) or oversample (i.e. create artificial observations for the non-frequent classes).</p><p>The model was re-run with the following output. Here we can see that the mean per-class error has dropped significantly. The Area Under the Curve (AUC) is another accuracy metric that tells you how well the model is at classifying cases correctly (i.e. maximising the true positive rate (TPR)). The higher the AUC, the more accurate the model. As the AUC is measured between 0 and 1, an AUC of 0.87 is pretty good.</p><p>Another metric that is commonly used in classification problems is the F1 score which is the harmonic mean of precision and recall. Both metrics aim to maximise the TPR while minimising either the false negative rate (recall) or false positive rate (precision). A <em>true positive </em>is when a success or failure is classified correctly. A <em>false negative</em> is when a success is labelled as a failure. A <em>false positive </em>is when a failure is labelled as a success. For the F1 score to be high, both precision and recall need to be high.</p><p>Confusion matrix indicates an overall error rate of 17.11% which is mainly driven by how good the model is at classifying successes. The model is not so good at classifying failures with an error rate of 39.07%. Again this may be due to the data being overrepresented by “Passes”. Thus, the results should be treated with caution and model re-run with a more balanced dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/0*zjn4N3tWsMsPEVeo.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/0*5_7YGRmsrAEULfDx.png" /></figure><p>Now, let’s look at the top predictors of success or failure by looking at the <em>variable importance list.</em></p><ul><li>The top 3 variables are code module, trimmed_assessment_type and average submission duration.</li><li>The bottom 3 variables at predicting whether or not a successful outcome will be reached for a given student are disability status, average date for registration and gender.</li><li><em>Note: As code module and code presentation are part of the unique identifier they should have been excluded from analysis. However, as presentations in February and October may be different for some courses, both variables were kept in the model. It is possible that excluding these variables may increase accuracy or make other variables more “important”.</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/0*DwkizWK_EkiRlcAe" /></figure><p>Now, let’s visualise information on the top predictors to better understand the model. The stacked bar plot below shows the proportion of records by course module and final_result. We can deduce that students are more likely to be successful in completing AAA, EEE and GGG courses over other courses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/0*rcZV6fxVOKxGPDBq" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/0*mxQmpTLbafOBBN1M" /></figure><ul><li>From the above table, we can see that there is a 100% success rate if an exam is the only assessment for a given course and presentation.</li><li>If only computer marked assessments make up the course component, there is a very high failure/withdrawn rate. It would be interesting to investigate why having CMA as part of a presentation assessment leads to a decrease in success rate.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/0*OGeH2vMBBIO6BpZ_" /></figure><p>The histograms above show the average submission duration by success and failure.</p><p>It appears that when students are successful, they are more likely to submit their assignment within 10 days (+/-) of the assessment submission date.</p><h3>Wrapping up</h3><p>Machine learning was used to quickly identify top contributors to student success.</p><p>Recommendations for model improvement include:</p><ul><li>Working with a balanced dataset</li><li>Including proxy measures for resource allocation within the dataset</li><li>Count of the number of assessments by type per course and presentation as a<br> feature</li><li>Remove categorical variables that are associated with each other (i.e. use of chi-squared test of independence)</li></ul><p>Hopefully, you now have a better understanding of utilising GBM for a classification problem, the pitfalls of a classification problem (i.e. imbalanced dataset) and the use of various accuracy metrics.</p><p>The reference to all R code is provided in my git repository: <a href="https://github.com/shedoesdatascience/openlearning">https://github.com/shedoesdatascience/openlearning</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b22b2f8ec1f1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/using-gradient-boosting-machines-for-classification-in-r-b22b2f8ec1f1">Using gradient boosting machines for classification in R</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>