<?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 Javier Lopez Castillo on Medium]]></title>
        <description><![CDATA[Stories by Javier Lopez Castillo on Medium]]></description>
        <link>https://medium.com/@javilopezcastillo?source=rss-221ab9e23bea------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xf33jelbSnyJakobnl2S3A.jpeg</url>
            <title>Stories by Javier Lopez Castillo on Medium</title>
            <link>https://medium.com/@javilopezcastillo?source=rss-221ab9e23bea------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 04:32:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@javilopezcastillo/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[Multiple Linear Regression Analysis of Citi Bike Ridership Data]]></title>
            <link>https://javilopezcastillo.medium.com/multiple-linear-regression-analysis-of-citi-bike-ridership-data-c49fd3f211f7?source=rss-221ab9e23bea------2</link>
            <guid isPermaLink="false">https://medium.com/p/c49fd3f211f7</guid>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[predictive-modeling]]></category>
            <dc:creator><![CDATA[Javier Lopez Castillo]]></dc:creator>
            <pubDate>Thu, 21 Sep 2023 17:18:14 GMT</pubDate>
            <atom:updated>2023-09-21T17:18:14.029Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XkYLusYnQIf_E2Be" /><figcaption>Photo by <a href="https://unsplash.com/@aginsbrook?utm_source=medium&amp;utm_medium=referral">Anthony Fomin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>In the bustling streets of New York City, a vibrant tapestry of commuters, tourists, and urban dwellers paints a dynamic picture of daily life. Amidst this urban landscape, Citi Bike, a bike-sharing program, has become an integral part of the city’s transportation ecosystem. But what drives the ebb and flow of Citi Bike ridership? How do factors like weather, pandemics, and holidays impact the usage of these two-wheeled companions?</em></p><p><em>This report embarks on a data-driven journey to uncover the hidden patterns and predictive insights behind Citi Bike ridership in the city that never sleeps. With a comprehensive analysis of five years’ worth of data and an array of variables, we seek to answer the central research question: Can Citi Bike ridership demand be predicted using a multiple linear regression model based on market research data?</em></p><p><em>Join me as we delve into the intricate world of data analysis, exploring the multifaceted influences that shape bike-sharing patterns within the urban context. Discover the tools, methodologies, and challenges encountered in our quest for predictive accuracy. As the city continues to evolve, our findings promise to guide the way for a more efficient and responsive bike-sharing experience in the heart of New York City.</em></p><h3><strong>Research Question</strong></h3><p>This project aims to comprehensively analyze five years’ worth of Citi Bike ridership data, in conjunction with weather patterns, a pandemic control variable, and US holidays data. The primary goal is to gain insights into the key factors that influence bike-sharing usage patterns in New York City and to predict future demand. The central research question that drives this endeavor is:</p><blockquote>Can Citi Bike ridership demand be predicted using a multiple linear regression model based on market research data?</blockquote><p>The bike-sharing industry, much like scooter-sharing organizations, relies heavily on accurate demand predictions to efficiently redistribute inventory across the city and meet user needs. Notably, in 2019, landmark legislation paved the way for the implementation of the NYC Streets Plan, a transformative initiative. Recently, in 2022, Mayor Adams and the New York City Council dedicated a substantial investment of $904 million to bring the NYC Streets Plan to fruition (Transportation Alternatives, 2023). The impending transformation of New York City’s landscape is projected to exert a significant impact on bike-sharing demand. To navigate these forthcoming shifts with precision, it is imperative to rigorously assess various prediction methods to ensure the highest attainable accuracy. Thus, the above-mentioned research question gains substantial justification due to the pressing need to comprehend the multifaceted influences that shape bike-sharing patterns within the urban context and to predict demand accurately.</p><p>This research embarks on a comprehensive analysis by studying Citi Bike ridership data spanning from June 1, 2018, to May 31, 2023. Additionally, it integrates weather data, a pandemic control variable, US holidays, and bicycle counts conducted around New York City at key locations at 15-minute intervals to gain deeper insights into the predictors that shape ridership trends. The analysis is grounded in a desire to understand how these variables impact ridership demand and to formulate an effective predictive model. By understanding the relationship between the predictor variables and the response variable, it should be possible to predict the response variable given the predictor inputs (Faghih-Imani et al., 2014). The research hypothesis is anchored in the objective of achieving a minimum of 70% prediction accuracy through the utilization of a multiple linear regression model that leverages market research data.</p><blockquote>The null hypothesis (H0) asserts that Citi Bike ridership demand cannot be accurately predicted through a multiple linear regression model based on market research data, with an accuracy surpassing 70%. On the contrary, the alternative hypothesis (H1) contends that such a model can indeed achieve a prediction accuracy exceeding 70%.</blockquote><p>To explore these hypotheses, the research employs multiple regression analysis to discern the significance of predictor variables and to identify which of these variables are most influential in predicting Citi Bike ridership trends. Furthermore, time series analysis is a powerful tool that can handle temporal dependencies and seasonal trends in the data, making it particularly suitable for this study (Hyndman &amp; Athanasopoulos, 2018). This analytical approach not only aids in addressing the central research question but also provides a benchmark for algorithmic comparison.</p><h3><strong>Data Collection</strong></h3><p>The data collection process was initiated by sourcing Citi Bike ridership data from the Citi Bike System Data web portal, hourly weather data from Visual Crossing, the Covid-19 pandemic timeline from Investopedia, and US holidays data from Microsoft Azure.</p><p>Historical bike trip data was obtained from the official Citi Bike NYC website, a valuable source that provided a comprehensive snapshot of ridership patterns. This endeavor involved the acquisition of a substantial dataset consisting of 60 CSV files, collectively containing a staggering 122,523,911 rows of ridership data. This expansive dataset provided a rich and detailed account of Citi Bike trips, spanning an extensive timeframe from June 2018 to May 2023. The dataset was organized into a structured format using the powerful data manipulation capabilities of the Pandas library in Python. By utilizing Pandas, the data was transformed into a DataFrame, a versatile data structure that facilitated efficient analysis and manipulation of the dataset. The resulting DataFrame featured a DatetimeIndex, allowing for temporal analysis and exploration of trends over time. All variables and their data types are listed in the table below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4qsZB_pVERu0Pjebd96VSg.png" /><figcaption>1. Citi Bike Ridership Data, Variables</figcaption></figure><p>Hourly weather data was sourced from Visual Crossing, a comprehensive historical weather database. The dataset covered New York City’s weather conditions from June 2018 to May 2023, providing variables such as temperature, wind speed, precipitation, and more. All variables and their data types are listed in the table below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t_SgqaJBsUjfS1Cq_9Wj1A.png" /><figcaption>2. Hourly Weather Data, Variables</figcaption></figure><p>Given the significant impact of the Covid-19 pandemic on ridership trends, pandemic control variables were incorporated. These variables were designed to account for variations in bikeshare trip volume during distinct phases of the pandemic. A timeline of the pandemic was extracted from Investopedia, enabling the categorization of data into pre-pandemic, during-pandemic, and post-pandemic periods. All variables and their data types are listed in the table below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PznXSkCpnSM162E-pjX2XQ.png" /><figcaption>3. Pandemic Control Variables</figcaption></figure><p>To assess the influence of holidays on ridership patterns, US holidays data was integrated from Microsoft Azure’s open datasets API. This dataset facilitated the analysis of how holidays impact bike-sharing usage, adding a valuable contextual dimension. All variables and their data types are listed in the table below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wk7GPkp_JeJk_T3XEveLFQ.png" /><figcaption>4. Holiday Variables</figcaption></figure><p>The NYC Bicycle Counts dataset was sourced from the NYC Open Data portal, offering a comprehensive insight into bicycle usage around New York City. The dataset captures bicycle counts conducted at strategic locations within the city at 15-minute intervals. This rich temporal granularity enables the examination of detailed patterns and trends in bicycle ridership over time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T5MeRGVG6iZdqo_l0ipJ4g.png" /><figcaption>5. NYC Bicycle Counts, Variables</figcaption></figure><p>In summary, the data collection process involved meticulous sourcing from diverse channels, ensuring that the dataset encompassed influential factors in bike-sharing usage patterns. By combining this data with other sources such as weather conditions and holidays, it becomes possible to uncover correlations and trends that shape bicycle usage patterns. The data can also be used to explore the determinants of cycling behavior, and the factors influencing the use of bike sharing systems (Ricci, 2019). Additionally, this data can serve as a foundation for predictive modeling, offering the potential to forecast future Citi Bike ridership based on various influencing factors.</p><h4><strong>Advantage of the Data-Gathering Methodology</strong></h4><p>An advantageous aspect of the data-gathering methodology lies in its comprehensive incorporation of a wide array of variables that hold potential influence over Citi Bike ridership. The inclusion of weather data, pandemic-related variables, and holidays data imparts a holistic perspective on the myriad factors that shape ridership patterns. As a result, this comprehensive approach contributes to the development of a predictive model characterized by enhanced accuracy and profound insights.</p><h4><strong>Disadvantage of the Data-Gathering Methodology</strong></h4><p>Conversely, a drawback of this data-gathering methodology lies in the potential introduction of noise and intricacy stemming from the amalgamation of diverse data sources. For instance, weather data could manifest variations that lack direct correlation with ridership trends. This introduces the possibility of injecting extraneous noise into the analysis, potentially culminating in overfitting within the predictive model.</p><h4><strong>Overcoming Challenges</strong></h4><p>Numerous challenges emerged during the data gathering phase, primarily rooted in data preprocessing and addressing missing values. The presence of incomplete or absent data points poses the risk of inducing bias within the subsequent analysis.When dealing with data that is missing at random, related data can be deleted to reduce bias (Master’s in Data Science, n.d.). In response, a range of data cleaning methodologies were implemented. These encompassed the removal of rows containing missing values and the transformation of categorical variables into binary counterparts via dummy variables. Moreover, meticulous attention was directed toward aligning data from disparate sources in a coherent manner. This intricate process demanded a judicious fusion of data manipulation and merging techniques, pivotal in attaining results that remained both precise and meaningful.</p><p>In summation, the data collection process entailed the comprehensive aggregation of diverse datasets for a comprehensive evaluation of Citi Bike ridership trends. While this methodology furnishes notable advantages by integrating multifaceted variables, it concurrently introduces intricacies necessitating meticulous management during preprocessing and analysis. Through meticulous diligence in data cleaning and manipulation, the complexities were surmounted, culminating in a dataset of exceptional quality poised for in-depth analysis.</p><h3><strong>Data Extraction and Preparation</strong></h3><h4><strong>Data Extraction</strong></h4><p>The initial stride within the data extraction process encompassed the transformation of the 60 resource-intensive CSV files containing Citi Bike data into more lightweight Parquet files. Subsequent to the conversion of CSV files to Parquet format, the ensuing progression involved the ingestion of each file. This phase entailed the establishment of uniformity in column names, the exclusion of superfluous columns, and the conversion of trip times to a datetime format, as illustrated below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SYgK9SpgMEbGKfNrQq_WYA.png" /><figcaption>6. Data Extraction, Step 1</figcaption></figure><p>Following these manipulations, each file underwent amalgamation into a principal DataFrame. To ensure a judicious management of this extensive procedure, the timing of the data collection endeavor was meticulously tracked. Each file’s processing time was logged, concurrently displaying both the mean time per file and an estimate of the remaining duration. This iterative timing mechanism facilitated the maintenance of well-timed updates throughout the course of this protracted undertaking.</p><p>Subsequently, the following phase entailed the elimination of trips that had their inception or termination within the confines of the Bronx, New Jersey, or an undisclosed borough. This discerning filtration of data resulted in a reduction of dataset size by 22.91%. Nevertheless, this process left an abundant 94.45 million rows available for further analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MGoHR5Vg4fUY38TWpcrwKQ.png" /><figcaption>7. Data Extraction, Step 2</figcaption></figure><p>Subsequently, the “usertype” column was divided into two separate columns representing user types, and a similar process was applied to the start and end borough columns. The original columns were eliminated, and distinct columns were generated for each pairing of trip origin or destination and user type. The final step involved resampling the datetime index at an hourly interval, leading to a reduction in data size from 3.2 gigabytes to a more manageable 7.4 megabytes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qRD61jba-B5jdaRUlEm6aQ.png" /><figcaption>8. Data Cleaning, Step 1</figcaption></figure><p>The weather data contained extensive details, but excessive granularity could result in overfitting. To address this, the initial action involved removing irrelevant columns and designating the date as a datetime index.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rg45KuTEA_4L3MZJxDnX5w.png" /><figcaption>9. Data Cleaning, Step 2</figcaption></figure><p>The Azure holidays data encompassed global holidays. Initially, holidays not applicable to the United States were eliminated, and any country-related columns were discarded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9mVoZ40nBmh9BBczIthtjg.png" /><figcaption>10. Data Cleaning, Step 3</figcaption></figure><p>Following this, the date column was transformed into a datetime index. Subsequently, an “isHoliday” column was generated to indicate holiday dates. The data was further resampled on a daily basis to include non-holiday dates. In the “holidayName” column, entries were replaced with “Non-Holiday.” The resultant DataFrame was resampled once more on an hourly basis to align with the Citi Bike and weather data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LbHhcGDzdqoMFOxxeok96Q.png" /><figcaption>11. Data Cleaning, Step 4</figcaption></figure><p>The NYC Bicycle Counts dataset’s first cleaning step was to begin by removing unnecessary variables (‘countid’, ‘id’, ‘status’). Subsequently, counts from various NYC locations are aggregated by grouping the data based on the ‘date’ column. This consolidation results in a summation of bicycle counts for each unique date. The datetime index of the aggregated DataFrame is converted for efficient temporal manipulation. Sorting the data chronologically by date ensures a coherent sequence. The analysis then narrows its focus to the period from June 1, 2018, to May 31, 2023, through the selection of relevant dates using the ‘loc’ function. The aggregated daily counts are further refined by resampling at an hourly frequency, enhancing the temporal granularity. Finally, to enhance clarity, the counts column is renamed as ‘nyc_bike_counts’. These combined steps yield a well-preprocessed DataFrame containing hourly bicycle counts, setting the stage for comprehensive analysis of bicycle ridership patterns across New York City.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AjVQCLB01N9QDqlHQ4Z_Cg.png" /><figcaption>12. Data Cleaning, Step 5</figcaption></figure><p><strong>Justification and advantages/disadvantages.<br></strong>The central tool utilized for efficient data extraction revolved around the Pandas library. By making use of the capabilities offered by the Glob2 and OS libraries, the process of loading Parquet and CSV files into DataFrames was executed smoothly. Additionally, the DateTime and Numpy libraries played a key role in enabling efficient access to data within substantial files. The decision to prioritize the Pandas library for data extraction was driven by its prevalent use in data manipulation tasks within the industry. Additionally, the integration of Azure ML’s PublicHolidays class simplified the retrieval of public holiday data. This class was selected for its ability to streamline the data collection process, contributing to improved efficiency and accuracy throughout the endeavor.</p><p>Pandas, Glob2, OS, DateTime, and Numpy collectively provided a robust suite of tools that greatly facilitated the management and manipulation of the data. Pandas, being the central library, played a pivotal role in handling various data formats like Parquet and CSV, which were effortlessly loaded into structured DataFrames. The inclusion of Glob2 and OS libraries further enhanced the data extraction process, streamlining the handling of files and directories.</p><p>DateTime and Numpy libraries seamlessly integrated into the workflow, ensuring efficient access to data within large files and enabling seamless datetime operations. These libraries were particularly beneficial in handling timestamps and time-based calculations, which were crucial for aligning data from multiple sources accurately.</p><p>The decision to rely on Pandas as the primary data extraction tool was well-founded due to its proven effectiveness in data manipulation tasks. Additionally, the utilization of Azure ML’s dedicated class for acquiring holiday data demonstrated a strategic choice, simplifying the retrieval of essential information and enhancing overall efficiency in the process. This amalgamation of tools and techniques streamlined the data extraction phase and laid a strong foundation for subsequent analysis and modeling.</p><p>While Pandas is highly proficient in managing datasets of moderate sizes, it could encounter challenges when confronted with significantly larger datasets due to memory constraints. However, a strategic approach to mitigate these limitations involves converting CSV files to Parquet format, which substantially alleviates the memory burden. Furthermore, it’s important to acknowledge that the process of extracting data from external sources may introduce additional intricacies, such as dealing with API authentication procedures and potential network connectivity issues. These factors underscore the importance of considering the scalability of data extraction methods and ensuring smooth interactions with external sources for comprehensive data collection.</p><h4><strong>Data Preparation</strong></h4><p>The data underwent a meticulous cleaning and preparation procedure, encompassing actions like renaming columns, discarding irrelevant attributes, handling missing values, converting data types, and generating novel features. The initial step in readying the data for analysis involved consolidating information from diverse sources into a unified DataFrame. Specifically, the weather data was initially integrated with the Citi Bike dataset utilizing the datetime index, followed by the incorporation of holiday data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wt1obvhID0Jm4UG8zc6thw.png" /><figcaption>13. Data Aggregation, Step 1</figcaption></figure><p>Five instances of missing values were detected within the weather dataset, and to rectify this, they were imputed using the mean value of the preceding and subsequent observations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pISRm6tygKpwtJcfFZRdHA.png" /><figcaption>14. Data Aggregation, Step 2</figcaption></figure><p>After detecting several outliers, the logical next step involved implementing data winsorization to address this issue. The primary goal of this process is to alleviate the influence of extreme values, which have the potential to disrupt the integrity of the models and their subsequent analyses. By strategically capping extreme values, data winsorization contributes to a more stable and reliable modeling outcome.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zTG1nQJ0xc7AFn5J1TfPLw.png" /><figcaption>15. Data Aggregation, Step 3</figcaption></figure><p>Following the consolidation of data into a unified file, the subsequent pivotal phase involved feature engineering. This strategic process imparts the dataset with enhanced insights, capable of bolstering the efficacy of predictive models. Key temporal attributes including the hour, weekday, month, year, and seasons were meticulously extracted from the datetime index. Leveraging the weekday information, a binary weekend variable was ingeniously crafted, assigning 0 to weekdays (Monday to Friday) and 1 to weekends (Saturday and Sunday). This nuanced transformation adds valuable context to the dataset and lays the foundation for more robust analyses and predictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R7hsqQ2ZeKQTXek0cPoBog.png" /><figcaption>16. Feature Engineering, Step 1</figcaption></figure><p>According to The New York Times, the morning rush hours span from 7:30 AM to 9:30 AM, while the evening rush hour is from 5:00 PM to 7:00 PM. Given the dataset’s hourly frequency, adjustments were made. The morning rush hour was extended from 7:00 AM to 10:00 AM, maintaining the evening rush hour as originally defined. These refined time intervals, in combination with the extracted weekend and hour variables, were harnessed to construct the informative “hour_type” variable. This new variable effectively encapsulates the temporal dynamics of rush hours and weekends, offering a valuable dimension for further analysis and interpretation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ze-Ab-IW05vMhdHAtFEOgA.png" /><figcaption>17. Feature Engineering, Step 2</figcaption></figure><p>The last phase of feature engineering culminated in the formulation of the “pandemic_period” variable, designed to encapsulate the variable ridership patterns witnessed during the Covid-19 pandemic. Drawing insights from the Investopedia timeline, pivotal pandemic events were identified and leveraged to segment the data into distinct periods: pre-pandemic, lockdown, reopening, post-vaccine, and post-pandemic. This comprehensive division provides a nuanced understanding of how different pandemic stages influenced Citi Bike ridership demand. By incorporating this variable into the analysis, the model gains the ability to capture and differentiate ridership trends across these pivotal phases, contributing to the depth and accuracy of the predictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OKHqUM5owoXG7CYJdoo8aA.png" /><figcaption>18. Feature Engineering, Step 3</figcaption></figure><p>In the final leg of data preparation, a pivotal step was taken to convert the data into a machine-readable format. Specifically, the ordinal variables “pandemic_period” and “season” were subjected to label encoding. This method preserves the inherent sequential order within these variables, ensuring that their underlying patterns and relationships are maintained in a manner that machine learning algorithms can readily comprehend. This transformation enhances the model’s capacity to discern the nuanced distinctions in pandemic periods and seasons, fostering more accurate predictive outcomes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A6ACekIEQ-01fkn0guhBMQ.png" /><figcaption>19. Data Transformation, Step 1</figcaption></figure><p>By applying trigonometric functions, specifically sine and cosine, to the “hour” and “season” variables, their inherent cyclical tendencies were safeguarded. This intricate process, known as cyclical encoding, works as a mechanism to retain the cyclic patterns that inherently reside within time-based features. The result is a dataset enriched with new variables that harmoniously capture the rhythmic ebbs and flows of hours and seasons, elevating the model’s discernment of cyclic trends and bolstering the potency of predictive analyses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sjmqapgJISG1GlX_J5BeWQ.png" /><figcaption>20. Data Transformation, Step 2</figcaption></figure><p>The data transformation journey culminated with the application of one-hot encoding to the residual categorical variables. This task was deftly executed by harnessing the power of the Pandas library’s “get_dummies” function. The purpose of this encoding method is to translate categorical variables into a format that machine learning algorithms can readily comprehend. Each categorical attribute metamorphosed into a set of binary variables, each representing a distinct category. This transformation empowers the predictive model by eliminating any hierarchical or ordinal assumptions while enhancing its ability to glean insights from categorical attributes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hrw6dNsKa9IODf0qzqNHLg.png" /><figcaption>21. Data Transformation, Step 3</figcaption></figure><p><strong>Justification and advantages/disadvantages.<br></strong>The robust capabilities of Pandas were instrumental in the data extraction and preparation phases. The utilization of strategies such as column renaming, elimination, and data type conversion was pivotal in orchestrating the harmonious metamorphosis of the dataset. These transformative maneuvers were executed employing an array of Pandas functions, including the versatile “map” and “get_dummies” functionalities. The selection of Pandas as the linchpin of this operation was steered by its remarkable adaptability to diverse data manipulation tasks. This adaptability, in turn, fostered a seamless orchestration of data transformations while preserving data integrity.</p><p>The inherent flexibility of Pandas served as a cornerstone, empowering the adept manipulation and transformation of the data to align with the project’s demands. This dynamic library proved to be an invaluable asset, effortlessly shouldering tasks such as the rectification of missing values and the conversion of data types.</p><p>Much like in the data extraction phase, Pandas’ efficiency could diminish when handling exceptionally large datasets. Additionally, manual data preparation processes hold the potential for errors or inconsistencies if not carefully supervised. The utilization of one-hot encoding may result in expanded dataset dimensions, potentially elevating memory usage and computational intricacies. Moreover, excessive or inappropriate feature engineering could introduce unwanted noise or multicollinearity within the dataset.</p><p>In summary, the execution of the data extraction, transformation, and preparation process was skillfully conducted through the utilization of tools and techniques offered by Pandas, NumPy, and Azure ML’s PublicHolidays class. These tools provided the necessary adaptability, functionality, and efficiency for navigating the intricate realm of data cleaning, transformation, and aggregation. Nonetheless, it remains vital to exercise prudence and account for resource management, especially when managing substantial datasets or intricate merging tasks.</p><h3><strong>Analysis</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8UXPlit9xsDYKj6vwLHoAA.png" /><figcaption>22. NYC Citi Bike Ridership Trends</figcaption></figure><h4><strong>Data Exploration</strong></h4><p>Initiating the data exploration process involved generating plots to discern the weekly, monthly, and yearly trends through rolling mean calculations. The graphical representations in Figure 22 revealed an accumulative trend across successive years, experiencing a temporary downturn during the initial pandemic period. Further visualization was carried out using a bar plot, as illustrated in Figure 23, showcasing the ridership distribution across different seasons. It was evident from this plot that Summer held the majority share at 31% of total trips, while Winter contributed a comparatively lower percentage of 16%. This observation lent substantial support to the hypothesis that temperature could wield a substantial impact on ridership patterns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7VXOhCCFnwbCKYUEk6VlWQ.png" /></figure><p>The correlation matrix, illustrated in Figure 24, provides additional evidence supporting the connection between temperature and ridership. The matrix analysis revealed that temperature and hour exhibit the most substantial positive correlation with ridership, indicating that higher temperatures and specific hours of the day are associated with increased ridership. Conversely, humidity emerges as the variable with the highest negative correlation, implying that higher humidity levels might deter ridership.</p><p>Exploring feature importance goes beyond mere correlation and offers a deeper understanding of how each variable contributes to predictive models. By quantifying the impact of temperature, hour, and other factors through feature importance analysis, their relative significance in predicting ridership patterns accurately can be ascertained. This quantitative assessment allows for influential variables to be prioritized when constructing predictive models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*CiWS28s1_Cv9nEeduYHGxA.png" /><figcaption>24. Correlation Matrix</figcaption></figure><p>The examination of the influence of holidays on ridership unveiled interesting patterns. Specifically, it was observed that holidays trigger a decline in ridership within Manhattan, whereas Brooklyn experiences an uptick in ridership. On the other hand, Queens appears to remain relatively unaffected by holidays in terms of ridership trends. This differentiated response across boroughs underscores the complex interplay between holidays and ridership habits.</p><p>Furthermore, when exploring the distribution of rider types, as illustrated in Figure 25, a noteworthy trend emerged. Despite the overall decrease in ridership within Manhattan, there is a notable increase in casual riders across all boroughs during the same time frame. This observation suggests that casual ridership might have a distinctive behavior pattern compared to members, which is important to consider when formulating predictive models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sfaN-ewbCrp10z_XH1UUqA.png" /><figcaption>25. Ridership Distribution by Day Type and Rider Type</figcaption></figure><p>The analysis of the Covid-19 pandemic’s effects on ridership revealed that the most significant shifts in ridership trends occurred during the morning and evening rush hour periods. As illustrated in Figure 26, the hours between 6:00 AM and 10:00 AM accounted for no more than 4% of bike trips each hour during the lockdown period, a stark contrast to the pre-pandemic scenario where these same hours contributed to up to 8% of bike trips during the peak morning rush hour at 8:00 AM. Conversely, an inverse relationship was observed for the evening rush hour period. Before the pandemic, the afternoon and evening hours exhibited the smallest share of ridership compared to the other pandemic periods, while the lockdown phase witnessed the highest percentage of bike trips during these hours.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U0INOgfYPN08RbBD7h4k1A.png" /><figcaption>26. NYC Citi Bike Ridership Distribution: Hourly by Pandemic Period</figcaption></figure><p>The examination of ridership distribution by weekday and pandemic period revealed a consistent shift in trends from the pre-pandemic era to the lockdown phase and subsequently the reopening period. As depicted in Figure 27, the line plot demonstrates that ridership reached its zenith on Wednesdays during the pre-pandemic period and gradually declined for each subsequent day. However, during the lockdown period, ridership increased from Friday through Sunday and exhibited fluctuating patterns on weekdays. This behavior was further mirrored in the reopening phase, wherein ridership peaked on Saturdays and more closely adhered to the pre-pandemic trends during the weekdays.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hOTdy8Nuu1sdPL9y3trE1A.png" /><figcaption>27. NYC Citi Bike Ridership Distribution: Week Day by Pandemic Period</figcaption></figure><p>Upon delving into an extensive examination of ridership trends through the lenses of weather conditions, holiday occurrences, and pandemic periods, a subsequent phase of analysis encompassed the exploration of individual variable distributions. The insights drawn from this exploration contribute valuable context to the overall understanding of the data’s characteristics.</p><p>The box-plots depicted in Figure 28 stand as informative visual representations of the data’s distribution characteristics. These boxplots provide a comprehensive overview of how variables behave in terms of their central tendencies, spread, and presence of potential outliers. Specifically, the efficacy of the winsorization technique, which was applied during the preliminary data preparation stage, becomes readily apparent. This technique successfully ensures that the total number of trips within New York City — the target variable for subsequent predictive modeling — displays a right-leaning distribution while maintaining a notable absence of significant outliers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JxGu1zfrsW3BAhkmz6fKuQ.png" /><figcaption>28. Distribution of Numerical Variables</figcaption></figure><p>Furthermore, a detailed examination of other essential variables showcases intriguing patterns. The temperature, humidity, windspeed, and weekday variables, for instance, follow distribution patterns consistent with a normal distribution. This conformity to a bell-shaped curve suggests a characteristic distribution that is symmetric and centered around the mean value. The attributes of these variables appear to align with expected trends and provide insights into their potential influence on ridership.</p><p>However, the visibility variable diverges from this norm. Its distribution exhibits a pronounced right-skew, indicating that the majority of data points are clustered toward the lower values of visibility. This unique distribution feature could potentially imply that instances of low visibility might be more frequent compared to higher visibility conditions, thereby suggesting a distinctive impact on ridership patterns under such circumstances. In essence, the exploration of individual variable distributions supplements the comprehensive understanding of the dataset, further guiding subsequent analyses and modeling endeavors. By uncovering the distinct distribution characteristics of various variables, this analysis adds depth to the insights derived from the overall exploratory process.</p><p><strong>Justification and advantages/disadvantages.<br></strong>The selection of analysis techniques was driven by the specific objectives of uncovering insights into ridership trends and their underlying factors. Each technique was chosen to contribute to a comprehensive understanding of the data, aligning with the research question at hand. Rolling mean calculations and trend visualization were employed to identify long-term patterns over time, such as weekly, monthly, and yearly trends. While this technique smooths out noise, it might overlook short-term fluctuations. Bar plots were utilized for seasonal analysis, effectively portraying the distribution of categorical variables like seasons. This approach simplifies categorical relationships, but may miss complex interactions.</p><p>The correlation matrix and feature importance analysis offered a quantitative perspective on relationships and influential features. While the correlation matrix revealed potential drivers, it did not establish causation. Similarly, feature importance quantified variable impact but might not capture collective interactions. Examining the impact of external factors like the Covid-19 pandemic and holidays provided insights into unique ridership trends and disruptions. However, this analysis might not encompass all underlying causal factors.</p><p>Exploring variable distributions shed light on characteristics like skewness, normality, and outliers. This guided subsequent data preparation steps and modeling choices. However, focusing solely on individual variable distributions might not capture complex interactions between variables. It’s important to acknowledge that these techniques have limitations. For instance, correlation does not imply causation, and individual variable analysis might not uncover all interactions. Despite these limitations, combining multiple techniques mitigates their drawbacks, providing a robust and comprehensive perspective on ridership trends.</p><h4><strong>Time-Series Analysis</strong></h4><p>In embarking upon the phase of time-series analysis, the initial stride involved an intricate exploration through seasonal decomposition — an insightful technique poised to unveil the latent constituents residing within the temporal data. This technique effectively disassembles the time series, unraveling it into three distinct and discernible elements: trend, seasonal, and residual components. By unraveling these components, a comprehensive panorama emerges, shedding light on the intricate interplay of temporal patterns and trends that characterize the dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_v-WWmAW3nNrPFZs7LUj7Q.png" /><figcaption>29. Seasonal Decomposition</figcaption></figure><p>The seasonal decomposition plots showcased in Figure 29 serve as a visual aid in illustrating the results of this analysis. Notably, these plots bring to light the presence of an annual cyclic trend inherent within the data. This recurring pattern, unfolding across the span of a year, bespeaks a regularity that encapsulates the dataset’s yearly rhythms. However, an equally significant revelation emerges in the trend component. In this aspect, the data diverges from the anticipated narrative, displaying a lack of discernible and conspicuous patterns within the trend component. The juxtaposition of these two components — the cyclical rhythm encompassed by the seasonal element and the relatively unstructured nature of the trend — forges a nuanced understanding of the temporal dynamics encapsulated within the data.</p><p>The subsequent step involved the depiction of residuals, captured within Figure 30. The resultant histogram plot provided a tangible representation of these residuals, revealing their distributional tendencies. However, it became apparent that this distribution did not uniformly adhere to the contours of a typical normal distribution — warranting further consideration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*h6FupMDzqco2dFvnSuSNfQ.png" /><figcaption>30. Histogram of Residuals</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*44ywCOo8_eci7k80k4QScw.png" /><figcaption>31. Histogram of Log-Transformed Residuals</figcaption></figure><p>The target variable underwent a log-transformation, a method chosen to induce a more balanced and normative distribution within the residual plot. As this transformation took root, the histogram plot observed within Figure 31 reflected a shift, evidencing the normalization imparted by the log-transformation. Yet, as with many endeavors seeking equilibrium, a nuanced residue persisted — a slight leftward skew, reminiscent of the intricacies often present in complex real-world data.</p><p>The subsequent phase involved generating autocorrelation and partial autocorrelation plots. These graphical tools are essential components of time series analysis, enabling the identification of underlying patterns and dependencies within data over time. The autocorrelation plot (ACF), shown in Figure 32, is a visualization that illustrates the correlation between a series and its lagged versions. When scrutinizing the autocorrelation plot, it was evident that there were no significant lags beyond which the correlation between the current observation and its past observations became negligible. This suggests that there isn’t a pronounced repeating pattern in ridership demand that extends beyond the immediate past.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vx_K3pY9oOTFnoAx-jAeUQ.png" /><figcaption>32. Autocorrelation/Partial Autocorrelation Plots</figcaption></figure><p>Conversely, the partial autocorrelation plot (PACF) delves deeper into the direct relationship between a data point and its lagged versions while accounting for the influence of intermediate observations. It allows for the identification of correlations that can’t be explained by preceding lags. In the analysis, the partial autocorrelation plot revealed a significant correlation at a lag of zero, indicating that the current ridership demand is directly related to its immediate past value. This suggests a strong auto-regressive component in the time series, where the current demand is influenced by its previous demand value.</p><p>These plots serve as critical diagnostic tools to discern the temporal dependencies within the data, aiding in the informed decision-making about modeling techniques and parameter selections. In this case, the absence of significant autocorrelation lags and the presence of a notable partial autocorrelation at lag zero provided insights into the nature of the time series and guided the subsequent modeling choices.</p><p>In the subsequent phase, the Dickey-Fuller test was performed on the training dataset — an integral step in scrutinizing time series data. This test serves a crucial role in determining whether the data exhibits a consistent pattern or displays more unpredictable behavior over time. The Dickey-Fuller test yielded specific results that offer significant insights into the nature of the dataset. The Test Statistic stands as a pivotal indicator. The value of -9.20 indicates that the dataset reveals a consistent pattern, suggesting its stationary nature rather than susceptibility to random fluctuations. The exceedingly small P-value of 1.98e-15 underscores that the likelihood of encountering such a result by random chance is extremely low. This strengthens the argument that the dataset demonstrates stationary behavior.</p><p>Upon evaluating the Critical Values, it is evident that thresholds exist at the 1%, 5%, and 10% significance levels. Importantly, the Test Statistic surpasses all of these critical values. This observation is noteworthy as it reaffirms the dataset’s consistent patterns, thus enhancing its reliability for subsequent analysis. In this context, the term “stationary” conveys that the statistical characteristics of the data remain stable over time. This outcome is highly favorable and confirms the dataset’s steady and stationary patterns, as it plays an integral role in ensuring the credibility of subsequent analysis and predictions.</p><p>The Variance Inflation Factor (VIF) measures the multicollinearity between predictor variables in a regression model. In general, a VIF value of 1 indicates no multicollinearity, while higher values indicate increasing multicollinearity. A common guideline is that VIF values above 10 can be considered concerning and might warrant further investigation or potential remediation. Following the initial calculation of the VIF for each variable, the obtained results shed light on potential multicollinearity concerns. The VIF values for the variables were as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zDnjCZjUzQVn0KUTdxMDAw.png" /><figcaption>33. Original Variance Inflation Factor Results</figcaption></figure><p>These initial VIF results provided insights into the degree of collinearity among the predictor variables. Notably, variables such as “year” and “season” exhibited relatively high VIF values, indicating the potential presence of multicollinearity. In response to these findings, a refinement was conducted by excluding the “year” and “season” variables from the dataset. This adjustment aimed to alleviate the multicollinearity issue and ensure that the remaining variables contribute independently to the predictive model. The subsequent VIF results, were as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wDOO2TGUuz0wpqFa7fdxWw.png" /><figcaption>34. Refined Variance Inflation Factor Results</figcaption></figure><p>The refined VIF values indicated a reduction in multicollinearity concerns after the removal of “year” and “season.” This iterative process of assessing and refining the VIF values contributes to the selection of independent and meaningful predictor variables, ensuring the robustness of the subsequent predictive model.</p><p>ARIMA (AutoRegressive Integrated Moving Average) is a popular time series forecasting method that combines autoregressive, integration, and moving average components. It models time-dependent data by considering the past values, differencing to achieve stationarity, and past prediction errors. ARIMA is specified by parameters ‘p’ (autoregressive order), ‘d’ (integration order), and ‘q’ (moving average order). It’s used for predicting trends, seasonality, and cycles in time series data. While versatile, ARIMA assumes linearity and constant parameters over time.</p><p>In the subsequent step, the construction of an initial Autoregressive Integrated Moving Average (ARIMA) model revealed valuable insights into its performance. The Akaike Information Criterion (AIC) is a statistical measure used for comparing the quality of different statistical models. It balances the trade-off between model fit and complexity by penalizing models with more parameters. AIC quantifies how well a model fits the data relative to the number of parameters it uses, aiming to prevent overfitting. Lower AIC values indicate better model suitability, making it a useful tool in selecting the most appropriate model within a dataset by considering both goodness of fit and model simplicity.</p><p>The model’s AIC value was computed at -76,138.82, offering a measure of the model’s goodness of fit relative to its complexity. Furthermore, the mean-absolute-percentage error (MAPE) was computed at 26.69%. MAPE is a metric used to evaluate the accuracy of a forecasting model. It measures the average percentage difference between predicted and actual values, providing insight into the magnitude of prediction errors relative to the actual values. The Root Mean Square Error (RMSE) is another widely used metric for assessing the accuracy of predictions or forecasts. It measures the square root of the average of the squared differences between predicted and actual values. RMSE represents the typical size of the errors in the model’s predictions, giving an indication of how well the model fits the data. It is sensitive to larger errors due to the squaring process and is often used to compare the performance of different models. A lower RMSE indicates better predictive accuracy, with values closer to zero reflecting a closer match between predictions and actual data.</p><p>The root-mean-square error (RMSE) was assessed at 905.44, providing a representation of the average magnitude of the model’s prediction errors, and finally the Accuracy Rate was determined to be 73.3%. These metrics collectively yielded a comprehensive understanding of the model’s effectiveness in capturing inherent data patterns. The above metrics are calculated as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EdAaFSte7i9I-iN32iuxmA.png" /><figcaption>35. Model Metric Calculations</figcaption></figure><p>To quantify the uncertainty within the model’s predictions, confidence intervals were established through bootstrapping, employing 1000 data points. The resultant visualization (Figure 36), portraying actual versus predicted values along with their associated confidence intervals, offered a clear depiction of the model’s predictive capabilities. This visual representation facilitated an assessment of how well our model’s predictions aligned with actual observations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o-oUivoPk8ifyOnjkcZNMg.png" /><figcaption>36. Citi Bike Ridership: Actual vs. Predicted (Rolling 7 Days)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2jZfXNxjJLZDSgXHnvQnGA.png" /><figcaption>37. Q-Q Plot of Residuals</figcaption></figure><p>Subsequent to this, a thorough analysis of the residuals was conducted to assess the model’s assumptions and performance. The Quantile-Quantile (Q-Q) plot (Figure 37) exhibited a robust positive correlation with a pronounced heavier tail towards the third theoretical quantile.</p><p>This pattern suggested that the model performed well in capturing central tendencies but displayed deviations in extreme observations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IizP5R_mU6NKFzlNv9jr2w.png" /><figcaption>38. Residual Plot</figcaption></figure><p>The residual plot (Figure 38) displayed residuals tightly clustered around the zero-line, affirming the model’s competence in accurately predicting the majority of observations. Furthermore, examination of the residual distribution (Figure 39) unveiled a prolonged tail towards lower values, alongside a noticeable leftward skew. This indicated that the model occasionally encountered challenges when predicting extreme values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3DZTcvD30_UWSgx4AnCbIg.png" /><figcaption>39. Distribution Plot of Residuals</figcaption></figure><p>Concluding the analysis, the residuals versus predicted plot (Figure 40) showcased a significant positive correlation, with the majority of data points concentrated within the lower half. This trend underscored the model’s tendency to underestimate higher values. Collectively, these diagnostic plots offered invaluable insights into the model’s performance and residual behavior, enabling a comprehensive evaluation of its accuracy, assumptions, and fit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O5Nsnl00Rg9sClp1e5H4bQ.png" /><figcaption>40. Residuals vs. Predicted Plot</figcaption></figure><p>Additionally, the Anderson-Darling test, a vital diagnostic tool, was employed to assess the normality of the residuals. The calculated Anderson-Darling Test Statistic of 121.69 was compared against critical values at various significance levels indicating that the residuals deviate from normality at all significance levels. The outcomes of this test are summarized in the table below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EckFHOx1V8n3xwSNgRbV8A.png" /><figcaption>41. Anderson-Darling Test Results</figcaption></figure><p>The subsequent step involved determining feature importance using the random forest algorithm, a robust technique for assessing the relative significance of each feature in predictive modeling. These importance scores offer insights into the extent to which each feature contributes to the model’s predictive performance. Subsequently, a stepwise regression process was undertaken, guided by the feature importance ranking. At each iteration, the feature with the least significance was removed. However, intriguingly, the results underscored that the most effective model encompassed all but the ‘is_holiday’ feature. This outcome emphasized the collective significance of these features in accurate prediction. The importance scores obtained for various features are as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YrxATinUZgFIRHtTYQ3aLg.png" /><figcaption>42. Feature Importance</figcaption></figure><p>Subsequently, a systematic assessment was conducted to determine the optimal forecast horizon, a critical factor in refining predictive accuracy. An iterative search was performed, ranging from one to twelve months. These results were visualized in Figure 43, allowing for a comprehensive understanding of the relationship between forecast horizon and performance metrics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6HBDxFKv4cRvLqv2bWMBwg.png" /><figcaption>43. Horizon vs. Accuracy Rate Plot</figcaption></figure><p>Notably, the evaluation identified the best forecast horizon as six months based on an Accuracy Rate of 81.66%. This new forecast horizon yielded a significant 11.39% improvement in the Accuracy Rate and a noteworthy 15.08% reduction in AIC compared to the initial forecast horizon. The Accuracy Rate and AIC improvements were calculated using the following equation where 𝑦 is the percentage of improvement, 𝑥0 is the original value, and 𝑥1 is the new value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*-E0lSjz0LDmmjrxbyyqnYg.png" /></figure><p>This assessment offers valuable guidance in choosing the appropriate forecast horizon, a key aspect in optimizing the predictive modeling process and ensuring robust predictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*coUJqePZeOeyJbVTE0_AoQ.png" /><figcaption>44. Citi Bike Ridership: Actual vs. Predicted (6-Month Horizon, Rolling 24 Hours)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZLv5zATGmbt3S5j2I53s7w.png" /><figcaption>45. Citi Bike Ridership: Actual vs. Predicted (6-Month Horizon, Rolling 7 Days)</figcaption></figure><p>Upon determining the optimal 1-month forecast horizon, a new forecast was generated, incorporating recalculated confidence intervals through bootstrapping. This updated forecast was visually represented in Figure 44, providing an illustrative overview of the forecasted values and their associated uncertainties. A broader view can be observed in Figure 45, which depicts a rolling 7-day mean.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WoC9ZQYzibECb6SsNxTxKA.png" /><figcaption>46. Residual Plot</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6-kuI03kmdPwnJshSqzJjw.png" /><figcaption>47. Distribution Plot of Residuals</figcaption></figure><p>Upon analyzing the residuals, it became evident that they did not resemble those of the original model. The residual plot illustrated in Figure 46 depicts residuals that are much more tightly packed around the zero-line than those in Figure 38. The distribution displayed a significantly more normally distributed bell-curve. This distributional insight was visually depicted in Figure 47, providing a tangible representation of the residual behavior.</p><p>The calculated Anderson-Darling Test Statistic of 59.45 was contrasted with critical values at various significance levels, revealing that the residuals exhibit non-normal behavior across all significance levels. However, a smaller Anderson-Darling test statistic in comparison to the prior test statistic suggests that the newly forecasted data conforms more closely to a normal distribution. This could imply an enhanced level of goodness of fit, indicating that the disparities from the specified distribution are relatively minimized, a desirable characteristic for statistical modeling and analysis. The results of this assessment are summarized in Figure 48. These evaluations and examinations significantly contributed to a deeper understanding of the forecast’s precision, the underlying presumptions, and any deviations from the model’s assumptions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vqtxMERGOlVuuu24w4nFcw.png" /><figcaption>48. Anderson-Darling Test Results</figcaption></figure><p><strong>Justification and advantages/disadvantages.<br></strong>The selection of analysis techniques was meticulously guided by the research objectives and the nature of the temporal data. Seasonal decomposition was chosen as the initial technique to uncover underlying patterns within the time series, as it effectively breaks down the series into its trend, seasonal, and residual components. This technique is advantageous as it provides a holistic view of temporal patterns and trends. However, one limitation is that it might not capture interactions between components that contribute to the observed patterns.</p><p>The decision to employ log-transformation to achieve a more balanced residual distribution was based on the desire to normalize the residuals for accurate modeling. This technique’s advantage lies in its ability to mitigate the impact of extreme values, leading to a more robust modeling process. However, the disadvantage is that log-transformations might not always fully rectify skewed distributions and might not be suitable for all datasets.</p><p>The choice of autocorrelation and partial autocorrelation plots for time series analysis was driven by the need to identify temporal dependencies. These plots offer a visual representation of lagged correlations, aiding in understanding repeating patterns and informing modeling decisions. The advantage of these plots is their ability to highlight lag relationships. However, they might not be effective in capturing complex interactions involving multiple lags.</p><p>The application of the Dickey-Fuller test was crucial to assess the stationarity of the time series data. This test’s advantage is its capability to determine if a series is stationary or not, a fundamental aspect of time series analysis. However, it has limitations in identifying the specific causes of non-stationarity or the presence of structural breaks.</p><p>Utilizing the Variance Inflation Factor (VIF) for feature selection was motivated by the need to identify and address multicollinearity among predictor variables. According to Phudinawala and Jha (2022) they were able to “predict the demand for shared bikes using multiple linear regression. To understand which attributes need to be dropped we used RFE (Recursive Feature Elimination) and VIF (Variance Inflation Factor) to drop columns with high p-values and to check the multicollinearity respectively. Now the model is able to predict the future demand for shared bikes in a city” (p. 481). The advantage of this technique is that it quantifies the degree of collinearity, aiding in the selection of independent predictors. Yet, the disadvantage is that it might not fully capture complex relationships among variables beyond linear correlations.</p><p>The evaluation of the best forecast horizon through an iterative search was a strategy to optimize predictive accuracy. The advantage of this approach is that it identifies the horizon that minimizes prediction errors. However, the limitation is that it might not account for sudden shifts or changes in trends that could impact longer-term predictions.</p><p>In summary, the selected analysis techniques were driven by the objectives to uncover patterns, assess model assumptions, and optimize predictive accuracy. Each technique brings unique advantages while carrying specific limitations, underscoring the importance of a comprehensive and multi-faceted approach to address the complexities of time series data.</p><h4><strong>Model Development</strong></h4><p>Multiple regression analysis allows the expression of relationships between predictor variables and the response variable (Field, 2013). Ridge regression, also referred to as L2 regularization, is a linear regression approach aimed at addressing multicollinearity and potential overfitting in predictive modeling. It achieves this by incorporating a penalty term that is proportional to the square of the regression coefficients’ magnitudes into the linear regression cost function. This introduces a regularization parameter, lambda, which governs the extent of regularization applied.</p><p>The primary goal of ridge regression is to find a middle ground between effectively fitting the model to training data and restraining the coefficients from becoming overly large, thus minimizing the model’s susceptibility to variations in input features. By integrating this regularization component, ridge regression enhances the model’s performance on new data while ensuring a more stable solution in the presence of correlated or influential predictor variables.</p><p>R-squared, also recognized as the coefficient of determination, serves as a statistical measure employed to evaluate the goodness of fit of a regression model. It quantifies the proportion of variance in the dependent variable (the predicted outcome) that can be explained by the independent variables (predictors) incorporated within the model. Ranging from 0 to 1, a value of 0 implies that the model does not account for any variability, while a value of 1 signifies that the model completely accounts for all variability. Transitioning to model development, the initial phase involved the utilization of Ridge regression along with a grid search to determine the optimal regularization parameter, ‘alpha.’ The resultant model achieved an Accuracy Rate of 73.23%, accompanied by an R-squared value indicating that the model elucidates 82.60% of the data’s variability. Additionally, the MAPE and RMSE were measured at 26.77% and 892.82, respectively.</p><p>Continuing the analysis, among the coefficients derived from the model, one of notable significance is the ‘bike_counts_log’ coefficient, which stands at 0.501. This coefficient represents the transformed log of bicycle counts, and its positive value suggests a substantial positive relationship between the log-transformed bicycle counts and the number of Citi Bike trips. Essentially, as the log-transformed bicycle counts increase, there is a corresponding increase in the predicted number of Citi Bike trips. This insight highlights the influence of higher bicycle counts on the demand for Citi Bikes.</p><p>Additionally, the ‘pandemic_period’ coefficient holds importance with a value of 0.06. This positive coefficient indicates that during specific pandemic periods, there were increases in the predicted number of Citi Bike trips. This aligns with the understanding that the pandemic-induced changes influenced ridership patterns. By analyzing these coefficients, a deeper understanding of the factors impacting the model’s predictions is gained, contributing to a comprehensive grasp of their respective contributions.</p><p>Following that, the established model was utilized to predict future demand, and a graphical representation was generated to showcase the alignment between actual and predicted values. This visualization also incorporated confidence intervals, as illustrated in Figure 49.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LeKBfuXfCuoDLhCZkI0KUw.png" /><figcaption>49. Citi Bike Ridership: Actual vs. Predicted (Rolling 7 Days)</figcaption></figure><p>Much like the visualization depicted in Figure 43, the residuals exhibited a striking similarity to those of the initial ARIMA model. Interestingly, the Anderson-Darling test statistic for the residuals was notably smaller than that of the initial ARIMA model, registering at 106.29 in contrast to the previous value of 121.69. These comparisons are complemented by a summary of critical values at various levels of significance, as outlined in the table below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F1fpDHiwjGpxllo2_kILww.png" /><figcaption>50. Anderson-Darling Test Results</figcaption></figure><p>In a manner reminiscent of the approach taken in the time series analysis, a step-back methodology was implemented for the purpose of feature selection. As a result, the resulting model achieved an accuracy rate of 73.28%, relying on twelve predictors — slightly trailing the performance of the ARIMA model, which achieved 73.31% accuracy with 17 predictors. A noteworthy discrepancy emerged when considering the root-mean-square error (RMSE) values between the two models. The Ridge regression model displayed an RMSE of 893.52, distinct from the ARIMA model’s RMSE of 904.97. This new model was then harnessed for forecasting future demand, presenting a marginal 0.07% enhancement in accuracy when compared to the initial model. A visual depiction of the actual versus predicted values, accompanied by confidence intervals, can be observed in Figure 51. Once more, the residual plots of the second Ridge regression model closely mirrored those of the second ARIMA model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-s1QIluewbZhJOkPVRmpSg.png" /><figcaption>51. Citi Bike Ridership: Actual vs. Predicted (Rolling 7 Days)</figcaption></figure><p>The next step delved into testing various forecast horizons to assess their impact on predictive performance. One particularly compelling result is observed with a horizon of 6 months, where the R-squared value soared to an impressive 93.97% from 82.58%, signifying the model’s strong explanatory power. Furthermore, the MAPE of 17.66% and RMSE of 494.17 indicated a relatively low margin of prediction error, and the high Accuracy Rate of 82.34% underscored the model’s proficiency in making accurate predictions. Comparing this performance to the model discussed earlier, it is evident that this particular forecast horizon demonstrates marked improvement in R-squared, 13.80%, indicating a better fit of the model to the data, as well as notable enhancements in prediction accuracy, as evidenced by the lower MAPE and RMSE values . This finding highlights the significance of selecting an appropriate forecast horizon to optimize the model’s predictive capabilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QYUGUyISYopR7Y_t-tdyTw.png" /><figcaption>52. Citi Bike Ridership Actual vs. Predicted (6-Month Horizon, Rolling 24 Hours)</figcaption></figure><p>The plot in Figure 52 depicts just how closely the model’s predicted values match to the actual values. A broader view of the plot, illustrated in Figure 53, shows a rolling 7-day mean. Following the previous residual plot trends, the final model’s residual plots also closely resemble those of the final ARIMA model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*goaljJz7ZRRXPGHXSYWHxQ.png" /><figcaption>53. Citi Bike Ridership Actual vs. Predicted (6-Month Horizon, Rolling 7 Days)</figcaption></figure><p>Additionally, the Anderson-Darling test statistic, 60.02, was almost that of the final ARIMA model of 59.45. The table below shows the critical values at each significance level.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h1N4S6FoZN4sSfmNesgZCw.png" /><figcaption>54. Anderson-Darling Test Results</figcaption></figure><p><strong>Justification and advantages/disadvantages.<br></strong>The chosen tools for this analysis, including Ridge regression and time series modeling (ARIMA), were selected based on their suitability for addressing specific challenges in predictive modeling. Ridge regression, or L2 regularization, was employed to mitigate multicollinearity and overfitting, enhancing the model’s generalization performance by balancing model complexity and variance. This technique introduces a regularization parameter to the linear regression cost function, which prevents coefficients from becoming too large and provides stability in the presence of correlated predictors. Ridge regression’s advantage lies in its ability to improve the model’s robustness and prevent overfitting by controlling the impact of individual predictors. However, a potential disadvantage is that it assumes that all predictors are relevant, which might not be the case in every scenario.</p><p>On the other hand, the use of time series analysis with ARIMA models was appropriate due to the temporal nature of the data, helping to capture patterns and dependencies over time. ARIMA models are adept at handling sequential data, making them valuable for forecasting time-dependent phenomena. One advantage of ARIMA models is their capability to capture complex temporal patterns and trends in data. However, a limitation lies in their sensitivity to data quality, as they assume stationarity, which might require preprocessing steps to ensure accurate modeling.</p><p>The combined use of Ridge regression and ARIMA models in this analysis allowed for a comprehensive exploration of predictive modeling techniques, leveraging the strengths of each to address the unique challenges posed by the dataset. Ridge regression addressed multicollinearity and overfitting, while ARIMA models captured temporal dependencies. This integration of methodologies contributed to a robust analysis and enriched understanding of the dataset’s dynamics and predictive capabilities.</p><h3><strong>Data Summary and Implications</strong></h3><h4><strong>Implications of Data Analysis</strong></h4><p>The data analysis aimed to predict Citi Bike ridership demand using a multiple linear regression model based on market research data. The analysis involved a multi-faceted approach, utilizing techniques such as seasonal decomposition, log-transformation, autocorrelation and partial autocorrelation plots, Dickey-Fuller test, Ridge regression, and ARIMA modeling. These techniques collectively allowed for a comprehensive exploration of the dataset’s patterns, dependencies, and predictive capabilities.</p><p>The Ridge regression model was employed to address multicollinearity and overfitting, enhancing the model’s generalization performance by finding a balance between model complexity and variance. The results showed that the Ridge regression model achieved an accuracy rate of around 82.34%, and it provided valuable insights into the relationships between predictor variables and Citi Bike ridership demand. Notably, variables like transformed log of bicycle counts and pandemic periods exhibited significant positive relationships with the predicted number of Citi Bike trips.</p><p>The analysis also explored various forecast horizons, revealing that a forecast horizon of 6 months led to a substantial improvement in R-squared value, indicating strong explanatory power, as well as lower MAPE and RMSE values, signifying enhanced prediction accuracy.</p><h4><strong>Limitation of Analysis</strong></h4><p>One limitation of the analysis is that the Ridge regression model assumes that all predictors are relevant, which might not always hold true. It’s possible that certain predictor variables may have limited impact on Citi Bike ridership demand, and the model might benefit from more rigorous feature selection techniques.</p><h4><strong>Recommendation</strong></h4><p>Based on the results of the analysis, I recommend leveraging the insights gained from the Ridge regression model to inform decision-making and strategies related to Citi Bike operations and ridership management. The model’s ability to highlight significant predictor variables and their relationships with ridership demand can aid in optimizing resource allocation, marketing efforts, and infrastructure improvements.</p><h4><strong>Future Directions for Study</strong></h4><p><strong>Advanced Feature Selection:<br></strong>To address the limitation of assuming all predictors are relevant, future studies could employ more advanced feature selection techniques. Techniques like Recursive Feature Elimination (RFE) or LASSO regression could help identify the most influential predictors and improve the model’s accuracy.</p><p><strong>Dynamic Time Series Models:<br></strong>While ARIMA models are effective for capturing temporal patterns, they might not account for sudden shifts or changes in trends. Future studies could explore more advanced time series models, such as state-space models or machine learning-based approaches like LSTM networks, which can better capture complex temporal dependencies and adapt to changes in the dataset.</p><p>In summary, the data analysis provides valuable insights into predicting Citi Bike ridership demand using a Ridge regression model and exploring forecast horizons. While the Ridge regression model’s performance and insights are promising, addressing predictor relevance and exploring more advanced modeling techniques could further enhance the accuracy and robustness of predictions.</p><h3><strong>Sources</strong></h3><p><em>Bronx Times</em>. (2020, May 5). <em>First Citi Bike stations installed in the Bronx as part of continued expansion</em>. Retrieved from <a href="https://www.bxtimes.com/first-citi-bike-stations-installed-in-t%20he-bronx-as-part-ofcontinued-expansion/">https://www.bxtimes.com/first-citi-bike-stations-installed-in-t he-bronx-as-part-ofcontinued-expansion/</a></p><p><em>Citi Bike NYC</em>. (2023). <em>System Data</em>. Retrieved from <a href="https://www.citibikenyc.com/system-data">https://www.citibikenyc.com/system-data</a></p><p>(DOT), D. of T. (2023, August 25). Bicycle counts: NYC open data. <em>Bicycle Counts | NYC Open Data</em>. Retrieved from <a href="https://data.cityofnewyork.us/Transportation/Bicycle-Counts/uczf-%20rk3c">https://data.cityofnewyork.us/Transportation/Bicycle-Counts/uczf- rk3c</a></p><p>Faghih-Imani, A., Hampshire, R., Marla, L., &amp; Eluru, N. (2014). <em>An empirical analysis of bike sharing usage and rebalancing: Evidence from Barcelona and Seville</em>. <em>Transportation Research Part A: Policy and Practice</em>, 71, 326–344.</p><p>Field, A. (2013). <em>Discovering statistics using IBM SPSS statistics</em>. Sage. Gebhart, K., &amp; Noland, R. B. (2014). <em>The impact of weather conditions on bikeshare trips in Washington, DC</em>. Transportation, 41(6), 1205–1225.</p><p>Hyndman, R. J., &amp; Athanasopoulos, G. (2018). <em>Forecasting: principles and practice</em>. OTexts. <em>Investopedia</em>. (2020, October 5). <em>Timeline: How COVID-19 Took Over NYC</em>. Retrieved from <a href="https://www.investopedia.com/historical-timeline-of-covid-19-in-new-york-city-5071986">https://www.investopedia.com/historical-timeline-of-covid-19-in-new-york-city-5071986</a></p><p><em>Master’s in Data Science</em>. (n.d.). <em>How to Deal with Missing Data</em>. Retrieved from <a href="https://www.mastersindatascience.org/learning/how-to-deal-with-missing-data/">https://www.mastersindatascience.org/learning/how-to-deal-with-missing-data/</a></p><p><em>National Constitution Center</em>. (n.d.). <em>How Martin Luther King Jr.’s birthday became a holiday</em>. Retrieved from <a href="https://constitutioncenter.org/blog/how-martin-luther-king-jr-s-birthday-%20became-a-holiday-3">https://constitutioncenter.org/blog/how-martin-luther-king-jr-s-birthday- became-a-holiday-3</a></p><p><em>New York Times</em>. (n.d.). <em>Fodor’s Travel Guide to New York City</em>. Retrieved from <a href="https://archive.nytimes.com/www.nytimes.com/fodors/top/features/travel/destinations/uni%20tedstates/newyork/newyorkcity/fdrs_tips_111_2.html">https://archive.nytimes.com/www.nytimes.com/fodors/top/features/travel/destinations/uni tedstates/newyork/newyorkcity/fdrs_tips_111_2.html</a></p><p>Phudinawala, H., &amp; Jha, M. (2022). <em>Prediction of Demand for Shared Bikes using Multple Linear Regression Model</em>. <em>International Journal of Advanced Research in Science, Communication and Technology (IJARSCT)</em>, 2(1). Retrieved from <a href="https://ijarsct.co.in/Pap%20er2577.pdf">https://ijarsct.co.in/Pap er2577.pdf</a></p><p>Protected bike lane tracker. <em>Transportation Alternatives</em>. (2022, September 26). <a href="https://projects.transalt.org/bikelanes#:~:text=The%20NYC%20Streets%20Plan%20requi%20res,30%20required%20miles%20in%202022">https://projects.transalt.org/bikelanes#:~:text=The%20NYC%20Streets%20Plan%20requi res,30%20required%20miles%20in%202022</a></p><p>Ricci, M. (2019). <em>Bike Sharing: A Review of Evidence on Impacts and Processes of Implementation and Operation</em>. <em>Sustainability</em>, 11(12), 3314. Retrieved from <a href="https://doi.or g/10.3390/su11123314">https://doi.or g/10.3390/su11123314</a></p><p>Visual Crossing. (2023). <em>Weather Data</em>. Retrieved from <a href="https://www.visualcrossing.com/weather-%20data">https://www.visualcrossing.com/weather- data</a></p><p>Yang, H., Xie, K., Ozbay, K., Ma, Y., &amp; Wang, Z. (2018). <em>Use of Deep Learning to Predict Daily Usage of Bike Sharing Systems</em>. <em>Transportation Research Record</em>, 2672(36), 92–102. Retrieved from <a href="https://doi.org/10.1177/0361198118801354">https://doi.org/10.1177/0361198118801354</a></p><p>Zamir, K. R., Bondarenko, I., Nasri, A., Brodie, S., &amp; Lucas, K. (2019). <em>Comparative Analysis of User Behavior of Dock-Based vs. Dockless Bikeshare and Scootershare in Washington, D.C</em>. Retrieved from <a href="https://arxiv.org/pdf/1907.11526.pdf">https://arxiv.org/pdf/1907.11526.pdf</a></p><p>The data files, Jupyter notebooks, Python scripts, and project report can be found on <a href="https://github.com/jlopez873/Multiple_Linear_Regression_of_Bike_Ridership_Data">GitHub</a> along with <a href="http://javierlopezcastillo.com/">other projects</a> I’ve completed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c49fd3f211f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sentiment Analysis Using LSTM Networks: A Deep Dive into Textual Data]]></title>
            <link>https://javilopezcastillo.medium.com/sentiment-analysis-using-lstm-networks-a-deep-dive-into-textual-data-61cdd2e43dec?source=rss-221ab9e23bea------2</link>
            <guid isPermaLink="false">https://medium.com/p/61cdd2e43dec</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[sentiment-analysis]]></category>
            <category><![CDATA[data-preprocessing]]></category>
            <category><![CDATA[lstm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Javier Lopez Castillo]]></dc:creator>
            <pubDate>Thu, 08 Jun 2023 13:17:52 GMT</pubDate>
            <atom:updated>2023-06-08T13:17:52.270Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HYGC710v2eI5FPFq" /><figcaption>Photo by <a href="https://unsplash.com/@christinhumephoto?utm_source=medium&amp;utm_medium=referral">Christin Hume</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>In this article, we will take a comprehensive look at how to apply sentiment analysis using a specific type of Recurrent Neural Network (RNN) known as Long Short-Term Memory (LSTM). Sentiment analysis is a critical aspect of Natural Language Processing (NLP), allowing us to extract and quantify subjective information, such as emotions and attitudes, from written language. Let’s dive into this exciting field, discussing each step in detail, from data preprocessing to model evaluation.</em></p><h3>Data Collection and Preprocessing</h3><p>Our dataset comprised Amazon product reviews, given in a JSON format. Each review was accompanied by a corresponding rating on a scale of 1–5. For the purpose of sentiment analysis, we transformed these ratings into three sentiment categories: positive, neutral, and negative.</p><p>Here’s a snippet of our preprocessing:</p><pre># Load review data<br>reviews_df = pd.read_json(&#39;reviews.json&#39;, lines=True)<br><br># Define a function to convert ratings into sentiments<br>def convert_rating_to_sentiment(rating):<br>    if rating &lt; 3:<br>        return &#39;negative&#39;<br>    elif rating == 3:<br>        return &#39;neutral&#39;<br>    else:<br>        return &#39;positive&#39;<br><br># Apply the function to the &#39;overall&#39; column<br>reviews_df[&#39;sentiment&#39;] = reviews_df[&#39;overall&#39;].apply(convert_rating_to_sentiment)</pre><p>Now that we had our sentiment labels, we turned to the review texts. Preprocessing textual data for an LSTM network involved several steps: tokenization, sequence conversion, and sequence padding. Let’s go through each:</p><ol><li><strong>Tokenization</strong>: This process involves breaking down the review text into individual words or “tokens”. We used the Tokenizer class from Keras, which also takes care of converting the words to lower case and removing punctuation.</li><li><strong>Sequence conversion</strong>: Next, we converted the tokens into sequences of integers. Each unique word was assigned a unique integer. These sequences provide a format that our LSTM network can work with.</li><li><strong>Sequence padding</strong>: Because LSTM networks require input data with the same length, we used padding to ensure all sequences had the same length.</li><li><strong>Label encoding</strong>: Finally, we converted our sentiment labels (positive, neutral, negative) into numerical format, as models work better with numerical data.</li></ol><p>Here’s how we implemented these steps:</p><pre># Tokenization<br>tokenizer = Tokenizer(num_words=VOCAB_SIZE)<br>tokenizer.fit_on_texts(clean_reviews)<br><br># Convert tokens to sequences<br>sequences = tokenizer.texts_to_sequences(clean_reviews)<br><br># Padding sequences<br>X = pad_sequences(sequences, maxlen=MAX_SEQUENCE_LENGTH)<br><br># Converting labels to numerical format<br>le = LabelEncoder()<br>y = le.fit_transform(sentiments)<br>y = to_categorical(y)</pre><h3>Model Building: LSTM Network</h3><p>After preprocessing our data, we moved on to constructing the LSTM network. The model was created using Keras’ Sequential API, indicating that our model would be built layer by layer in a sequential manner.</p><p>Here’s the architecture of our LSTM network:</p><ol><li>Embedding layer: This layer transformed our integer sequences (representing words) into dense vectors of fixed size. The Embedding layer is crucial for handling categorical data, particularly textual data.</li><li>LSTM layers: Next, we added two LSTM layers with 128 units each. LSTM layers are effective in processing sequences (like text), as they can capture the temporal dependencies between elements in the sequence. We also added dropout to these layers to avoid overfitting</li><li>Dense layers: After the LSTM layers, we included two dense (fully connected) layers. The first had 64 units, while the last one, serving as the output layer, had three units (corresponding to our three sentiment classes). We used the ‘softmax’ activation function in our output layer to get probabilities for each class.</li></ol><pre># Define the model<br>model = Sequential([<br>    Embedding(input_dim=len(word_index), output_dim=200, input_length=max_seq),<br>    LSTM(128, return_sequences=True),<br>    Dropout(0.5),<br>    LSTM(128),<br>    Dense(64, activation=&#39;relu&#39;, <br>          kernel_regularizer=regularizers.l2(0.01), <br>          activity_regularizer=regularizers.l1(0.01)),<br>    Dense(3, activation=&#39;softmax&#39;)  # number of classes (sentiment categories)<br>])<br><br># Compile the model<br>model.compile(loss=&#39;categorical_crossentropy&#39;, optimizer=&#39;adam&#39;, metrics=[&#39;accuracy&#39;])</pre><h3>Model Training and Evaluation</h3><p>We then trained our model on our preprocessed reviews and sentiments, using a batch size of 32 and running for 100 epochs. We also included early stopping in our training to prevent overfitting.</p><pre># Create early stopping object<br>early_stopping = EarlyStopping(monitor=&#39;val_loss&#39;, min_delta=0, patience=3, verbose=1, mode=&#39;auto&#39;)<br><br># Train the model<br>history = model.fit(X_train, y_train, epochs=100, batch_size=32, validation_data=(X_val, y_val), callbacks=[early_stopping])</pre><p>Model evaluation involved computing various performance metrics, including accuracy, precision, recall, and F1 score. We also generated a confusion matrix for a more intuitive understanding of the model’s performance.</p><pre># Evaluate model on test data<br>score = model.evaluate(X_test, y_test, verbose=1)<br><br># Calculate precision, recall, F1 score<br>y_pred = model.predict(X_test)<br>y_pred = np.argmax(y_pred, axis=1)<br>y_test_argmax = np.argmax(y_test, axis=1)<br><br>print(&#39;Precision:&#39;, precision_score(y_test_argmax, y_pred, average=&#39;weighted&#39;))<br>print(&#39;Recall:&#39;, recall_score(y_test_argmax, y_pred, average=&#39;weighted&#39;))<br>print(&#39;F1 score:&#39;, f1_score(y_test_argmax, y_pred, average=&#39;weighted&#39;))</pre><h3>Conclusions and Future Work</h3><p>Using an LSTM-based neural network, we achieved impressive results in predicting the sentiment of Amazon product reviews. This method offers a powerful tool for understanding customer attitudes and guiding business decisions. However, this is only a single step in the expansive world of NLP. Future work might involve exploring different neural network architectures, using pre-trained embeddings, or applying this model to other NLP tasks.</p><p>Stay tuned for more exciting adventures in NLP and machine learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61cdd2e43dec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Time Series Forecasting: A Case Study on Telecom Revenue]]></title>
            <link>https://javilopezcastillo.medium.com/time-series-forecasting-a-case-study-on-telecom-revenue-5878943e01d1?source=rss-221ab9e23bea------2</link>
            <guid isPermaLink="false">https://medium.com/p/5878943e01d1</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[telecommunication]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[arima]]></category>
            <dc:creator><![CDATA[Javier Lopez Castillo]]></dc:creator>
            <pubDate>Wed, 07 Jun 2023 15:40:52 GMT</pubDate>
            <atom:updated>2023-06-07T15:40:52.898Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ucrQD5-KYzKMn2VA" /><figcaption>Photo by <a href="https://unsplash.com/@insungyoon?utm_source=medium&amp;utm_medium=referral">insung yoon</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>Understanding revenue trends and accurately predicting future revenues are crucial aspects of running a successful business. This article will walk you through a case study of revenue forecasting for a telecommunications company using Time Series analysis and the ARIMA (Autoregressive Integrated Moving Average) model.</em></p><h3>The Challenge</h3><p>The telecommunications company, Teleco, had been collecting daily revenue data for the past two years. They approached us with a challenge: Could we analyze their past revenue data and predict their future revenues? Our team decided to take up this challenge and came up with an approach using time series forecasting.</p><h3>Exploratory Data Analysis</h3><p>Our first step was to understand the data. We used Python’s powerful data manipulation library, Pandas, for this.</p><pre>import pandas as pd</pre><pre># Load the data<br>df = pd.read_csv(&#39;teleco_time_series.csv&#39;)</pre><pre># Take a quick look at the data<br>print(df.head())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/185/1*xAZljpp-o40uSHsdNgFoiw.png" /></figure><p>We then analyzed the trends, seasonality, and autocorrelation in the data. One key discovery was that the data did not show a clear seasonal pattern, which would influence our choice of model later on. Our initial plot included the daily revenue trend over 2 years.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*USHVaHJlNqEo8kUZ43fJIg.png" /></figure><p>Then we broke the data down into seasonal sub-series to spot any patterns over a quarterly, monthly, and weekly window.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*55H2dusZp1P7RjaPxUAkAg.png" /></figure><p>Next, we decomposed the data to visualize the trend, seasonal component, and residuals separately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gWAm5wMNIKCijybkovBm6w.png" /></figure><pre>import matplotlib.pyplot as plt<br>from pandas.plotting import autocorrelation_plot</pre><pre># Plot autocorrelation<br>autocorrelation_plot(df[&#39;Revenue&#39;])<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*VDby3402WTCqs6XpX6DF5A.png" /></figure><p>Our last exploratory step was to visualize the spectral density in our data on a periodogram. The line graph showed no significant local maximums, meaning there is no dominant frequency component. However, the convex shape of the trend indicates that the power at different frequencies increases or decreases smoothly as you move across the frequency spectrum. It suggests that there might be a gradual trend or a slow-changing pattern in the time series rather than sharp, distinct periodicity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*ZYss_bXFquPfo1u5-ozsMw.png" /></figure><h3>Data Cleaning and Preprocessing</h3><p>Before applying any forecasting model, we had to make sure our data was clean and ready for analysis. This involved checking for any missing or erroneous data and handling them appropriately.</p><pre># Check for missing data<br>print(df.isnull().sum())</pre><p>After finding no missing data, we performed the Augment Dickey-Fuller (ADF) test to check for stationarity.</p><pre># Define Augmented Dickey-Fuller (ADF) test function as per statsmodels<br>def adf_test(timeseries):<br>    print(&quot;Results of Dickey-Fuller Test:&quot;)<br>    dftest = adfuller(timeseries, autolag=&quot;AIC&quot;)<br>    dfoutput = pd.Series(<br>        dftest[0:4],<br>        index=[<br>            &quot;Test Statistic&quot;,<br>            &quot;p-value&quot;,<br>            &quot;#Lags Used&quot;,<br>            &quot;Number of Observations Used&quot;,<br>        ],<br>    )<br>    for key, value in dftest[4].items():<br>        dfoutput[&quot;Critical Value (%s)&quot; % key] = value<br>    print(dfoutput)</pre><p>The results of the ADF test, showed that the data was not stationary as the p-value is well above the established 0.05 confidence value.</p><pre>Results of Dickey-Fuller Test:<br>Test Statistic                  -1.924612<br>p-value                          0.320573<br>#Lags Used                       1.000000<br>Number of Observations Used    729.000000<br>Critical Value (1%)             -3.439352<br>Critical Value (5%)             -2.865513<br>Critical Value (10%)            -2.568886<br>dtype: float64</pre><p>We visualized the rolling mean and standard deviation over a 12-day window, which aligned with the ADF test results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*Od65sTL704zSMm7m__jVJQ.png" /></figure><p>Next, we transformed the data to ensure it was stationary, a necessary condition for applying ARIMA models.</p><pre># Difference the data<br>diff = np.diff(ts)<br><br># Create a pandas series object from the differenced time-series data<br>diff_ts = pd.Series(diff, index=ts.index[:-1])</pre><p>We then tested the differenced data to ensure it was stationary, which we saw was the case since the test statistic was significantly smaller than the critical values and the p-value was significantly smaller than the 0.05 confidence threshold.</p><pre>Results of Dickey-Fuller Test:<br>Test Statistic                 -44.874527<br>p-value                          0.000000<br>#Lags Used                       0.000000<br>Number of Observations Used    729.000000<br>Critical Value (1%)             -3.439352<br>Critical Value (5%)             -2.865513<br>Critical Value (10%)            -2.568886<br>dtype: float64</pre><p>The visualization of the differenced data was much flatter than our previous visualization, a clear sign of stationarity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*zVGRSgJnArTXpedAlZt0xQ.png" /></figure><h3>Forecasting Model: ARIMA</h3><p>ARIMA models are a popular choice for time series forecasting. ARIMA, which stands for Autoregressive Integrated Moving Average, is a class of models that captures a suite of different standard temporal structures in time series data.</p><p>Our chosen model was an ARIMA(1, 1, 0) model, as determined by the autocorrelation and partial autocorrelation plots.</p><pre>from statsmodels.tsa.arima.model import ARIMA<br><br># Create the ARIMA model with the identified order<br>model = ARIMA(train.reset_index(drop=True), order=(1,1,0))<br>model = model.fit()<br>model.summary()</pre><p>We trained the model on our training data and then used it to make forecasts.</p><h3>Model Evaluation and Forecasting</h3><p>We evaluated the model using the test data. The evaluation metric used was the Root Mean Squared Error (RMSE), a commonly used error metric for evaluating the performance of forecasting models.</p><pre># Predict the last month<br>fcast = model.get_forecast(steps=len(test))<br>fcast_vals = fcast.predicted_mean<br>ci = fcast.conf_int()<br><br># Calculate the root mean squared error<br>rmse = np.sqrt(mse(fcast_vals, test))<br>print(f&#39;Root Mean Squared Error (RMSE): {rmse}&#39;)</pre><p>Our model achieved an RMSE of 1.8317, suggesting a reasonably accurate forecasting. We then visualized our model’s forecast and the test data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gQs6U2HEdRovnX6Kx37G4Q.png" /></figure><p>Once we were satisfied with the model’s performance, we used it to forecast the revenue for the next 30 days.</p><pre># Forecast the next 30 days with confidence intervals<br>fcast2 = model.get_forecast(steps=30)<br>fcast_vals2 = fcast2.predicted_mean<br>ci2 = fcast2.conf_int()</pre><p>The forecast provided us with the predicted mean revenue and the associated confidence intervals, which gave us an understanding of the possible range of the future values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DMk6c5Le8cXZl1dmwAY6Nw.png" /></figure><p>We then took a more zoomed-out view of the forecast.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*d2PaUtzKZm3nBPTxz7qRpw.png" /></figure><h3>Results and Recommendations</h3><p>The ARIMA model provided a robust forecast of the Teleco’s revenue for the next month. Based on our forecast, Teleco can expect to see an average increase in revenue of 46.82% from January Year 2 to January Year 3, a $157.69 Million increase in revenue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*maJWsEi1eguVPV2TJvzB7Q.png" /></figure><p>We recommended Teleco to use this model to generate forecasts for future time periods. However, as time progresses and new data becomes available, it is crucial to periodically re-evaluate the model’s performance. Also, while the current ARIMA(1, 1, 0) model appears to perform well, it’s worth exploring other modeling approaches to potentially improve the accuracy of the forecasts.</p><h3>Conclusion</h3><p>This project showcases how time series analysis and forecasting models like ARIMA can be used to predict future revenue, aiding in decision-making and planning. As businesses collect more data over time, the value of these techniques will only increase. The code used throughout this project serves as a solid foundation for those who want to try their hands at time series forecasting.</p><p>The data files, Jupyter notebooks, Python scripts, and project report can be found on <a href="https://github.com/jlopez873/Telecom_Revenue_Time_Series_Forecasting">GitHub</a> along with <a href="http://javierlopezcastillo.com/">other projects</a> I’ve completed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5878943e01d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Telecom Association Rules and Lift Analysis: A Deep Dive Into Transaction Data]]></title>
            <link>https://javilopezcastillo.medium.com/telecom-association-rules-and-lift-analysis-a-deep-dive-into-transaction-data-8f7ed815d71c?source=rss-221ab9e23bea------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f7ed815d71c</guid>
            <category><![CDATA[market-basket-analysis]]></category>
            <category><![CDATA[association-rule]]></category>
            <category><![CDATA[customer-behavior]]></category>
            <category><![CDATA[telecom]]></category>
            <category><![CDATA[lift-analysis]]></category>
            <dc:creator><![CDATA[Javier Lopez Castillo]]></dc:creator>
            <pubDate>Fri, 12 May 2023 19:57:38 GMT</pubDate>
            <atom:updated>2023-05-12T19:57:38.251Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kDki3a1_JUVRGIED" /><figcaption>Photo by <a href="https://unsplash.com/@boxedwater?utm_source=medium&amp;utm_medium=referral">Boxed Water Is Better</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>In the dynamic world of e-commerce, understanding customer behavior and shopping patterns is a critical aspect of enhancing customer engagement and increasing revenue. This study aims to analyze telecom e-commerce transactions using MLXtend’s Apriori and Association Rules algorithms to identify item associations and frequent itemsets that customers often purchase together.</p><h3>Market Basket Analysis</h3><p>Market Basket Analysis (MBA) is a powerful data mining technique used to uncover associations between items based on transaction data. This method is employed to identify frequent itemsets and create association rules that show which items are usually purchased together. The goal is to discover meaningful relationships and patterns between items that can be harnessed to improve marketing strategies, cross-selling, and upselling opportunities.</p><p>For instance, if a customer purchases a smartphone, they might also be interested in buying a phone case, screen protector, or headphones. Recognizing these patterns allows telecom companies to make targeted recommendations, potentially increasing the average transaction value.</p><h3>Assumption</h3><p>A fundamental assumption of market basket analysis is that each transaction is independent of other transactions. This means each transaction is unique and not influenced by any purchases in other transactions. Each transaction within the dataset should contain information independent of data from other transactions within the dataset.</p><h3>Data Preparation and Analysis</h3><p>The Apriori algorithm, a popular method used for market basket analysis, was executed on the telecom transaction dataset. This algorithm identifies frequent itemsets within the dataset, which are then used to generate association rules.</p><h3>Interpreting the Metrics</h3><p>The strength and significance of the association rules are determined by three key metrics: support, confidence, and lift.</p><ol><li>Support measures the frequency with which a particular itemset occurs within the dataset. The higher the support value, the more frequent the itemset is observed in the dataset.</li><li>Confidence measures the likelihood that a consequent item is purchased with the antecedent item. The higher the confidence value, the stronger the association between the items in the rule.</li><li>Lift is the ratio of the observed confidence to the expected confidence if the antecedent and consequent items were independent. A lift value greater than one indicates a positive association between the items in the rule, meaning the items are more likely to be purchased together. Conversely, a lift value less than one indicates a negative association.</li></ol><h3>Significance of Results and Practical Implications</h3><p>Our analysis revealed that the ‘Dust-Off Compressed Gas 2 pack’ was the most frequently purchased item with ‘VIVO Dual LCD Monitor Desk Mount,’ ‘HP 61 ink,’ and ‘Apple Pencil.’ These findings suggest that the ‘Dust-Off Compressed Gas 2 pack’ is a popular add-on among all of Teleco’s items.</p><p>This has several practical implications. First, Teleco could adjust their product placement strategy to ensure the add-on does not get overlooked by customers. Second, they could manage their inventory to ensure that the ‘Dust-Off Compressed Gas 2 pack’ is always available. Finally, Teleco could create product bundles offering a discount when customers purchase both items together, thereby potentially increasing sales.</p><h3>Recommendations</h3><p>Based on these findings, it is recommended that Teleco add a message in the user’s cart before checkout offering the ‘Dust-Off Compressed Gas 2 pack’ whenever any of the three items appear in the cart. This would help increase the average transaction value by promoting items that customers are likely to purchase together based on historical transaction data. It’s also recommended that Teleco revise their inventory planning to ensure they always have the ‘Dust-Off Compressed Gas 2 pack’ available, to avoid missing out on cross-selling opportunities.</p><h3>Incorporating AI and ML for Enhanced Market Basket Analysis</h3><p>As the e-commerce landscape becomes increasingly competitive, it is crucial for companies like Teleco to leverage advanced techniques such as AI and machine learning to understand and predict customer behavior. This study demonstrates the use of machine learning techniques, specifically the Apriori algorithm and Association Rules, for Market Basket Analysis.</p><p>These techniques provide a data-driven approach to uncovering patterns in customer transactions, allowing businesses to tailor their marketing strategies more effectively. This could involve personalized product recommendations, promotional offers targeting frequently bought together items, or even refining their product inventory based on the popularity of specific items.</p><h3>Limitations and Future Research</h3><p>While this study provides valuable insights into customer purchasing behavior, it’s important to note that Market Basket Analysis does have limitations. The primary limitation is the assumption that all transactions are independent of each other. This may not always be the case as customer purchasing behavior can be influenced by a variety of external factors such as seasonal trends, promotional campaigns, or changes in product availability.</p><p>Additionally, while the Apriori algorithm is effective at identifying frequent itemsets, it may not perform as well with large, sparse datasets due to its computational complexity. Future research could explore alternative algorithms or methods that can efficiently handle large datasets while still providing meaningful insights.</p><h3>Conclusion</h3><p>Market Basket Analysis is a powerful tool for e-commerce businesses to uncover associations between products, allowing them to leverage these insights for improved marketing strategies, cross-selling, and upselling opportunities. This study demonstrated how Teleco can use this approach to identify popular add-on items and implement strategies to promote these items effectively.</p><p>The data-driven insights gleaned from this analysis can guide Teleco’s decision-making in various areas, from marketing and sales to inventory management. By implementing the recommended strategies, Teleco has the potential to enhance customer engagement, increase average transaction value, and ultimately boost their bottom line.</p><p>As technology continues to evolve, incorporating advanced data analysis techniques like Market Basket Analysis will be crucial for businesses looking to stay competitive in the rapidly evolving e-commerce landscape.</p><p>The data files, Jupyter notebooks, Python scripts, and project report can be found on <a href="https://github.com/jlopez873/Teleco_Association_Rules_and_Lift_Analysis">GitHub</a> along with <a href="http://javierlopezcastillo.com/">other projects</a> I’ve completed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f7ed815d71c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Telecom Churn Analysis Using Dimensionality Reduction Methods]]></title>
            <link>https://javilopezcastillo.medium.com/telecom-churn-analysis-using-dimensionality-reduction-methods-87ddd15972a5?source=rss-221ab9e23bea------2</link>
            <guid isPermaLink="false">https://medium.com/p/87ddd15972a5</guid>
            <category><![CDATA[churn-analysis]]></category>
            <category><![CDATA[telecom]]></category>
            <category><![CDATA[apc]]></category>
            <category><![CDATA[customer-behavior]]></category>
            <category><![CDATA[dimensionality-reduction]]></category>
            <dc:creator><![CDATA[Javier Lopez Castillo]]></dc:creator>
            <pubDate>Fri, 12 May 2023 19:47:01 GMT</pubDate>
            <atom:updated>2023-05-12T19:47:01.817Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*twrdJo1BrMlD5iQU" /><figcaption>Photo by <a href="https://unsplash.com/es/@leofoureaux?utm_source=medium&amp;utm_medium=referral">Leo Foureaux</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Abstract</h3><p>In the highly competitive telecom sector, understanding customer behavior and preferences is vital to reducing customer churn. This study utilizes Principal Component Analysis (PCA) to reduce customer data dimensionality and retain crucial information. The goal is to identify key factors contributing to customer churn, which could assist in improving targeted marketing campaigns and strategies.</p><h3>Introduction</h3><p>The telecom industry is characterized by high customer churn rates, where customers switch from one service provider to another in search of better services or lower prices. Understanding the factors contributing to this churn is crucial for telecom providers to tailor their services and retain their customers. This study aims to use PCA to reduce customer data dimensionality, identify the key factors contributing to customer churn, and ultimately improve targeted marketing campaigns and strategies.</p><h3>Methodology</h3><p>PCA is a statistical procedure that transforms the original variables in a dataset into a new set of uncorrelated variables called principal components. These new variables capture the maximum variance in the data while reducing the number of dimensions. PCA assumes that the most significant information in a dataset is captured by the principal components with the highest variance. However, this assumption may not always be accurate, especially if the components with low variance contain important information for the specific context being analyzed.</p><p>The first step in PCA is calculating the covariance matrix of the data, expressing the relationship between each variable in the dataset. The algorithm then computes the eigenvectors and eigenvalues of the covariance matrix, the directions of the principal components, and the magnitude of the variance captured by each principal component, respectively.</p><p>The number of principal components specified to the PCA algorithm can be determined using the elbow method on a scree plot or the Kaiser criterion. When transforming the original data to reduce dimensionality, PCA projects it onto the selected principal components.</p><h3>Data Preparation</h3><p>The dataset used in this study includes various variables such as Income, Tenure, Bandwidth_GB_Year, and MonthlyCharge. The variables were standardized before being fed into the PCA algorithm.</p><h3>Results</h3><p>The PCA algorithm produced a Principal Component Matrix that represents the correlation between the continuous variables and principal components. Each value in the matrix represents the loading of the variable on the respective principal components.</p><p>The scree plot showed the percentage of explained variance for each principal component. Based on the Kaiser Rule, the first two principal components, which had an explained variance of 1.99 and 1.02 respectively, were kept.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UU5xnxhr_hpAvQjVVrtAEQ.png" /></figure><p>The three principal components selected captured a total variance of 60.35%. The PCA results were plotted to visualize two distinct clusters within the dataset. The biplot showed how the original features contributed to the shape of the data by representing their relationships with the selected principal components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tsto3XiVzyR36iEAp_E3TA.png" /></figure><h3>Conclusion</h3><p>This study aimed to reduce the dimensionality of customer data while retaining the most important information, to better understand the key factors that contribute to customer behavior and preferences. By transforming our data using PC1 and PC2, we were able to reduce the dimensionality of our dataset while still capturing 60.35% of the total variance. These insights will be valuable for telecom companies seeking to understand their customer behavior and preferences better and could lead to more effective marketing strategies and reduced customer churn in the future.</p><p>However, it’s worth noting that PCA assumes linear relationships between variables, which may not always hold true. Future research could consider using non-linear dimensionality reduction techniques to complement the findings from PCA.</p><p>The data files, Jupyter notebooks, Python scripts, and project report can be found on <a href="https://github.com/jlopez873/Telecom_Churn_Analysis_Dimensionality_Reduction_Methods_PCA">GitHub</a> along with <a href="http://javierlopezcastillo.com/">other projects</a> I’ve completed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87ddd15972a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Telecom Churn Analysis: Using Clustering Techniques for Customer Segmentation]]></title>
            <link>https://javilopezcastillo.medium.com/telecom-churn-analysis-using-clustering-techniques-for-customer-segmentation-4cdb7318f672?source=rss-221ab9e23bea------2</link>
            <guid isPermaLink="false">https://medium.com/p/4cdb7318f672</guid>
            <category><![CDATA[k-means-clustering]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[telecom]]></category>
            <category><![CDATA[customer-segmentation]]></category>
            <category><![CDATA[churn-analysis]]></category>
            <dc:creator><![CDATA[Javier Lopez Castillo]]></dc:creator>
            <pubDate>Fri, 12 May 2023 19:35:31 GMT</pubDate>
            <atom:updated>2023-05-12T19:35:31.896Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qtWZ43IVfwQfXsu5" /><figcaption>Photo by <a href="https://unsplash.com/es/@gferla?utm_source=medium&amp;utm_medium=referral">Guillermo Ferla</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the highly competitive landscape of the telecommunications industry, understanding customer behavior is a key aspect of maintaining a competitive edge. A well-conducted customer segmentation allows companies to tailor their services and marketing efforts to different customer groups, leading to improved customer satisfaction and reduced churn. In this article, we explore the use of k-means clustering, a popular machine learning algorithm, to segment a telecommunications company’s customer base.</p><h3>Research Question</h3><p>The primary question guiding this analysis is: “What are the distinct customer segments within the telecommunications company’s customer base?” The objective is to better understand the similarities and differences between various groups of customers, enabling more targeted and effective business strategies.</p><h3>Technique Justification</h3><p>K-means clustering was selected for this analysis due to its simplicity and efficacy in segmenting datasets. It works by grouping data points into specified clusters based on their similarity. The algorithm begins by randomly assigning data points to serve as the initial centers (centroids) of the clusters. Each data point is then assigned to the nearest centroid, and the centroids are recalculated based on the new assignments. This process continues iteratively until the centroids stabilize.</p><p>The primary assumption behind k-means clustering is that all variables have an equal variance, as the algorithm uses Euclidean distance to measure the proximity between data points. To satisfy this assumption, data was normalized using Sklearn’s StandardScaler function, ensuring all variables were measured on the same scale.</p><h3>Data Preparation</h3><p>Before feeding the data into the algorithm, categorical variables were removed, as k-means clustering only takes in continuous variables. The following continuous variables were included in the analysis:</p><ul><li>Income</li><li>Outage_sec_perweek</li><li>Tenure</li><li>MonthlyCharge</li><li>Bandwidth_GB_Year</li></ul><p>Data was first imported into a Pandas dataframe. Columns with continuous variables were isolated and location-based longitude and latitude columns were dropped. The data was then scaled using the StandardScaler function and saved as a clean dataset for further analysis.</p><h3>Analysis and Results</h3><p>The analysis involved testing multiple k-means clustering models with different k values (representing the number of clusters). Inertia scores (measuring the distance of each data point to its assigned centroid) for each model were plotted against the number of clusters, using the Elbow Method to visually determine the optimal k value. The final model’s accuracy was evaluated using the silhouette score, a measure of how well each data point fits within its assigned cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sah1ohOTN6EdGBOChLhEBw.png" /></figure><p>The analysis resulted in two distinct customer segments. The two clusters had similar centroids for Income, Weekly Outage Duration, and Monthly Charge, but significantly differed in Tenure and Annual Bandwidth Usage. Cluster 1 had a lower average tenure and bandwidth usage than Cluster 2. This implies that customers in Cluster 1 tend to churn before completing a 12-month tenure with the organization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ExSdaM-5qdA0TepVLRd5PA.png" /></figure><h3>Implications and Recommendations</h3><p>The results of this analysis have several important implications for the telecom company. Firstly, the company can use this customer segmentation to allocate resources more effectively and design marketing campaigns tailored to the specific characteristics of each cluster. Secondly, the company can focus on customer retention efforts, particularly for customers in Cluster 1, who have a shorter tenure.</p><p>Based on the centroids of each cluster, it is recommended that the telecom company focus on extending the tenure of customers in Cluster 1 through targeted marketing campaigns and incentives. For customers in Cluster 2, who have a longer average tenure, the company should ensure they feel valued through rewards programs or targeted discounts on additional services.</p><h3>Limitations and Future Directions</h3><p>A key limitation of this analysis is the subjectivity involved in selecting the value of k. Different analysts may arrive at different conclusions based on their interpretation of the Elbow Method or silhouette score. Furthermore, the k-means clustering technique is sensitive to outliers and the initial random placement of centroids. To overcome these limitations, advanced clustering techniques such as DBSCAN or hierarchical clustering may be used in future analyses.</p><p>Another limitation is the exclusion of categorical variables from the analysis, as k-means clustering only works with continuous variables. Some of these categorical variables, such as the type of contract or the customer’s preferred method of payment, could provide additional insights into customer behavior. Future research could explore the use of clustering algorithms that can handle both categorical and continuous variables, like k-prototypes or k-modes clustering.</p><p>Furthermore, this study only considered five variables in the analysis. The inclusion of more variables could provide a more comprehensive view of customer behavior. Future research could also consider the use of dimensionality reduction techniques, such as Principal Component Analysis (PCA), to condense a large number of variables into fewer, more manageable dimensions.</p><p>Lastly, while this study provides valuable insights into the current state of the customer base, it does not consider changes over time. Future research could explore the use of time-series clustering techniques to track changes in customer behavior over time, providing more dynamic and actionable insights.</p><h3>Conclusion</h3><p>In conclusion, this study demonstrates the power of k-means clustering in segmenting a telecom company’s customer base into distinct groups. It provides actionable insights that can guide the company’s marketing and customer retention strategies. While there are limitations to this approach, the analysis serves as a foundation for further research into more advanced and comprehensive customer segmentation techniques. The goal remains the same — to understand our customers better and provide services that meet their unique needs and preferences.</p><p>The data files, Jupyter notebooks, Python scripts, and project report can be found on <a href="https://github.com/jlopez873/Telecom_Churn_Analysis_Using_Clustering_Techniques_Kmeans">GitHub</a> along with <a href="http://javierlopezcastillo.com/">other projects</a> I’ve completed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4cdb7318f672" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leveraging Data Analysis for Better Healthcare Management: Installation and Analysis of a…]]></title>
            <link>https://javilopezcastillo.medium.com/leveraging-data-analysis-for-better-healthcare-management-installation-and-analysis-of-a-8427e1ac5759?source=rss-221ab9e23bea------2</link>
            <guid isPermaLink="false">https://medium.com/p/8427e1ac5759</guid>
            <category><![CDATA[healthcare-analytics]]></category>
            <category><![CDATA[tableau-public]]></category>
            <category><![CDATA[dashboard]]></category>
            <category><![CDATA[pgadmin-4]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Javier Lopez Castillo]]></dc:creator>
            <pubDate>Fri, 12 May 2023 19:22:34 GMT</pubDate>
            <atom:updated>2023-05-12T19:22:34.037Z</atom:updated>
            <content:encoded><![CDATA[<h3>Leveraging Data Analysis for Better Healthcare Management: Installation and Analysis of a Compliance Dashboard</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nf_ohq9BLIiFhFsaKZLoDw.png" /></figure><h3>Introduction</h3><p>In the data-driven world of healthcare, key decision-makers rely heavily on data analysis tools for insights and decision-making. One of these tools, a compliance dashboard, can help hospital administrators track metrics, patient demographics, and health trends. It enables them to develop new initiatives aimed at improving patient outcomes based on observed patterns. As such, this article provides detailed instructions on how to install and utilize a compliance dashboard using pgAdmin 4 and <a href="https://public.tableau.com/app/profile/javier.lopez.castillo">Tableau Public</a>.</p><p>To view the Tableau dashboard <a href="https://public.tableau.com/app/profile/javier.lopez.castillo/viz/ComplianceDashboard_16830611211120/COMPLIANCEDASHBOARD">click here</a>.</p><h3>Installation and data preprocessing</h3><p>Before proceeding, ensure that you have a fully functioning installation of pgAdmin 4 and Tableau Public on your Mac OS. If not, you can download and install pgAdmin 4 <a href="https://www.pgadmin.org/download/pgadmin-4-macos/">here</a> and Tableau Public <a href="https://www.tableau.com/products/public/download">here</a>. Be aware that you may need to create an account for Tableau Public.</p><p>To begin, you will need to preprocess your data using PostgreSQL. After opening PostgreSQL on your desktop, expand Servers in the Object Explorer. Here, you’ll create a new database named ‘medical’ by right-clicking Databases &gt; Create &gt; Database on the Object Explorer container.</p><p>Afterward, select the ‘medical’ database and choose the Query Tool. Use the Open File folder button to select the CreateTables.sql file and click Open. Execute the script by clicking the Execute/Refresh play button.</p><p>Next, expand Schemas and Tables. Import the medical_clean.csv file to the ‘medical’ table and the FY_2023_HRRP.csv file to the ‘readmissions’ table. To clean the data, open the CleanData.sql file and execute it. Finally, save the resulting table onto a CSV file named ‘readmissions.csv’.</p><h3>Dashboard Installation</h3><p>The next phase involves installing and viewing the compliance dashboard. Open Tableau Public and click File &gt; Open on the Menu bar. Select the Compliance Dashboard.twbx file and click Open. Finally, click on the ComplianceDashboard tab to view the dashboard.</p><h3>Troubleshooting</h3><p>In case the dashboard does not populate with data, there are troubleshooting steps to follow. Click on the Data Source tab and then click Add &gt; Text File beside Connections on the left sidebar. Select the readmissions.csv file and click Open. Drag the readmissions.csv table from the left sidebar onto the space in the center of the screen.</p><h3>Data Analysis and Decision Making</h3><p>Once the dashboard is up and running, you can use it to inform stakeholders of hospital metrics, patient demographics, and health trends. The data can be filtered by geographic location, patient demographics, and patient health data, allowing for a more in-depth investigation into specific States and Counties.</p><p>The analysis can reveal critical insights like the age groups with the highest readmission rates or how readmission rates vary across regions or among different genders. These findings can support executive decision-making by prompting Regional VPs to develop action plans to ensure that all patients receive the same level of care across all regions.</p><h3>Limitations and Future Directions</h3><p>While this dashboard provides critical insights, there are some limitations to be aware of. The data set does not specify dates, making it difficult to assess performance trends over time. Additionally, the reason for patient readmission, a key factor impacting readmission tracking, is not included.</p><p>Despite these limitations, this compliance dashboard serves as a robust tool for healthcare administrators to track and improve patient outcomes. As healthcare data continues to grow in volume and complexity, tools like these will become increasingly indispensable in managing healthcare operations effectively and efficiently.</p><h3>Sources</h3><p><a href="https://data.cms.gov/provider-data/dataset/9n3s-kdb3">Center for Medicare &amp; Medicaid Services</a></p><p>The data files, Jupyter notebooks, and project report can be found on <a href="https://github.com/jlopez873/Compliance_Tableau_Dashboard">GitHub</a> along with <a href="http://javierlopezcastillo.com/">other projects</a> I’ve completed and the <a href="https://public.tableau.com/app/profile/javier.lopez.castillo/viz/ComplianceDashboard_16830611211120/COMPLIANCEDASHBOARD">Tableau dashboard</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8427e1ac5759" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Utilizing Tableau for In-Depth Hospital Readmission Data Analysis]]></title>
            <link>https://javilopezcastillo.medium.com/utilizing-tableau-for-in-depth-hospital-readmission-data-analysis-52195fa277ec?source=rss-221ab9e23bea------2</link>
            <guid isPermaLink="false">https://medium.com/p/52195fa277ec</guid>
            <category><![CDATA[tableau]]></category>
            <category><![CDATA[demographic-analysis]]></category>
            <category><![CDATA[hospital-readmissions]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[performance-metrics]]></category>
            <dc:creator><![CDATA[Javier Lopez Castillo]]></dc:creator>
            <pubDate>Fri, 12 May 2023 19:04:20 GMT</pubDate>
            <atom:updated>2023-05-12T19:04:20.649Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oMmzqHSOxW7sGMULHNLlew.png" /></figure><h3>Abstract</h3><p>This article outlines a comprehensive project that involves the utilization of <a href="https://public.tableau.com/app/profile/javier.lopez.castillo">Tableau</a> to effectively analyze and visualize hospital readmission data. The main goal of the project is to assist in the understanding of various factors that affect hospital readmissions, with a particular focus on Medica General Hospital. The project leverages Tableau’s powerful data visualization capabilities to present clear and insightful findings.</p><p>To view the Tableau dashboard <a href="https://public.tableau.com/app/profile/javier.lopez.castillo/viz/UnitedStatesHospitalAdmissions/Hospital">click here</a>.</p><h3>Introduction</h3><p>Tableau has become an essential tool in data analytics due to its ability to handle large volumes of data and its intuitive data visualization capabilities. This project involves using Tableau to analyze readmission data from Medica General Hospital, with the aim of identifying key factors contributing to the readmission rates. The data includes patient demographics, medical conditions, initial services provided, and various performance metrics.</p><h3>Understanding Readmission Rates</h3><p>The first part of the project involves building a comprehensive understanding of the readmission rates at a national, regional, and county level. By creating specific worksheets in Tableau, the data is visualized to compare the expected and actual readmission rates, both within the hospital and compared to other institutions nationally. This analysis allows us to gain insights into how Medica General’s performance stacks up against other hospitals and identify areas for improvement.</p><h3>Detailed County Analysis</h3><p>A detailed breakdown of the data is also done on a county level. This involves creating a new worksheet that provides insights into readmission rates, admission types, and patient statistics for each county. By examining the different variables in detail, it becomes possible to identify any county-specific trends or anomalies that might be influencing readmission rates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sm9GLGHy0ilkYrMfc2DBYQ.png" /></figure><h3>Performance Metrics Tracking</h3><p>Another vital aspect of this project is the tracking of performance metrics. This includes measures such as the Network to Comp (NTC) Score, which calculates the difference between the national comparative hospitals’ and Medica General’s readmission rate. Understanding these metrics can help identify any systemic issues or opportunities for improvement in the hospital’s operations.</p><h3>Demographic Analysis</h3><p>Demographics play a crucial role in understanding hospital readmissions. This project therefore includes a comprehensive analysis of patient demographics such as gender, age, marital status, dependents, and income groups. By incorporating these demographic variables into the analysis, we can gain a deeper understanding of the patient population and how these factors might be influencing readmission rates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7-6V_ki85cc-SYihdlfGJA.png" /></figure><h3>Dashboard Design</h3><p>The culmination of the project is the creation of a comprehensive dashboard that integrates all the different components of the analysis. The dashboard is designed to be highly interactive and user-friendly, with filters that allow users to customize the data displayed. This makes it easy to explore different aspects of the data and gain a thorough understanding of the factors influencing hospital readmissions.</p><h3>Conclusion</h3><p>This project is an excellent example of how Tableau can be leveraged for in-depth data analysis. The comprehensive analysis of hospital readmission data provides valuable insights that can be used to improve patient care and reduce readmission rates. The interactive dashboard makes it easy for users to explore the data and draw their own conclusions, demonstrating the power of data visualization in healthcare analytics.</p><p>This project is a step towards a more data-driven approach in healthcare, enabling hospitals like Medica General to leverage data in their decision-making processes and ultimately improve patient outcomes.</p><h3>Sources</h3><p><a href="https://data.cms.gov/provider-data/dataset/9n3s-kdb3">Center for Medicare &amp; Medicaid Services</a></p><p>The data files, Jupyter notebooks, and project report can be found on <a href="https://github.com/jlopez873/Medica_General_Tableau_Dashboard">GitHub</a> along with <a href="http://javierlopezcastillo.com/">other projects</a> I’ve completed and the <a href="https://public.tableau.com/app/profile/javier.lopez.castillo/viz/UnitedStatesHospitalAdmissions/Hospital">Tableau dashboard</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52195fa277ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Predicting Customer Bandwidth Usage Using Machine Learning]]></title>
            <link>https://javilopezcastillo.medium.com/predicting-customer-bandwidth-usage-using-machine-learning-766fd0264658?source=rss-221ab9e23bea------2</link>
            <guid isPermaLink="false">https://medium.com/p/766fd0264658</guid>
            <category><![CDATA[random-forest-regressor]]></category>
            <category><![CDATA[telecommunication]]></category>
            <category><![CDATA[bandwidth-usage]]></category>
            <category><![CDATA[feature-importance]]></category>
            <category><![CDATA[customer-churn]]></category>
            <dc:creator><![CDATA[Javier Lopez Castillo]]></dc:creator>
            <pubDate>Fri, 12 May 2023 18:46:07 GMT</pubDate>
            <atom:updated>2023-05-12T18:46:07.229Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zOOj9yto9lI4Yf_2" /><figcaption>Photo by <a href="https://unsplash.com/@skamenar?utm_source=medium&amp;utm_medium=referral">Steven Kamenar</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Telecommunications has evolved over the years, morphing into an industry that heavily relies on data analytics. Predicting customer bandwidth usage has become crucial for telecom companies. As the demand for streaming services and smart home devices grows, so does the need for bandwidth. This article discusses how a random forest regression model can be used to predict future bandwidth usage based on customer data.</p><h3>The Dataset</h3><p>The first step of our analysis was to acquire and clean the dataset. The dataset had several features including age, gender, partner status, dependents, tenure with the company, phone service, multiple lines, internet service, online security, online backup, device protection, tech support, streaming services, contract, paperless billing, payment method, monthly charges, total charges, churn, and customer satisfaction survey responses.</p><p>After the data was cleaned and preprocessed, it was split into training and testing datasets for model building and evaluation. The cleaned data was saved in “rf_clean.csv”, the training dataset in “rf_train.csv”, and the testing dataset in “rf_test.csv”.</p><h3>Data Analysis using Random Forests</h3><p>Random Forests regression model was used to analyze the dataset. This model builds multiple decision trees and combines their predictions to make a single prediction for each data point. It is especially good at handling large datasets with many features and can predict numerical values based on input features.</p><p>The model was initially tested with all input variables in the dataset. The mean squared score was calculated, and the true and predicted values were plotted to visualize the model’s performance. The correlation coefficient between the true and predicted values was also calculated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AVTXUnNiVvZDYCEqQfTeOw.png" /></figure><p>Next, the importance of each feature used to predict bandwidth usage was evaluated. The five most important features were found to be tenure, InternetService_DSL, MonthlyCharge, Age, and Children. Interestingly, customer survey responses did not appear in the top ten feature importance values, which is an important insight for stakeholders.</p><p>Step-forward feature selection was used to find the best set of features for our reduced model, which recursively added one feature at a time by order of importance. After the best features were identified, their variance inflation factor was calculated to check for multicollinearity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5S0G6QYUaWk4xipVzstdGw.png" /></figure><p>Finally, the model was used to predict future bandwidth usage. This was done by isolating active customers who have yet to churn and increasing their tenure by 12 months. The model then used this data to predict bandwidth usage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NKSApTfLGI51CiVNbXdR1A.png" /></figure><h3>Results and Implications</h3><p>The accuracy of the random forest models was measured using the R-Squared and Mean Squared Error (MSE) values. The model began with an initial R-Squared value of 99.79%, which improved to 99.83% in the reduced model. The initial model had an MSE of 0.0020, which reduced to 0.0018 in the reduced model.</p><p>The model predicted that on average, each customer would use 1.21 GB of bandwidth more than the previous year. The heatmap of the reduced model’s features and our target variable showed a strong positive relationship between tenure and annual bandwidth usage. Other important factors include the customer’s monthly charge, age, number of children in their household, and whether they subscribe to TV streaming services.</p><p>Interestingly, the analysis also revealed a negative correlation between age and annual bandwidth usage, implying that customers use less bandwidth as they age.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WeDdFjGpEB_0ITlJnC_3Ow.png" /></figure><h3>Limitations and Recommendations</h3><p>One limitation of this analysis was the computational cost of tuning hyperparameters for random forest models. Hyperparameter tuning is a process that finds the best values for parameters such as n_estimators, max_depth, min_samples_split, min_samples_leaf, and max_features. This process can be time-consuming and resource-intensive.</p><p>Given the insights from the analysis, it is recommended that the telecom company focus on attracting younger customers and parents. Younger customers are likely to use more bandwidth as they are more inclined towards streaming services and the use of smart devices. Parents, particularly those with multiple children, also represent a significant user group as they would need more bandwidth for their family’s various online activities. Furthermore, customer retention strategies should be emphasized as longer-term customers tend to have higher annual bandwidth usage. This could include loyalty programs, personalized offers, or enhanced customer service.</p><h3>Future Directions</h3><p>Looking ahead, the next step would be to focus on hyperparameter tuning to further improve the model. Advanced techniques like grid search or random search can be used to automate the hyperparameter tuning process, although these techniques require significant computational resources.</p><p>Additionally, other machine learning models like gradient boosting or deep learning could be explored to see if they offer any performance benefits over random forests for this particular problem.</p><p>Finally, it would be interesting to incorporate more dynamic data into the model, such as real-time bandwidth usage or customer behavior data. This could potentially allow the model to make more accurate and timely predictions, which could be beneficial for network planning and management.</p><p>In conclusion, machine learning provides a powerful tool for telecommunications companies to predict customer bandwidth usage. Despite its limitations, our random forest model achieved high accuracy in predicting future bandwidth usage. The insights derived from this model can assist the telecom company in strategic planning, improving customer service, and ultimately staying competitive in the rapidly evolving telecommunications industry.</p><p>The data files, Jupyter notebooks, Python scripts, and project report can be found on <a href="https://github.com/jlopez873/Customer_Churn_Prediction_Random_Forest">GitHub</a> along with <a href="http://javierlopezcastillo.com/">other projects</a> I’ve completed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=766fd0264658" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leveraging Machine Learning to Predict Customer Churn for a Telecom Company]]></title>
            <link>https://javilopezcastillo.medium.com/leveraging-machine-learning-to-predict-customer-churn-for-a-telecom-company-82811c606f73?source=rss-221ab9e23bea------2</link>
            <guid isPermaLink="false">https://medium.com/p/82811c606f73</guid>
            <category><![CDATA[customer-churn]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[telecom-industry]]></category>
            <category><![CDATA[predictive-modeling]]></category>
            <category><![CDATA[k-nearest-neighbors]]></category>
            <dc:creator><![CDATA[Javier Lopez Castillo]]></dc:creator>
            <pubDate>Fri, 12 May 2023 18:26:51 GMT</pubDate>
            <atom:updated>2023-05-16T16:35:41.798Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DlT899gye1UEmWdo" /><figcaption>Photo by <a href="https://unsplash.com/@jontyson?utm_source=medium&amp;utm_medium=referral">Jon Tyson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In today’s competitive telecommunications market, customer churn can severely impact a company’s financial bottom line. Losing customers is costly, and acquiring new ones can be more expensive than retaining existing ones. Recognizing this, a leading telecom company recently undertook a project to leverage machine learning (ML) models to predict which of their customers were at risk of churning.</p><h3>Analysis Methodology and Data Processing</h3><p>The company used a dataset of over 10,000 customers, containing various features such as demographics, internet service details, tenure, monthly charges, contract type, among others. These features were used to create an optimal machine learning model to predict customer churn. The data was preprocessed to handle missing values and outliers. Moreover, categorical variables were one-hot encoded to be suitable for machine learning algorithms.</p><p>Data preprocessing was carried out with the following code.</p><pre># Import libraries/packages<br>import numpy as np<br>from numpy.linalg import eig<br>import pandas as pd<br>import seaborn as sns<br>import matplotlib.pyplot as plt<br>%matplotlib inline<br>plt.rcParams[&#39;figure.figsize&#39;] = (18,10)<br>plt.rcParams[&#39;figure.max_open_warning&#39;] = False<br>from sklearn.preprocessing import LabelEncoder, StandardScaler<br>from sklearn.model_selection import train_test_split, cross_val_score<br>from sklearn.neighbors import KNeighborsClassifier<br>from sklearn.metrics import confusion_matrix, roc_curve, auc<br>from sklearn.ensemble import GradientBoostingClassifier<br><br># Import data<br>df = pd.read_csv(&#39;churn_clean.csv&#39;).reset_index(drop=True)<br><br># Review shape and data types<br>df.info()</pre><pre>RangeIndex: 10000 entries, 0 to 9999<br>Data columns (total 50 columns):<br> #   Column                Non-Null Count  Dtype  <br>---  ------                --------------  -----  <br> 0   CaseOrder             10000 non-null  int64  <br> 1   Customer_id           10000 non-null  object <br> 2   Interaction           10000 non-null  object <br> 3   UID                   10000 non-null  object <br> 4   City                  10000 non-null  object <br> 5   State                 10000 non-null  object <br> 6   County                10000 non-null  object <br> 7   Zip                   10000 non-null  int64  <br> 8   Lat                   10000 non-null  float64<br> 9   Lng                   10000 non-null  float64<br> 10  Population            10000 non-null  int64  <br> 11  Area                  10000 non-null  object <br> 12  TimeZone              10000 non-null  object <br> 13  Job                   10000 non-null  object <br> 14  Children              10000 non-null  int64  <br> 15  Age                   10000 non-null  int64  <br> 16  Income                10000 non-null  float64<br> 17  Marital               10000 non-null  object <br> 18  Gender                10000 non-null  object <br> 19  Churn                 10000 non-null  object <br> 20  Outage_sec_perweek    10000 non-null  float64<br> 21  Email                 10000 non-null  int64  <br> 22  Contacts              10000 non-null  int64  <br> 23  Yearly_equip_failure  10000 non-null  int64  <br> 24  Techie                10000 non-null  object <br> 25  Contract              10000 non-null  object <br> 26  Port_modem            10000 non-null  object <br> 27  Tablet                10000 non-null  object <br> 28  InternetService       10000 non-null  object <br> 29  Phone                 10000 non-null  object <br> 30  Multiple              10000 non-null  object <br> 31  OnlineSecurity        10000 non-null  object <br> 32  OnlineBackup          10000 non-null  object <br> 33  DeviceProtection      10000 non-null  object <br> 34  TechSupport           10000 non-null  object <br> 35  StreamingTV           10000 non-null  object <br> 36  StreamingMovies       10000 non-null  object <br> 37  PaperlessBilling      10000 non-null  object <br> 38  PaymentMethod         10000 non-null  object <br> 39  Tenure                10000 non-null  float64<br> 40  MonthlyCharge         10000 non-null  float64<br> 41  Bandwidth_GB_Year     10000 non-null  float64<br> 42  Item1                 10000 non-null  int64  <br> 43  Item2                 10000 non-null  int64  <br> 44  Item3                 10000 non-null  int64  <br> 45  Item4                 10000 non-null  int64  <br> 46  Item5                 10000 non-null  int64  <br> 47  Item6                 10000 non-null  int64  <br> 48  Item7                 10000 non-null  int64  <br> 49  Item8                 10000 non-null  int64  <br>dtypes: float64(7), int64(16), object(27)</pre><pre># Drop granular data<br>df.drop([<br>    &#39;CaseOrder&#39;, <br>    &#39;Customer_id&#39;, <br>    &#39;Interaction&#39;, <br>    &#39;UID&#39;, <br>    &#39;City&#39;, <br>    &#39;State&#39;,<br>    &#39;County&#39;, <br>    &#39;Zip&#39;, <br>    &#39;Lat&#39;, <br>    &#39;Lng&#39;, <br>    &#39;TimeZone&#39;, <br>    &#39;Job&#39;<br>], axis=1, inplace=True)<br><br># Drop granular data<br>df.drop([<br>    &#39;CaseOrder&#39;, <br>    &#39;Customer_id&#39;, <br>    &#39;Interaction&#39;, <br>    &#39;UID&#39;, <br>    &#39;City&#39;, <br>    &#39;State&#39;,<br>    &#39;County&#39;, <br>    &#39;Zip&#39;, <br>    &#39;Lat&#39;, <br>    &#39;Lng&#39;, <br>    &#39;TimeZone&#39;, <br>    &#39;Job&#39;<br>], axis=1, inplace=True)<br><br># Rename non-descript variables<br>df.rename({<br>    &#39;Item1&#39;:&#39;TimelyResponse&#39;,<br>    &#39;Item2&#39;:&#39;TimelyFixes&#39;,<br>    &#39;Item3&#39;:&#39;TimelyReplacements&#39;,<br>    &#39;Item4&#39;:&#39;Reliability&#39;,<br>    &#39;Item5&#39;:&#39;Options&#39;,<br>    &#39;Item6&#39;:&#39;RespectfulResponse&#39;,<br>    &#39;Item7&#39;:&#39;CourteousExchange&#39;,<br>    &#39;Item8&#39;:&#39;ActiveListening&#39;<br>}, axis=1, inplace=True)<br><br># Create a copy of the original data<br>df1 = df.copy()<br><br># Check for duplicate values<br>print(&#39;Duplicate Values Found:&#39;, df.duplicated().sum())</pre><blockquote>Duplicate Values Found: 0</blockquote><pre># Isolate string variables from numeric variables<br>object_df = pd.DataFrame()<br>for col in df.columns:<br>    if df[col].dtype == object:<br>        object_df[col] = df[col]<br>        df = df.drop(col, axis=1)<br><br># Scale the data<br>scaler = StandardScaler()<br>df = pd.DataFrame(scaler.fit_transform(df), columns=df.columns)<br><br># Detect outliers<br>df[df.abs() &gt; 3].dropna(how=&#39;all&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9mJGhrOfhsfrVX1bjmlshQ.png" /></figure><pre># Remove observations with absolute zscore over 3<br>df = df[df.abs() &lt; 3].dropna()<br><br># Evaluate data loss<br>lost = ((len(object_df) - len(df)) / len(object_df)) * 100<br>print(&#39;Data Lost: {}%\nData Kept: {}%&#39;.format(lost, 100-lost))</pre><blockquote>Data Lost: 9.15%<br>Data Kept: 90.85%</blockquote><pre># Drop outlier observations from object data frame<br>object_df = object_df.loc[df.index]<br><br># Define dictionary for contract variable<br>contract = {<br>    &#39;Month-to-month&#39;: 0,<br>    &#39;One year&#39;: 1,<br>    &#39;Two Year&#39;: 2<br>}<br><br># Encode the contract variable and drop it from object df<br>df[&#39;Contract&#39;] = object_df[&#39;Contract&#39;].map(contract)<br>object_df.drop(&#39;Contract&#39;, axis=1, inplace=True)<br><br># Instantiate the label encoder<br>le = LabelEncoder()<br><br># Loop through each variable to encode it<br>for col in object_df.columns:<br>    if &#39;Yes&#39; in object_df[col].values:<br>        df[col] = le.fit_transform(object_df[col])<br>        object_df.drop(col, axis=1, inplace=True)<br><br># Get dummy variables<br>object_df = pd.get_dummies(object_df)<br><br># Combine data frames<br>df[object_df.columns] = object_df<br><br># Save clean data set to csv file<br>df.to_csv(&#39;knn_clean.csv&#39;)</pre><p>The following code illustrates the data splitting process into training and testing subsets.</p><pre># Isolate the target variable from the data<br>X, y = df.drop(&#39;Churn&#39;, axis=1), df[&#39;Churn&#39;]<br><br># Split the data into training and testing sets<br>X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.7)<br><br># Combine target and explanatory variables<br>X_train[&#39;Churn&#39;] = y_train<br>X_test[&#39;Churn&#39;] = y_test<br><br># Save training and testing data sets to csv files<br>X_train.to_csv(&#39;knn_train.csv&#39;)<br>X_test.to_csv(&#39;knn_test.csv&#39;)<br><br># Drop target variable from train and test sets<br>X_train.drop(&#39;Churn&#39;, axis=1, inplace=True)<br>X_test.drop(&#39;Churn&#39;, axis=1, inplace=True)</pre><h3>Churn Analysis using Machine Learning Models</h3><p>The company employed two machine learning models to predict customer churn: K-Nearest Neighbors (KNN) and Gradient Boosting. These models were chosen due to their robustness in handling both continuous and categorical variables.</p><p>The KNN model was trained and tested using cross-validation, achieving an accuracy of 83.64%. This means that the model correctly predicted whether a customer would churn or not in about 83.64% of the cases. The model’s effectiveness was further validated using the Receiver Operating Characteristic (ROC) curve, obtaining an Area Under the Curve (AUC) of 0.8943, suggesting that the model could effectively distinguish between customers who churn and those who don’t.</p><p>The next block of code was utilized for cross-validation to find the optimal value for K.</p><pre># Create a dictionary to store model metrics<br>k_scores = {}<br><br># Loop through k values 10 times<br>for k in range(1,11):<br>    <br>    # Define the knn classifier model<br>    knn = KNeighborsClassifier(n_neighbors=k)<br>    <br>    # Evaluate the model using cross-validation<br>    results = cross_val_score(knn, X, y, cv=10, scoring=&#39;accuracy&#39;)<br>    <br>    # Store the average cv score and k<br>    k_scores[k] = results.mean()<br><br># Select the highest scoring model<br>k = max(k_scores, key=k_scores.get)</pre><p>The subsequent code snippets were used to fit, test, and score the KNN model.</p><pre># Fit the model using the training set<br>knn = KNeighborsClassifier(n_neighbors=k)<br>knn.fit(X_train, y_train)</pre><blockquote>KNeighborsClassifier(n_neighbors=9)</blockquote><pre># Score the final model<br>score = knn.score(X_test, y_test)<br><br>print(f&#39;Accuracy: {round(score*100, 2)}%&#39;)</pre><blockquote>Accuracy: 84.45%</blockquote><pre># Predict churn using the final model<br>y_pred = knn.predict(X_test)<br><br># Define function to plot confusion matrix<br>def plot_cm(y_test, y_pred, mod_name):<br>    ## Get confusion matrix<br>    cm = confusion_matrix(y_test, y_pred)<br>    ## Plot confusion matrix<br>    labels = [&#39;Positive&#39;, &#39;Negative&#39;]<br>    sns.heatmap(cm, annot=True, fmt=&#39;d&#39;, cmap=&#39;Blues&#39;, xticklabels=labels, yticklabels=labels)<br>    plt.title(&#39;Confusion Matrix: {}&#39;.format(mod_name))<br>    plt.show()<br><br># Plot the confusion matrix for the knn model<br>plot_cm(y_test, y_pred, &#39;KNN&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*IV0qJbjTtZAqQrfnBuXZMA.png" /></figure><pre># Get model probabilities<br>y_pred_prob = knn.predict_proba(X_test)[:,1]<br><br># Calculate false and true positive rates<br>fpr, tpr, thresholds = roc_curve(y_test, y_pred_prob)<br><br># Calculate the AUC<br>auc_score = auc(fpr, tpr)<br>print(f&#39;AUC: {auc_score}&#39;)</pre><blockquote>AUC: 0.8981965528736664</blockquote><pre># Plot the ROC curve<br>plt.plot(fpr, tpr, label=f&#39;AUC = {round(auc_score, 2)}&#39;)<br><br># Plot the diagonal line (random classifier)<br>plt.plot([0, 1], [0, 1], &#39;k--&#39;)<br><br># Fill the area under the curve<br>plt.fill_between(fpr, tpr, color=&#39;blue&#39;, alpha=0.05)<br>plt.xlabel(&#39;False Positive Rate (FPR)&#39;)<br>plt.ylabel(&#39;True Positive Rate (TPR)&#39;)<br>plt.title(&#39;ROC Curve: KNN&#39;)<br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IFH41W8eKjd3dViUxaziYg.png" /></figure><p>In addition, the Gradient Boosting model was employed to understand the importance of various features in predicting churn. The features with the highest Gini importance values were Tenure, MonthlyCharge, Contract, StreamingMovies, StreamingTV, InternetFiberOptic, InternetDSL, and Bandwidth_GB_Year. Interestingly, customer survey responses did not appear among the top twenty feature importance values.</p><p>The following code illustrates how the Gradient Boosting model was utilized to discern the significance of various features in churn prediction.</p><pre># Instantiate the gradient boosting model<br>gini = GradientBoostingClassifier(<br>           n_estimators=1000, random_state=10, n_iter_no_change=10<br>       )<br><br># Fit the model<br>gini.fit(X_train, y_train)</pre><blockquote>GradientBoostingClassifier(n_estimators=1000, n_iter_no_change=10, random_state=10)</blockquote><pre># Print the stopping n_estimators value<br>print(f&#39;Best n_estimators Value: {gini.n_estimators_}&#39;)</pre><blockquote>Best n_estimators Value: 149</blockquote><pre># Print the model&#39;s accuracy score<br>print(f&#39;Accuracy: {round(gini.score(X, y)*100, 2)}%&#39;)</pre><blockquote>Accuracy: 91.49%</blockquote><pre># Store the Gini importance values<br>importance = pd.DataFrame(gini.feature_importances_, index=gini.feature_names_in_, columns=[&#39;gini&#39;])<br>importance.sort_values(&#39;gini&#39;, ascending=False, inplace=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*kqs5gGUWz9luAT29yqfS0A.png" /></figure><p>The code provided below was implemented to identify active customers susceptible to churn.</p><pre># Create data frame from customers that have not churned<br>not_churned = df[df.Churn == 0]<br><br># Split target and explanatory variables<br>X_true, y_true = not_churned.drop(&#39;Churn&#39;, axis=1), not_churned[&#39;Churn&#39;]<br><br># Predict what current customers are at highest risk of churn<br>y_pred = knn.predict(X_true)<br><br># Plot the confusion matrix<br>plot_cm(y_true, y_pred, &#39;KNN Predictions&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*BeYUCZBsY0cPJUlzQLDFmA.png" /></figure><pre># Get model probabilities<br>y_pred_prob = knn.predict_proba(X_true)[:,1]<br><br># Calculate the amount of positive and negative predictions<br>pos = np.count_nonzero(y_pred!=0)<br>neg = np.count_nonzero(y_pred==0)<br>print(f&#39;({pos}, {neg})&#39;)</pre><blockquote>(388, 6278)</blockquote><pre># Calculate the false and true, positive and negative rates<br>fpr = fpr.mean()<br>tpr = tpr.mean()<br>fnr = 1 - tpr.mean()<br>tnr = 1 - fnr<br><br># Calculate the amount of false positives and negatives<br>fp = int(fpr * neg)<br>fn = int((1 - tpr) * pos)<br><br># Compare false negative and positive rates<br>fnr, fpr</pre><blockquote>(0.45032866178841624, 0.21361127582903802)</blockquote><pre># Combine the predicted values with explanatory features<br>X_true[&#39;Churn&#39;] = y_pred</pre><h3>Key Findings and Implications</h3><p>The models were able to identify customers at high risk of churn. From the summary statistics of customers predicted to churn, it was found that such customers had an average tenure of just 10.85 months with the company and an average monthly charge of $181.48. They typically subscribed to a streaming service and used fiber optic internet, consuming about 1,441.61 GB of bandwidth per year.</p><p>The following code snippet was used to gather the summary statistics of customers predicted to churn.</p><pre># Recall the customers that have been predicted to churn<br>churn = df1.loc[<br>    X_true[X_true.Churn == 1<br>].index].drop(&#39;Churn&#39;, axis=1).reset_index(drop=True)<br><br># View summary statistics<br>churn[[&#39;Tenure&#39;, &#39;MonthlyCharge&#39;, &#39;Bandwidth_GB_Year&#39;]].describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*FeJS4igOd_eM3C-vrUb5rA.png" /></figure><pre># View total customers at risk of churn by feature<br>for feature in churn[<br>    [&#39;Contract&#39;, &#39;StreamingTV&#39;, &#39;StreamingMovies&#39;, &#39;InternetService&#39;]<br>]:<br>    print(churn[feature].value_counts())</pre><blockquote><strong>Contract</strong><br>Month-to-month 213<br>One year 123<br>Two Year 52<br><strong>StreamingTV</strong><br>No 201<br>Yes 187<br><strong>StreamingMovies</strong><br>Yes 203<br>No 185<br><strong>InternetService</strong><br>Fiber Optic 220<br>DSL 95<br>None 73</blockquote><p>However, a limitation of the analysis was the model’s relatively high false-negative rate (FNR) of 0.45, compared to the false-positive rate (FPR) of 0.21. This means that the model tended to predict that a customer would not churn when they actually would, which is a more costly mistake than predicting a customer will churn when they actually won’t.</p><h3>Recommendations</h3><p>Based on the analysis, the telecom company is advised to review its pricing strategy, especially for customers using streaming services, as they seem to be at a higher risk of churn. Additionally, it could be beneficial to incentivize customers before they reach eleven months’ tenure to try to convert them into a one-year or two-year contract. This strategy should particularly target those subscribed to streaming services.</p><p>In conclusion, machine learning models can provide valuable insights into customer behavior and help in predicting customer churn. These insights can guide the development of effective customer retention strategies, ultimately helping to improve a company’s bottom line. Future work could focus on fine-tuning the models to reduce the false-negative rate, potentially by incorporating additional significant features or reducing noise in the current model.</p><p>The data files, Jupyter notebooks, Python scripts, and project report can be found on <a href="https://github.com/jlopez873/Customer_Churn_Analysis_KNN">GitHub</a> along with <a href="http://javierlopezcastillo.com/">other projects</a> I’ve completed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82811c606f73" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>