<?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 Shashank Gupta on Medium]]></title>
        <description><![CDATA[Stories by Shashank Gupta on Medium]]></description>
        <link>https://medium.com/@shashank.and.gupta?source=rss-ac4f401b071f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*7cd9AUMB5k8T6cD0.jpg</url>
            <title>Stories by Shashank Gupta on Medium</title>
            <link>https://medium.com/@shashank.and.gupta?source=rss-ac4f401b071f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 06:46:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shashank.and.gupta/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[Ways of working in age of AI]]></title>
            <link>https://medium.com/@shashank.and.gupta/ways-of-working-in-age-of-ai-7f3effab2666?source=rss-ac4f401b071f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f3effab2666</guid>
            <dc:creator><![CDATA[Shashank Gupta]]></dc:creator>
            <pubDate>Wed, 21 Oct 2026 19:33:03 GMT</pubDate>
            <atom:updated>2026-10-21T19:33:03.622Z</atom:updated>
            <content:encoded><![CDATA[<p>I’m writing a blog almost after a decade now. A lot has changed in the data science and ML landscape since then. I have gained experience working through different industries — life sciences, healthcare, oil &amp; gas. I aim to address some questions today which I believe are crucial for us to be on the same foot with AI. This is not an LLM written blog and you can sit back relax and give it a read on my perspective.</p><p>Over the 6–7 year period, AI has significantly changed our lives from building statistical models to building agentic systems and so has changed our ways of working. At one point in somewhere 2018, where we use the term AI interchangeably for Machine Learning and Deep Learning models to a time now where we can confidently call LLM &amp; Vision models AI, we have come a long way. AI has made us highly productive in daily tasks and it’s only getting better at it.</p><p>Below are some questions, I would like to address reflecting back on my experience and journey with AI.</p><ul><li><strong>What is one piece of work in my function that is meaningfully different today because of AI?</strong></li><li><strong>Where is the line between an impressive AI system and one I would actually trust with consequential work?</strong></li><li><strong>If every organization had access to roughly the same powerful AI models, what would separate those that succeed with AI from those that do not?</strong></li><li><strong>Where should humans remain meaningfully “in the loop” and what should we probably stop requiring people to do?</strong></li><li><strong>What are universities at risk of preparing students for that may look very different five years from now?</strong></li><li><strong>What distinguishes someone who frequently uses AI from someone you would genuinely consider AI-capable?</strong></li></ul><p>Before I start answering these questions, I would like to mention that I work in healthcare industry. My answers might reflect my personal views to AI from a Clinical perspective but I will try to be more complete.</p><blockquote><strong>What is one piece of work in my function that is meaningfully different today because of AI?</strong></blockquote><p>Few years back, I use to develop Clinical triaging Machine learning models aiming to predict for specific health conditions and tying them with better patient outcomes. We still do that, but recently there has been an influx of new kind of models which falls outside of the realm of traditional machine learning. Most of these new models utilizes Generative AI in different flavors. To name a few, we have Summarizer models, Chat-Assistants, RAG models, and Agentic medical coding assistants.</p><p>Now, with these new incoming models. The question emerges, how would you evaluate the performance of these Generative models. The game has changed since triaging ML models has much more concrete evaluation literature. While for Generative models, it’s a new beast with different capabilities. It’s no more about evaluating the traditional metrics and rests much more on developing new frameworks, metrics, and workflows keeping in mind any wrong step in evaluation could mis-represent the patient outcomes. From spending time to develop traditional ML models, we invest time in responsibly evaluating the Generative models. So, spending more time developing comprehensive evaluation plans, pressure testing these new frameworks and workflows.</p><p>There’s a positive outcome as well, evaluating traditional triaging models has become easier. We recently created an agentic system to evaluate and monitor the performance of traditional ML models. These are mostly deterministic and utilizes Agents in decision making primarily.</p><p>AI is posing new challenges related to evaluation but also helping automating the old ways of evaluating the ML models.</p><blockquote><strong>Where is the line between an impressive AI system and one I would actually trust with consequential work?</strong></blockquote><p>We frequently encounter scenarios relating to above question in our line of work. As an example, let’s say an AI summarizer tool might produce a beautifully written summary of a patient chart but lacks in presenting the clinically meaningful findings. For example, the summarizer may omit useful information relating to patient’s medical history like omitting the Chronic Kidney disease diagnosis which can result in wrongful interpretation of the patient’s chart and affects the subsequent treatment. To overcome such issues, it’s always helpful to know the limitations of the tool for which the tool matters.</p><p>In this case, knowing the summarizer’s capabilities on clinical relevance, completeness, omissions can help disclose the limitations of the tool which matters most from a clinical perspective.</p><p>So to answer, an Impressive AI system shows us what it can do, while a Trustworthy AI system shows us what it can do reliably, where it can fail, whether those failures can be safely managed.</p><blockquote><strong>If every organization had access to roughly the same powerful AI models, what would separate those that succeed with AI from those that do not?</strong></blockquote><p>Assuming all organizations have access to the same AI models, the value comes down to below three points.</p><ul><li><em>Domain Expertise and Understanding the actual problems</em></li><li><em>Integration of AI in workflows</em></li><li><em>Ability to build trust</em></li></ul><p><strong><em>Domain Expertise &amp; Understanding the actual problems</em></strong></p><p>Today’s organizations need people who deeply understands the challenges in their industry and problems worth solving.</p><p><strong><em>Integration of AI in workflows</em></strong></p><p>Many times, we develop POC that look impressive on Jupyter notebook reports but hardly converts to production where users can actually use it. It boils down to having right data infrastructure and workflows which user can actually use.</p><p><strong><em>Ability to build Trust</em></strong></p><p>Organizations needs to know where AI is working reliably, where AI is failing, and if those failures are acceptable.</p><p><strong>So, an actual winner would be the one that understand their problems best, redesign their workflows effectively, and build systems they can actually trust.</strong></p><blockquote><strong>Where should humans remain meaningfully “in the loop” and what should we probably stop requiring people to do?</strong></blockquote><p>I believe Human Oversight is important when there’s important decisions to be made. This should be part of the solution design while automating a particular task.</p><p>For example, while automating a task, we should identify where AI is reliably automating the process and where it’s struggling and requires human judgement. Also, checking if human judgement is bringing any value when compared to AI.</p><blockquote><strong>What are universities at risk of preparing students for that may look very different five years from now?</strong></blockquote><p>In my opinion, universities curriculum is focused on the current ways of working rather then planned for 5 years from now.</p><p>I have been a student 3 years ago and I took the courses which helped me learn programming and algorithms development. These courses are still relevant today but in the current age of AI, the task completion time has been shrinked significantly by coding assistants.</p><p>So, I believe the universities at risk are those which are not including the problem formulation, domain expertise, and critical thinking skills. Universities focusing on these in addition to their current curriculum are prepared for future.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f3effab2666" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Time Series Forecasting Using Machine Learning]]></title>
            <link>https://medium.com/enjoy-algorithm/time-series-forecasting-using-machine-learning-d137485dd43e?source=rss-ac4f401b071f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d137485dd43e</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Shashank Gupta]]></dc:creator>
            <pubDate>Sun, 13 Feb 2022 04:42:14 GMT</pubDate>
            <atom:updated>2022-02-19T00:13:34.821Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TQPtXJZ7wybHyYPsSltVVA.jpeg" /></figure><p>Time Series is a set of observations taken at a specific periodic time. Time Series Forecasting refers to the use of statistical models to predict future values using the previously recorded observations. It is broadly classified into two parts:</p><ul><li><strong>Univariate Time Series Forecasting:</strong> Involves a single variable</li><li><strong>Multivariate Time Series Forecasting:</strong> Involves multiple variables</li></ul><p>Building a Statistical Forecasting model often involves a standard procedure. The image below depicts the steps to be carried out to build a forecasting model. We will use the ARIMA algorithm for this tutorial, which is extensively used in short-run forecasts.</p><p>Let’s dive into data analysis:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*rtmThtZhVo3OL6Xhx5QmKw.png" /></figure><h4><strong>Data Analysis</strong></h4><p>For this tutorial, we will be using the Air Passenger Dataset available on <a href="https://www.kaggle.com/rakannimer/air-passengers">Kaggle</a>. It is a reasonably simple time-series data with “<strong>Timestamp</strong>” and “<strong>Number of passengers</strong>” as features. It contains approximately 144 rows and covers 11 years of passenger count.</p><p>Let’s take a look at the trend.</p><pre>import pandas as pd<br>import plotly.express as px</pre><pre>air_passengers = pd.read_csv(&#39;AirPassengers.csv&#39;)<br>fig = px.line(air_passengers, x=&#39;Month&#39;, y=&quot;Passengers&quot;)<br>fig.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*XvHCTjhxyimHO8OHSpC-ig.png" /><figcaption>Month vs. Number of Passengers</figcaption></figure><h4>Time Series Decomposition</h4><p>Understanding a whole time series could be a challenging task. Fortunately, the time series can be decomposed into a combination of trend, seasonality, and noise components. These components provide a valuable conceptual model for thinking about a time series prediction.</p><ul><li><strong>Additive Decomposition:</strong> Assumes that the time series is a linear combination of Trend, Seasonality, and Residual.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*GBDV5sNcRS4tb1MTfVxJ-w.png" /></figure><ul><li><strong>Multiplicative Decomposition:</strong> Assumes that the time series is a product of Trend, Seasonality, and Residual component.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*mSPtUWykmwSrpcHGzCOpmA.png" /></figure><p>The additive decomposition model is preferred when the seasonal variation is somewhat constant over time, while the multiplicative model is useful when the seasonal variation increases over time. For a concrete understanding, visit this <a href="https://online.stat.psu.edu/stat510/lesson/5/5.1">blog</a>. A multiplicative time series can be converted into an additive series using a log transformation.</p><blockquote>Yt = Tt * St * Rt<br>log(Yt) = log(Tt) + log(St) + log(Rt)</blockquote><p>In our case, the seasonality increases over time, so we have to use a multiplicative time series decomposition. Let’s decompose our time series!</p><pre>from statsmodels.tsa.seasonal import seasonal_decompose</pre><pre>decomposed = seasonal_decompose(series, model=&#39;multiplicative&#39;)<br>decomposed.plot()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*Jr8ymZ7SyWVdw_IF0aid4w.png" /><figcaption>Time Series Decomposition</figcaption></figure><p>From the above time series decomposition, we can infer that the time series has a seasonality period of 1 year, and the trend is strictly increasing. We also have some residuals or noise in the data, which we will attempt to resolve later.</p><h4><strong>Stationary Test</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*ynuU6lvOJluT-KhALP2KsQ.png" /></figure><p>Before applying any forecasting models to a time series dataset, the time series needs to be stationary. A time series is said to be stationary if its statistical properties (mean, variance, &amp; autocorrelation) do not change over time by a far value.</p><blockquote>It is clear from the above time series plot that the mean of our time series is increasing over time. We know it is not stationary but let’s just confirm it.</blockquote><p>Several methods are available for testing the stationary nature of a time series. One such method is <strong>Dickey-Fuller Test.</strong></p><blockquote>Note: If the time series is not stationary, we can prove that the standard assumptions for forecasting analysis will not be held valid.</blockquote><h4>Dickey-Fuller Test:</h4><p>The Dickey-Fuller test is a statistical significance test, which will give results in hypothesis tests. The hypothesis test considers a Null and an Alternative hypothesis. The hypothesis made for the Dickey-Fuller Test is as follows:</p><blockquote>Null Hypothesis (H0): The time series is not stationary.</blockquote><blockquote>Alternate Hypothesis (Ha): The time series is stationary.</blockquote><p>In the null hypothesis, we first consider that time-series data is non-stationary and then calculate the Dickey-Fuller Test (ADF) value. If the test statistics of the Dickey-Fuller Test (ADF) is less than the critical value(s), then reject the null hypothesis of non-stationary (Series is stationary). On the contrary, if the ADF is greater than the critical value(s), we failed to reject the null hypothesis (Series is Non-stationary).</p><p>In simple terms, the ADF test is a way of testing the stationarity of a time series. ADF test fits the time-series against the differenced time-series using a Linear Regression Model, and this helps us in the computation of t-statistics which is the same as the Dickey-Fuller Test (ADF) value. This t statistics value is then compared against the critical value (significance levels) to arrive at a result.</p><p>Let’s test the stationarity of a time series using the Dickey-Fuller Test:</p><pre>from statsmodels.tsa.stattools import adfuller</pre><pre>result = adfuller(air_passengers[&quot;Passengers&quot;])</pre><pre>print(‘ADF Statistic: %f’ % result[0])<br>print(‘p-value: %f’ % result[1])<br>print(‘Critical Values:’)</pre><pre>for key, value in result[4].items():<br> print(‘\t%s: %.3f’ % (key, value))<br> <br>if result[0] &lt; result[4][“5%”]:<br> print(“Reject Ho — Time Series is Stationary!”)<br>else: <br> print(“Failed to reject Ho — Time Series is not Stationary!”)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*KBz0LD2WL8YkduQBpZxrFg.png" /><figcaption>Dickey-Fuller test result</figcaption></figure><p>Our series is non-stationary, which is evident in the trend itself, but it is always good to verify things. We need to apply some operations to make the series stationary. There are several options available to make a series stationary:</p><ul><li>Time Series Differencing</li><li>Power Transformation</li><li>First-Order Differencing</li><li>Log Transformation</li></ul><p>There’s no perfect way of making a series stationary. Finding an optimum transformation requires an empirical process of hit and try. We will use the differencing method, which is nothing but taking the difference of Y(t)-Y(t-1). This operation generally results in a stationary time series. If not, we can apply the differencing again to an already differenced time series.</p><p>Let’s implement Differencing to our time series:</p><pre>differenced = air_passengers[&quot;Passengers&quot;].diff().dropna()<br>fig = px.line(differenced)<br>fig.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*knw50PX72CS7RN-4f8SV6A.png" /><figcaption>Differenced Time Series</figcaption></figure><p>The differenced time series appears to be stationary this time. We can again apply the Dickey-Fuller test to confirm the stationarity of the differenced time series.</p><h4>ARIMA</h4><p>Now that we have a stationary series, we can move ahead with our forecasting models. We will be using the ARIMA model, which stands for Auto-Regressive Integrative Moving Average for forecasting. It is a generalized version of the ARMA model and simply a combination of two distinct <strong><em>Auto-Regressive</em></strong> &amp; <strong><em>Moving Average</em></strong> models.</p><p>Let’s understand it component-wise:</p><p><strong>Auto-Regressive (AR(p))</strong>: An Auto-Regressive model predicts the value at the current timestamp using the regression equation made from values at previous timestamps. Only past data is used for predicting the value at the current timestamp. Series having autocorrelation indicates the requirement of the auto-regressive component in ARIMA.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YD-srZ1kVe0ZEueu_gG46w.png" /></figure><p><strong>Integrative (I(d))</strong>: This component helps in making the series stationary using the differencing. Differencing is simply an operation where an observation is subtracted from the observation at the previous time step. This operation makes the time series stationary (removes trend and seasonality components from time series). We have already applied it in the last step.</p><p><strong>Moving Average (MA(q))</strong>: A Moving Average model uses the errors from past forecasts in a regression equation. This model assumes that the value at the current timestamp can be predicted using the errors from the past forecasts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FBBQonoMt8k1R4bi870X9w.png" /></figure><p>Integrate all these components to form the ARIMA equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NG92pC7ZzzshJ6DmeRAMwQ.jpeg" /><figcaption>Source: Towards Data Science</figcaption></figure><blockquote>How to find the p, d, q values?</blockquote><p>While using an auto-ARIMA model, finding the optimum seasonal auto-regressive component(p), differencing component(d), and seasonal moving average component(q) is a lot easier. However, we are interested in manually determining these p, d, q components.</p><p>Following are some ways of determining the p, d, &amp; q parameters of ARIMA:</p><ul><li>The autocorrelation plot helps determine the optimal set of q parameters for the Moving Average model.</li><li>The partial autocorrelation plot helps determine the optimal set of p parameters for the Auto-Regressive model.</li><li>An extended autocorrelation plot of the data confirms whether the combination of the AR and MA terms is required for forecasting.</li><li>Akaike’s Information Criterion (AIC) assists in determining the optimal set of p, d, q. Usually, the model with a smaller absolute value of AIC is preferred.</li><li>Schwartz Bayesian Information Criterion (BIC) is another alternative of AIC, and lower BIC is better for selecting the optimal p, d, q.</li></ul><p>Finding the set of p and q values:</p><pre>from statsmodels.graphics.tsaplots import plot_acf, plot_pacf</pre><pre>plot_acf(air_passengers[&quot;Passengers&quot;].diff().dropna())<br>plot_pacf(air_passengers[&quot;Passengers&quot;].diff().dropna())<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*gUmvtv3MCGzAEjI_nb14QQ.png" /></figure><p>For finding the AR component p, we need to look for a sharp initial drop in the partial autocorrelation plot. It is happening just after the first peak. So, the p component value can have either 1 or 2.</p><p>For finding the q value, we will need to see an exponential decrease in the autocorrelation plot. We are not looking for a drastic change; instead, we are looking for a curve settling down to saturation. We can see it is happening just after 1. So, q can also be taken as either 1 or 2.</p><p>Let’s implement ARIMA(1, 1, 1) model:</p><pre>from statsmodels.tsa.arima.model import ARIMA</pre><pre>model = ARIMA(air_passengers[&#39;Passengers&#39;].diff(), order=(1,1,1))<br>results_ARIMA = model.fit()</pre><pre>plt.plot(air_passengers[&#39;Passengers&#39;].diff())<br>plt.plot(results_ARIMA.fittedvalues, color=&#39;red&#39;)</pre><pre>print(&#39;Plotting ARIMA model&#39;)<br>print(results_ARIMA.summary())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*rlWMehA9UzXFHTEwx-LaDw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*w2YRTDCWH8VvXu15SX9Mlg.png" /><figcaption>Fitted ARIMA against Differenced Series</figcaption></figure><pre>residuals = pd.DataFrame(results_ARIMA.resid)<br>residuals.plot(kind=&#39;kde&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*4JYioVx8JDlZ5bYbOSGMqQ.png" /><figcaption>Residuals</figcaption></figure><p>Residuals mean is approximately centered around zero, AIC &amp; BIC metrics indicate an okay-ish fit, and our ARIMA order is optimum, as per the ACF and PACF. But relying upon PACF and ACF for finding the optimum p and q often deceives to the true potential of the ARIMA model. We can always tweak parameters and see if they provide a good forecast for the problem instead of going with the conventional rules. Let’s try another combination:</p><pre>model = ARIMA(air_passengers[&#39;Passengers&#39;].diff(), order=(4,1,4))</pre><pre>results_ARIMA_updated = model.fit()</pre><pre>plt.plot(air_passengers[&#39;Passengers&#39;].diff())<br>plt.plot(results_ARIMA_updated.fittedvalues, color=&#39;red&#39;)</pre><pre>print(&#39;Plotting ARIMA(4,1,4) model&#39;)<br>print(results_ARIMA_updated.summary())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*WtgLvT7NaHJ2zTEY5YDiEw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*2Z_EHiNr85hy1OG1R1aQVA.png" /><figcaption>ARIMA (4, 1, 4)</figcaption></figure><pre>residuals = pd.DataFrame(results_ARIMA_updated.resid)<br>residuals.plot(kind=&#39;kde&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*iYnFIM3i7sW5z-qiYXqOWQ.png" /><figcaption>Residuals of ARIMA(4, 1, 4)</figcaption></figure><p>ARIMA(4, 1, 4) is slightly better than ARIMA(1, 1, 1). Let’s also implement seasonal-ARIMA, which is the same as an ARIMA model, but it also considers the seasonality.</p><pre>import statsmodels.api as sm</pre><pre>model=sm.tsa.statespace.SARIMAX(air_passengers[&#39;Passengers&#39;],order=(7, 1, 7),seasonal_order=(1,1,1,12))<br>results=model.fit()<br>air_passengers[&#39;forecast&#39;]=results.predict(start=120,end=145)<br>air_passengers[[&#39;Passengers&#39;,&#39;forecast&#39;]].plot(figsize=(12,8))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*IooSATPYX5CBejjI5G2NBA.png" /><figcaption>SARIMA (7, 1, 7)</figcaption></figure><h4><strong>Strengths &amp; Limitations of ARIMA</strong></h4><h4><strong>Limitations:</strong></h4><ul><li>Forecasts are unreliable for an extended window</li><li>Data needs to be univariate</li><li>Data should be stationary</li><li>Outliers are challenging to forecast</li><li>Poor at predicting Turning Points</li></ul><h4><strong>Strengths:</strong></h4><ul><li>Highly reliable Forecasts for a short window</li><li>Short-run forecasts frequently outperform the results from complex models, but that also depends on data</li><li>Easy to implement</li><li>Unbiased Forecast</li><li>Realistic Confidence Intervals</li><li>High Interpretability</li></ul><h4><strong>More Forecasting Models</strong></h4><ul><li>Exponential Smoothing</li><li>Dynamic Linear Model</li><li>Linear Regression</li><li>Neural Network Models</li></ul><h3>Possible Interview Questions</h3><p>Time series problems are pretty famous and very useful across different industries. Interviewers ask questions on time series in two cases,</p><ul><li>If we have written some project on time series in our resume.</li><li>If the interviewer wants to hire you for the time series project.</li></ul><p>Questions on this topic will be either generic, covered in this blog, or very specific to our projects. Possible questions on this topic can be:</p><ol><li>What is time-series data, and what makes it different from other datasets?</li><li>What is a forecasting technique? Can you name some popular applications of it?</li><li>Why do we need to decompose the time-series dataset, and what are the possible ways?</li><li>What does the stationary test signify in time-series datasets?</li><li>What is the ARIMA model, and what do we do to find the value of parameters involved in this algorithm?</li></ol><h3><strong>Conclusion</strong></h3><p>This article discussed the essential details about the time series data and forecasting models. We played with the real-world data, in which we learned stationary testing, time series differencing, and data decomposition techniques. After that, we built and evaluated our ARIMA model on that. We hope you enjoyed this article.</p><p><strong>Enjoy Learning! Enjoy Algorithms!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d137485dd43e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/enjoy-algorithm/time-series-forecasting-using-machine-learning-d137485dd43e">Time Series Forecasting Using Machine Learning</a> was originally published in <a href="https://medium.com/enjoy-algorithm">EnjoyAlgorithms</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pre-processing of Time Series Data]]></title>
            <link>https://medium.com/enjoy-algorithm/pre-processing-of-time-series-data-c50f8a3e7a98?source=rss-ac4f401b071f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c50f8a3e7a98</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Shashank Gupta]]></dc:creator>
            <pubDate>Tue, 08 Feb 2022 12:36:30 GMT</pubDate>
            <atom:updated>2022-02-08T12:36:30.521Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qPy-8oH-yXi5M3tc7aJdSA.jpeg" /></figure><p>Time series data is found everywhere, and to perform the time series analysis, we must preprocess the data first. Time Series preprocessing techniques have a significant influence on data modeling accuracy.</p><h4>Key takeaways from this blog</h4><p>In this article, we will be discussing mainly these points:</p><ol><li>Definition of time-series data and its importance.</li><li>Preprocessing steps for time series data.</li><li>Structuring time-series data, finding the missing values, denoising the features, and finding the outliers present in the dataset.</li></ol><p>To begin with, let’s understand the definition of time series first:</p><blockquote>Time Series is a sequence of evenly spaced observations recorded at a specific time interval.</blockquote><p>An example of time series would be the gold prices. In this case, our observation is the gold price collected over a while after fixed time intervals. The time unit could be in minutes, hours, days, years, etc. But the time difference between any two consecutive samples will be the same.</p><p>In this article, we will see the common time-series preprocessing steps that should be carried out before diving into the data modeling part. Let’s look at the common problems associated with the time-series data.</p><h3>Preprocessing Time Series Data</h3><p>Time Series data holds a lot of information, but generally, it is not visible. The common problems associated with time series are un-ordered timestamps, missing values (or timestamps), outliers, and noise in the data. Of all the mentioned problems, handling the missing values is the most difficult one. Since the conventional imputation (A technique used to take care of the missing data by replacing the missing values to retain most of the information) methods are not applicable while working with the time series data. To analyze the real-time analysis of this preprocessing, we will use Kaggle’s Air Passenger dataset, which can be downloaded from<a href="https://www.kaggle.com/rakannimer/air-passengers"> here</a>.</p><h4>Structuring Time Series</h4><p>Time Series data is generally found in unstructured formats, i.e., Timestamps could be mixed and not properly ordered. Also, most of the time, the date-time column has default string data type, and it is essential to covert the data-time column to date-time datatype first before applying any operation to it. Let’s implement this into our dataset:</p><pre>import pandas as pd</pre><pre>passenger = pd.read_csv(&#39;AirPassengers.csv&#39;)<br>passenger[&#39;Date&#39;] = pd.to_datetime(passenger[&#39;Date&#39;]) <br>passenger.sort_values(by=[&#39;Date&#39;], inplace=True, ascending=True)<br>#Above line will sort the values according to dates.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vlSgmgh_YxhAA4v7nI4y1g.png" /></figure><h3>Missing Value Imputation in Time Series</h3><p>Handling the missing values in time series data is a challenging task. Conventional imputation techniques are not applicable for the time-series data since the sequence in which values are received matters. To address this problem, we have the following Interpolation methods:</p><h4><strong>Interpolation</strong></h4><p>Interpolation is a commonly used technique for time series missing value imputation. It helps in estimating the missing data-point using the two surrounding known data points. This method is simple and most intuitive. However, interpolation further has the following sub-methods:</p><ul><li>Time-Based Interpolation</li><li>Spline Interpolation</li><li>Linear Interpolation</li></ul><p>Let’s see how our data looks like before imputation:</p><pre>from matplotlib.pyplot import figure<br>import matplotlib.pyplot as plt</pre><pre>figure(figsize=(12, 5), dpi=80, linewidth=10)<br>plt.plot(passenger[&#39;Date&#39;], passenger[&#39;Passengers&#39;])<br>plt.title(&#39;Air Passengers Raw Data with Missing Values&#39;)<br>plt.xlabel(&#39;Years&#39;, fontsize=14)<br>plt.ylabel(&#39;Number of Passengers&#39;, fontsize=14)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*tfqNdrmL6LMjSgeoJdCIWw.png" /><figcaption>Before Imputation</figcaption></figure><p>Let’s take a look at the imputations:</p><pre>passenger[‘Linear’] = passenger[‘Passengers’].interpolate(method=’linear’)<br>passenger[‘Spline order 3’] = passenger[‘Passengers’].interpolate(method=’spline’, order=3)<br>passenger[‘Time’] = passenger[‘Passengers’].interpolate(method=’time’)</pre><pre>methods = [&#39;Linear&#39;, &#39;Spline order 3&#39;, &#39;Time&#39;]</pre><pre>from matplotlib.pyplot import figure<br>import matplotlib.pyplot as plt<br>for method in methods:<br>    figure(figsize=(12, 4), dpi=80, linewidth=10)<br>    plt.plot(passenger[&quot;Date&quot;], passenger[method])<br>    plt.title(&#39;Air Passengers Imputation using: &#39; + types)<br>    plt.xlabel(&quot;Years&quot;, fontsize=14)<br>    plt.ylabel(&quot;Number of Passengers&quot;, fontsize=14)<br>    plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*kSEMA0kl8CjQiMC2zgocGQ.png" /></figure><p>All methods have given a reliable set of imputations. Imputations from these methods make more sense when the missing value window ( width of missing data) is small. For instance, if several consecutive values are missing, it becomes harder for these methods to estimate them.</p><h4><strong>Denoising a Time Series</strong></h4><p>Noise elements in a time series can cause significant problems, and noise removal is highly recommended before building any model. The process of carefully minimizing the noise is called denoising. Following are some methods commonly used for removing the noise from a time series:</p><ul><li><strong>Rolling means</strong></li></ul><p>The Rolling mean is simply the mean for a window of previous observations, where the window is a sequence of values from the time series data. Mean is calculated for each ordered window. This can greatly help in minimizing the noise in time series data.</p><p>Let’s apply the rolling mean on <a href="https://www.kaggle.com/szrlee/stock-time-series-20050101-to-20171231?select=GOOGL_2006-01-01_to_2018-01-01.csv">Google Stock Price</a>:</p><pre>rolling_google = google_stock_price[&#39;Open&#39;].rolling(20).mean()<br>plt.plot(google_stock_price[&#39;Date&#39;], google_stock_price[&#39;Open&#39;])<br>plt.plot(google_stock_price[&#39;Date&#39;], rolling_google)<br>plt.xlabel(&#39;Date&#39;)<br>plt.ylabel(&#39;Stock Price&#39;)<br>plt.legend([&#39;Open&#39;,&#39;Rolling Mean&#39;])<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*fCxJo661otXxfUO6fPweZA.png" /></figure><ul><li><strong>Fourier Transform</strong></li></ul><p>Fourier Transform can help remove the noise by converting the time series data into the frequency domain, and from there, we can filter out the noisy frequencies. Then, we can apply the inverse Fourier transform to obtain the filtered time series. Let’s use Fourier transform on the Google Stock Price.</p><pre>denoised_google_stock_price = fft_denoiser(value, 0.001, True)<br>plt.plot(time, google_stock[&#39;Open&#39;][0:300])<br>plt.plot(time, denoised_google_stock_price)<br>plt.xlabel(&#39;Date&#39;, fontsize = 13)<br>plt.ylabel(&#39;Stock Price&#39;, fontsize = 13)<br>plt.legend([‘Open’,’Denoised: 0.001&#39;])<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*2b2rkPk1t188JumbBi7S_A.png" /></figure><h4><strong>Outlier Detection in Time Series</strong></h4><p>An outlier in time series refers to a sudden peak or drop in the trend line. We are not concerned with the factors causing the outliers, but certainly, there can be multiple factors. We will keep ourselves confined with the detection of outliers. Let’s take a look at the available methods for detecting the outliers:</p><ul><li><strong>Rolling Statistical Bound based approach</strong></li></ul><p>This method is most intuitive and works for almost all kinds of time series. In this method, upper and lower bounds are created based on specific statistical measures like mean and standard deviation, Z and T scores, and percentile of the distributions. For instance, we can define our upper and lower bound as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*tiNRiw0Oipb4h6BKVflDZA.png" /></figure><p>Taking the mean and standard deviation of the whole series is not advisable for outlier detection since the bound would be static in that case. The bounds should be created on a rolling basis, like considering a continuous set of observations to create bounds and then shifting to another window. This method is highly effective and simple for outlier detection.</p><ul><li><strong>Isolation Forest</strong></li></ul><p>As the name suggests, Isolation forest is a decision tree-based machine learning algorithm for anomaly detection. It works by isolating the data points on a given set of features using the decision tree’s partitions. In other words, It takes a sample out of the dataset and builds trees over that sample until each point is isolated. To isolate a data point, partitions are made randomly by selecting a split between the max and min values of that feature until each point is isolated. Random partition of features will create shorter paths in trees for the anomalous data points and thus distinguishing them from the rest of the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P8YwDuGw48GTWV1sI7DBog.png" /><figcaption>Source: Medium</figcaption></figure><ul><li><strong>K-means Clustering</strong></li></ul><p>K-means clustering is again an unsupervised machine learning algorithm frequently used to detect outliers in time series data. This algorithm looks at the data point in the dataset and groups the similar data points into K number of clusters. Anomalies are distinguished by measuring the distance of a data point to its nearest centroid. If the distance is greater than a certain threshold value, the data point is marked as an anomaly. K-Means algorithm uses the Euclidean Distances for comparison.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*mHy3NgfkqGeasIPH9nLBlA.jpeg" /></figure><h3>Possible Interview Questions</h3><p>If one is writing a project on time-series in their CV, then the interviewer can ask these possible questions from this topic:</p><ol><li>What are the ways to preprocess the time-series data, and how is it different from standard imputation methods?</li><li>What does it mean by a time-series window?</li><li>Have you heard of the Isolation forest method? If yes, then can you explain how does it work?</li><li>What is Fourier transform, and why do we need that?</li><li>What are the different methods to correct the missing values in time-series data?</li></ol><h3><strong>Conclusion</strong></h3><p>In this tutorial, we looked at some common time series data preprocessing techniques. We started with ordering the time-series observations; then, we looked at various missing value imputation techniques. We found that the time-series imputations are different from the conventional imputation techniques since we deal with an ordered set of observations. Further, we applied some noise removal techniques to the google stock price dataset and finally discussed some outlier detection methods for time series. Using all these mentioned preprocessing steps ensures high-quality data, ready for building complex models.</p><h4>Enjoy Learning! Enjoy Pre-processing! Enjoy Algorithms!</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c50f8a3e7a98" width="1" height="1" alt=""><hr><p><a href="https://medium.com/enjoy-algorithm/pre-processing-of-time-series-data-c50f8a3e7a98">Pre-processing of Time Series Data</a> was originally published in <a href="https://medium.com/enjoy-algorithm">EnjoyAlgorithms</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Boston House Price Prediction]]></title>
            <link>https://medium.com/enjoy-algorithm/boston-house-price-prediction-2b3c78672049?source=rss-ac4f401b071f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b3c78672049</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Shashank Gupta]]></dc:creator>
            <pubDate>Mon, 07 Feb 2022 12:10:58 GMT</pubDate>
            <atom:updated>2022-02-08T19:32:35.688Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QOPb_DeqDJ6TxmVFefOJzQ.jpeg" /></figure><p>The surrounding environment highly influences house prices. For instance, a house in Beverly Hills may cost you a mind-blowing 40,00,000 US Dollars. Notably, it is the home to all the famous Hollywood celebrities. On the contrary, a house in any secluded region may come at a low budget. Still, the area will be prone to crime, and standard services like the police stations, schools, grocery stores, etc., may not be available in the vicinity. There is a clear trade-off between the locality and price. Whenever we have an issue associated with an exchange, we can always use Machine Learning to find the optimal solution to the problem.</p><h4><strong>Key takeaways from this blog</strong></h4><p>After reading this blog, we would be able to answer the following questions:</p><ol><li>Why do we need Machine Learning models to solve the problem of house price prediction?</li><li>What are the factors that affect house prices?</li><li>Which machine learning models can be used to predict house prices?</li><li>Possible interview questions on this project.</li></ol><p><strong>Following are the set of features that we will use to build the machine learning model to predict house prices.</strong></p><ul><li><strong>CRIM</strong>: Per capita crime rate by town</li><li><strong>ZN</strong>: Proportion of residential land zoned for lots over 25,000 sq. ft.</li><li><strong>INDUS</strong>: Proportion of non-retail business acres per town</li><li><strong>CHAS</strong>: Charles River dummy variable (1 if tract bounds river; 0 otherwise)</li><li><strong>NOX</strong>: Nitric oxides concentration (parts per 10 million) [parts/10M]</li><li><strong>RM</strong>: Average number of rooms per dwelling</li><li><strong>AGE</strong>: Proportion of owner-occupied units built before 1940</li><li><strong>DIS</strong>: Weighted distances to five Boston employment centers</li><li><strong>RAD</strong>: Index of accessibility to radial highways</li><li><strong>TAX</strong>: Full-value property-tax rate per $10,000 [$/10k]</li><li><strong>PT-RATIO</strong>: It is the Pupil-Teacher ratio by the town</li><li><strong>B</strong>: The result of the equation B=1000(Bk — 0.63)² where Bk is the proportion of blacks by town</li><li><strong>L-STAT</strong>: Percentage lower status of the population</li><li><strong>MEDV</strong>: Median value of owner-occupied homes in $1000s</li><li>We can see that the input attributes have a mixture of units.</li></ul><p>Probably in the future, you will consider all these factors before fixing a deal.</p><h4>Data Analysis</h4><p>Our objective is to build a machine learning model to predict house prices. However, before diving into the prediction task, we want to perform some exploratory data analysis to gain a basic understanding of the house price data, followed by feature selection and engineering. We are going to use the <a href="https://www.kaggle.com/vikrishnan/boston-house-prices">Boston house price dataset</a> on Kaggle for this analysis. MEDV (Median House Price) is our target variable which we want to predict using the given set of independent features.</p><p>Let’s take a look at the data:</p><pre>import pandas as pd</pre><pre>house_price = pd.read_csv(&#39;boston.csv&#39;)<br>house_price.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*xJQ7ap1MEZjFOA5dALn79Q.png" /><figcaption>House Price Data</figcaption></figure><p>Our dataset contains 13 independent features. Let’s see if we have some collinear features in the dataset. Such features are redundant and can be removed for ease of analysis. Let’s check the correlation:</p><pre>import seaborn as sns<br>import matplotlib.pyplot as plt</pre><pre>plt.figure(figsize=(20, 10))<br>cmap = sns.diverging_palette(500, 10, as_cmap=True)<br>sns.heatmap(house_price.corr().abs(), cmap=cmap, center=0, square=True, annot =True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*76UcNeBaFMCVoT3dwVmsxg.png" /><figcaption>Correlation Matrix</figcaption></figure><p>From the above correlation matrix, we can see that TAX and RAD are highly correlated, and any one of them can be discarded. Also, LSTAT, RM, NOX, INDUS, PRTAIO, and TAX have a correlation greater than 0.4 with MEDV, which is a good indicator for using these parameters as predictors. Let’s visualize the relationship between these features vs. Median House Price (MEDV):</p><pre>fig, axs = plt.subplots(nrows=2, ncols=4, figsize=(20,8))<br>cols = [&#39;LSTAT&#39;, &#39;INDUS&#39;, &#39;NOX&#39;, &#39;PTRATIO&#39;, &#39;RM&#39;, &#39;TAX&#39;, &#39;DIS&#39;, &#39;AGE&#39;]<br>for col, ax in zip(cols, axs.flat):<br>    sns.regplot(x = house_price[col],y = house_price[&#39;MEDV&#39;], color = &#39;red&#39;, ax=ax)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ERnetBk-01yMBbldX9pSbQ.png" /><figcaption>Scatter Plot</figcaption></figure><p>The majority of the features show a negative relationship to the house prices. Only a few features show a positive relationship.</p><p>Let’s check the Boxplot for finding the outliers, if available:</p><pre>fig, axs = plt.subplots(ncols=4, nrows=2, figsize=(10, 5))<br>index = 0<br>axs = axs.flatten()<br>for k,v in house_price.items():<br>    sns.boxplot(y=k, data=house_price, ax=axs[index])<br>    index += 1<br>plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=5.0)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*XEXVw3l-2_NdPLyNCsI6iA.png" /><figcaption>Boxplot</figcaption></figure><p>Only RM seems to have some significant outliers. Let’s remove them!</p><pre>house_price = house_price[~((house_price[‘RM’] &gt;= 8.5) | (house_price[‘RM’] &lt; 4))]</pre><p><strong>Let’s summarize our data analysis steps:</strong></p><ul><li>We used a correlation heatmap for finalizing the relevant set of features required for the analysis.</li><li>Further, we visualized the relation of independent features to the target variable Median House Price using the reg-plot. We found a majority of attributes have a negative relationship with respect to the median house price.</li><li>Finally, we used the Boxplots to confirm the presence of outliers in the dataset. However, we only found the major outliers for RM (Average room) feature. In the subsequent step, we carefully removed the outliers.</li></ul><h4>Model Building</h4><p>We want to build a model which can take house-surrounding parameters as input and return an estimated price of the house based on the above discussed independent features. We will address this problem by building a regression model. This approach will eliminate a lot of manual visits, meetings with brokers &amp; dealers, and paperwork required for estimating the price of a property. Companies like 99acres, MagicBricks, and Housing.com have already automated the house price estimation mechanism based on the surrounding parameters and housing requirements. We will be doing the same, but first, we need to select a regression model.</p><p>This is a classic regression problem where we have the independent features as input and house price as the target. We need to select a supervised regression algorithm to accomplish this task. Let’s look at some regression algorithms that can be used for predicting the house price.</p><ul><li>Linear Regression</li><li>Decision Tree Regressor</li><li>Support Vector Regressor</li><li>K-NN Regressor</li><li>Random Forest Regressor</li></ul><p>Linear Models are relatively less complex and explainable, but linear models perform poorly on data containing the outliers. Also, linear models fail to perform well on non-linear datasets. In such cases, non-linear regression algorithms Random Forest Regressor and XGBoost Regressor perform better in fitting the non-linear data.</p><p>We don’t have significant outliers in our dataset, indicating that we can use linear as well as complex models. However, the model must have the following qualities:</p><ul><li>Simple &amp; Explainable</li><li>Provides accurate predictions</li><li>Robust to concept drift and outliers</li><li>Easy to deploy</li></ul><p>We should always look for the above points in mind while selecting a regression model. For this tutorial, we will be using the Support Vector Regressor.</p><p><strong>Support Vector Regressor</strong></p><p>Support Vector Machine is a supervised machine learning algorithm that can be used for both classification and regression tasks. Support Vector Regression works on the same principle as that of an SVM. The important idea behind the SVR is to find the best-fit hyper-plane along with the optimum threshold. The optimum threshold value is the distance between the hyperplane and the boundary line. The boundary line is defined by the support vectors that lie farthest to the hyperplane. It is similar to fit the best fit line along with some threshold limits. The threshold limit is the distance between the hyperplane and the boundary line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*Ad9FXKQ4Amse2Ch0haJGTQ.png" /><figcaption>Source: ResearchGate</figcaption></figure><p>Following are some characteristics of SVR:</p><ul><li>SVR is sensitive to outliers (for Hard Margin only)</li><li>Considers outermost data points for the determination of margin</li><li>SVR is insensitive to inner data points</li><li>SVR can tackle non-linear data using the Kernel Trick</li></ul><p>Let’s implement SVR to predict the house prices:</p><pre>from sklearn.svm import SVR<br>from sklearn.preprocessing import MinMaxScaler<br>from sklearn.model_selection import train_test_split</pre><pre>target = house_price[&#39;MEDV&#39;]<br>features = house_price.drop(&#39;MEDV&#39;, axis = 1)</pre><pre>X_train, X_test, Y_train, Y_test = train_test_split(features, target, test_size=0.3)</pre><pre>scaler = MinMaxScaler(feature_range=(0, 1))</pre><pre>X_train = scaler.fit_transform(X_train)<br>X_train = pd.DataFrame(X_train)</pre><pre>X_test = scaler.fit_transform(X_test)<br>X_test = pd.DataFrame(X_test)</pre><pre># Baseline SVR Model<br>regressor = SVR(kernel = &#39;rbf&#39;)<br>regressor.fit(X_train, Y_train)</pre><pre>regressor.score(X_test, Y_test)</pre><pre># R-Squared Score: 0.705</pre><p>Implementing SVR with Hyper-Parameter Tuning:</p><pre>from sklearn.model_selection import GridSearchCV<br>from sklearn.metrics import mean_squared_error<br>from sklearn.metrics import make_scorer</pre><pre>K = 15</pre><pre>parameters = [{&#39;kernel&#39;: [&#39;rbf&#39;], &#39;gamma&#39;: [1e-4, 1e-3, 0.01, 0.1, 0.2, 0.5, 0.6, 0.9],&#39;C&#39;: [1, 10, 100, 1000, 10000]}]</pre><pre>print(&quot;Tuning hyper-parameters&quot;)</pre><pre>scorer = make_scorer(mean_squared_error, greater_is_better=False)<br>svr = GridSearchCV(SVR(epsilon = 0.01), parameters, cv = K, scoring=scorer)<br>svr.fit(X_train, Y_train)</pre><pre>print(&quot;Grid scores on training set:&quot;)</pre><pre>means = svr.cv_results_[&#39;mean_test_score&#39;]<br>stds = svr.cv_results_[&#39;std_test_score&#39;]<br>for mean, std, params in zip(means, stds, svr.cv_results_[&#39;params&#39;]):<br>    print(&quot;%0.3f (+/-%0.03f) for %r&quot;% (mean, std * 2, params))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*wRr4agYSJdghrO41pzPKGA.png" /></figure><pre># <strong>Best parameters at C = 1000, gamma = 0.9, kernel = ‘rbf’</strong></pre><pre>regressor_tuned = SVR(kernel = &#39;rbf&#39;, C = 1000, gamma = 0.9)<br>regressor_tuned.fit(X_train, Y_train)</pre><pre>regressor_tuned.score(X_test, Y_test)</pre><pre># R-Squared Score: 0.821<br># 16.45 % Improvement in R Squared Score</pre><p>After hyper-parameter tuning, the R-Squared score jumped from 0.70 (Baseline SVR model) to 0.82 (Hyper-tuned SVR model), which is a massive 16.45% overall improvement.</p><p>Let’s visualize the residuals on the test and train set:</p><pre>plt.figure(figsize=(10,6))<br>visualizer = ResidualsPlot(regressor_tuned)<br>visualizer.fit(X_train, Y_train) <br>visualizer.score(X_test, Y_test) <br>visualizer.show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*OyjyCBoOHPVMhmFqYDn9Wg.png" /></figure><p>Residuals are centered around zero, which indicates a good fit. Also, the R-squared score indicates a reliable fit for predicting house prices.</p><h4>Industrial Use Cases</h4><h4><strong>99acres</strong></h4><p>99acres is an Indian Real Estate Property dealing company launched in 2005 for automating the Buy, Sell, rent business on properties. Over the years, it has gained the title of India’s number 1 property portal. 99acres uses regression modeling for the estimation of house valuations, rent, and land prices.</p><h4><strong>Amazon</strong></h4><p>Amazon is an American multinational tech company that focuses primarily on e-commerce and Artificial Intelligence. Amazon uses regression analysis to predict and forecast the demand for consumer goods and maintains the inventory accordingly.</p><h4><strong>Chevron</strong></h4><p>Chevron is an American multinational energy corporation. It is the second-largest oil company in America. Chevron specifically uses the Support Vector Regression to explore rock positions in the old fields and to create the 2D and 3D models as a representation of the subsoil.</p><h3>Possible Interview Questions</h3><p>Boston house price prediction is one of the highest attempted machine learning applications. One can easily find some best research works in this field. If this is present in the resume of candidates, then they can expect these questions in their data science and machine learning interviews:</p><ol><li>Do you think your model is sufficiently able to capture all the advanced factors that can affect house prices in any area?</li><li>What is the most critical parameter you think to decide the price of any house?</li><li>Why did you apply SVM? What are the problems associated with it?</li><li>Did you compare the performance of SVM with the Linear regression model?</li><li>What is a cross-correlation matrix, and how do we remove/shorten some features using that?</li><li>Tell us more about this SVM algorithm. What is Hinge loss?</li></ol><h3>Conclusion</h3><p>We started with a brief introduction to the house price prediction problem. Moving on, we discussed the features impacting the price of houses and started the data analysis. We used the correlation heatmap for selecting the relevant set of features and discarded the rest. We performed some data visualization and removed some outliers from the data. Further, we discussed the qualities of an idea regression model and selected the SVM Regression model for predicting house prices. Finally, we compared the results obtained from a baseline SVR model to a hyper-tuned SVR model and found a 16.5% improvement.</p><p>We could have used a complex model like XGBoost and Random Forest at the cost of computational time. However, the results received from SVM are highly reliable and sufficient.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b3c78672049" width="1" height="1" alt=""><hr><p><a href="https://medium.com/enjoy-algorithm/boston-house-price-prediction-2b3c78672049">Boston House Price Prediction</a> was originally published in <a href="https://medium.com/enjoy-algorithm">EnjoyAlgorithms</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sentiment Analysis For Classifying Sentiment Of Movie Reviews]]></title>
            <link>https://medium.com/enjoy-algorithm/sentiment-analysis-for-classifying-sentiment-of-movie-reviews-f6d65e7e5be2?source=rss-ac4f401b071f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6d65e7e5be2</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Shashank Gupta]]></dc:creator>
            <pubDate>Tue, 02 Nov 2021 18:59:01 GMT</pubDate>
            <atom:updated>2021-11-02T18:59:01.560Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BrUGjtWiyibUhPPQ4tOUVw.jpeg" /></figure><p>Sentiment Analysis is the use of Natural Language Processing (NLP), Text Mining, and Computational Linguistics to identify, extract, and understand the emotional inclination present in the text. With the widespread propagation of reviews, blogs, ratings, recommendations, and feedback, online opinion has turned into a gold mine for businesses looking to capture the market with their products, identify new opportunities, and manage their reputations and brand name. Sentiment Analysis has been used by almost every sector and is widely appliable to Market Research, Customer Feedback, Brand Monitoring, Voice of employees, and Social Media Monitoring.</p><h4>Key takeaways from this blog</h4><p>After completing this blog, we will have the knowledge about</p><ol><li>How sentiment analysis is being used by different industries?</li><li>Data analysis for the IMDB movie review dataset.</li><li>Different steps of text processing or data processing, including tokenization, lemmatization, word embedding, and tf-idf.</li><li>Building Light GBM model for prediction positive and negative reviews.</li><li>Twitter, and IBM use cases and how they use sentiment analysis?</li><li>Possible interview questions on this project.</li></ol><p>The conventional approach to sentiment classification involves several steps, from structuring the text data to understanding the customer sentiments. Over the years, Deep Learning has transformed Sentiment Analysis to a whole new level. With the introduction of Transformers and Transfer Learning, building a model for sentiment classification is a mere matter of minutes. However, knowing the basics of sentiment classification always comes in handy.</p><p>Let’s build a model for classifying the sentiments using the conventional approach!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ba_1s81KvlI6_vdLPjWItw.jpeg" /></figure><h4>Data Analysis</h4><p>In this tutorial, we will be using Kaggle’s <a href="https://www.kaggle.com/columbine/imdb-dataset-sentiment-analysis-in-csv-format">IMDB movie review dataset</a> for demonstration. This dataset contains more than 40,000 Reviews &amp; sentiments, and most of the reviews are described with 200 plus words in this dataset.</p><p>Let’s load the dataset!</p><pre>import pandas as pd<br>imdb_reviews = pd.read_csv(&#39;train.csv&#39;)<br>imdb_reviews.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*ka4Q1W62QdcZfSzEJkHWWA.png" /></figure><h4><strong>Text Preprocessing</strong></h4><p>Why do we need to clean the text? Unlike humans, machines lack the understanding of the unstructured text, and therefore, it becomes necessary to clean the text data before fitting any machine learning model to it.</p><p>Let’s build a text preprocessing pipeline where we will be applying the following operations to our movie review corpus:</p><ul><li>Lowering the text</li><li>Removing URLs from text</li><li>Removing Punctuations from text</li><li>Removing Stopwords from text</li><li>Correcting the misspelled words</li></ul><pre>def text_preprocessing_pipeline(corpus):<br> corpus[‘text’] = corpus[‘text’].str.lower()<br> corpus[‘text’] = corpus[‘text’].str.replace(r”http\S+”, “”, regex=True)<br> corpus[‘text’] = corpus[‘text’].str.replace(‘[^A-Za-z0–9]+’,’ ‘, regex=True)<br> corpus[‘text’] = corpus[‘text’].apply(lambda words: ‘ ‘.join(word.lower() for word in words.split() if word not in stopwords))<br> corpus[‘text’] = corpus[‘text’].apply(lambda x: str(TextBlob(x).correct()))</pre><pre>reviews = text_preprocessing_pipeline(imdb_reviews)<br>reviews.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*ieggVAHbUA-6Y_0pCZ4VDQ.png" /></figure><h4>Tokenization &amp; Lemmatization</h4><p>Tokenization is the process of breaking down the sentence into words called tokens. These tokens help in understanding the context and in the creation of vocabulary. It works by separating the words by spaces or punctuations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*lZpm-kDSPsw7Ma0uKsYmPQ.jpeg" /><figcaption>Tokenization</figcaption></figure><p>Whereas, Lemmatization helps in reducing the word to its common base root word. It takes the help of the linguistic analysis of the words. It is necessary to have detailed dictionaries which the algorithm can look through to link the form back to its root word.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JWKtkIDAZy2l4PulQL3-Zg.png" /><figcaption>Lemmatization</figcaption></figure><p>Applying tokenization and Lemmatization to our Clean Movie Reviews:</p><pre>import nltk</pre><pre>nltk.download(&#39;wordnet&#39;)<br>nltk.download(&#39;punkt&#39;)</pre><pre>w_tokenizer = nltk.tokenize.WhitespaceTokenizer()<br>lemmatizer = nltk.stem.WordNetLemmatizer()</pre><pre>def lemmatize_text(text):<br>    return [lemmatizer.lemmatize(w) for w in w_tokenizer.tokenize(text)]</pre><pre>reviews[&#39;lemmatized_tokens&#39;] = reviews[&#39;text&#39;].apply(lemmatize_text)<br>reviews.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*TtV2b7KUnLVkXY8S7UBLvQ.png" /></figure><p>Now, we have a clean dataset ready for Exploratory data analysis.</p><h4><strong>Text Exploratory Analysis</strong></h4><p>We are also interested in the most frequent words other than the stopwords but highly frequent in reviews. Let’s find those words!</p><pre>import itertools<br>import collections<br>import pandas as pd<br>import matplotlib.pyplot as plt</pre><pre>lemmatized_tokens = list(reviews[&quot;lemmatized_tokens&quot;])<br>token_list = list(itertools.chain(*lemmatized_tokens))</pre><pre>counts_no = collections.Counter(token_list)</pre><pre>clean_reviews = pd.DataFrame(counts_no.most_common(30),<br>                             columns=[&#39;words&#39;, &#39;count&#39;])</pre><pre>fig, ax = plt.subplots(figsize=(12, 8))</pre><pre>clean_reviews.sort_values(by=&#39;count&#39;).plot.barh(x=&#39;words&#39;,<br>                         y=&#39;count&#39;,<br>                         ax=ax,<br>                         color=&quot;purple&quot;)</pre><pre>ax.set_title(&quot;Most Frequently used words in Reviews&quot;)</pre><pre>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*2DLEKoGaNUAA4E6JEQMrWw.png" /></figure><p>Since our dataset contains movie reviews, the resultant words frequency plot is pretty intuitive.</p><h4>Bigrams</h4><p>A bigram is a sequence of two adjacent elements from a string of tokens, typically letters, syllables, or words. Let’s also check the highly frequent bigrams in our data.</p><pre>bigrams = zip(token_list, token_list[1:])<br>counts_no = collections.Counter(bigrams)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VlkvRrUj3CxjQy1mphNZnw.png" /></figure><p>Almost all the above bigrams make sense in our data. We could go further with trigrams, but that would not be as informative as these bigrams and unigrams.</p><h4>Visualization of Sentimental Words</h4><p>Let’s visualize the most practical words that represent positive or negative sentiment in reviews.</p><pre>import scattertext as st<br>from IPython.display import IFrame<br>from IPython.core.display import display, HTML<br>from scattertext import CorpusFromPandas, produce_scattertext_explorer</pre><pre>corpus = reviews.loc[(reviews[‘label’] == “Positive”) | (reviews[‘label’] == “Negative”)]</pre><pre>corpus = st.CorpusFromParsedDocuments(corpus.iloc[:2000,:], category_col=’label&#39;).build()</pre><pre>html = st.produce_scattertext_explorer(corpus,<br>                         category=”Positive”,<br>                         category_name=’Negative’,<br>                         not_category_name=’Positive’,<br>                         minimum_term_frequency=5,<br>                         width_in_pixels=1000,<br>                         transform=st.Scalers.log_scale_standardize)</pre><pre>file_name = ‘Sentimental Words Visualization.html’<br>open(file_name, ‘wb’).write(html.encode(‘utf-8’))<br>IFrame(src=file_name, width = 1000, height=700)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mzdn2gTKilbAwHyn3NaKpQ.png" /></figure><p>Let’s quickly summarise our findings:</p><ul><li>The red cluster represents the words that have been used in most of the positive sentiments. Words farthest from the yellow shade have even higher positive sentimental context.</li><li>On the contrary, the blue cluster represents the words that have appeared majorly in the negative sentiments. The farther they are from the yellow shade, the higher will be negative sentimental context.</li><li>The thin yellow shaded cluster represents the neutral words.</li><li>The words on the extreme right side more frequently appear in the reviews than those appearing on the extreme left.</li></ul><h4><strong>Word Embeddings</strong></h4><p>Word Embedding is a term that has been used to represent words as a numeric vector. Words are encoded in real-valued vectors such that words sharing similar meaning and context are clustered closely in vector space. In simple words, word embeddings are a form of word representation that connects the human understanding of language to that of a machine. Word embeddings are crucial for solving NLP problems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*Y6RtSmHlcfDR74QRDVa0sg.png" /><figcaption>Source: ResearchGate</figcaption></figure><p>There are several methods available for producing the word embeddings. However, their idea is primarily the same: to capture most of the contextual and semantical information. Selecting an optimal word embedding often requires empirical efforts, and generally, it is not an easy task.</p><p>Following are some popular and simple word embedding methods available for the vector representation of words:</p><ul><li>Word2Vec</li><li>GloVe</li><li>Bag-of-words</li><li>TF-IDF</li><li>ELMO (Embeddings for Language models)</li></ul><p>In this tutorial, we will keep ourselves confined with the TF-IDF Vectorizer.</p><h4><strong>TF-IDF Vectorizer</strong></h4><p>TF-IDF is a short notation for Term Frequency and Inverse Document Frequency. It is commonly used to transform the text into a meaningful representation of numeric vectors. Initially, it is an information retrieval method that relies on Term Frequency (TF) and Inverse Document Frequency (IDF) to measure the importance of a word in a document.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*HFl5amhpBamQe9TKyOeCKQ.png" /></figure><p>Term Frequency (TF) tracks the occurrence of words in a document; Inverse Document Frequency (IDF) assigns a weightage to each word in the corpus. The IDF weightage is high for infrequently appearing words and low for frequent words. This allows us to detect how important a word is to a document.</p><p>Let’s implement TF-IDF on our movie reviews:</p><pre>tfidf_converter = TfidfVectorizer(max_features=2000)<br>features = tfidf_converter.fit_transform(reviews[&#39;text&#39;]).toarray()</pre><h4><strong>Model Building</strong></h4><p>Now, we are ready to build our Sentiment Classification model, but first, we need to select a supervised classification model that satisfies our requirements.</p><p>We have a bunch of algorithms for classification tasks, and each algorithm has its pros and cons. One algorithm might fetch superior results as compared to others but might lack in terms of explainability. Even if explainability is not compromised, the deployment of such complex algorithms is a tedious task. In other words, there is a trade-off between performance, model complexity, and model explainability. An ideal algorithm must be explainable, reliable, and easy to deploy, but again, there’s nothing like a perfect algorithm.</p><p>For instance, XGBoost is a high-performance and explainable algorithm, but on the contrary, it is pretty complex and requires high computational power. On the other hand, Logistic Regression is relatively fast, easy to implement, and explainable, but the performance of logistic regression over non-linear datasets is considerably disappointing. As the number of features in the dataset progresses, Logistic Regression tends to become slower, and finally, the performance clips.</p><p>For this tutorial, we will be using the Light GBM Classifier!</p><h4><strong>Light Gradient Boosting Machine (Light GBM)</strong></h4><p>Light GBM is a gradient boosting framework similar to XGBoost that uses tree-based learning algorithms. It is designed to be distributed and efficient with the following advantages:</p><ul><li>Faster training speed and higher efficiency.</li><li>Lower memory usage.</li><li>Better accuracy.</li><li>Support of parallel and GPU learning.</li><li>Capable of large-scale handling data.</li></ul><p>Light GBM is an excellent alternative to XGBoost as it is roughly six times faster than XGBoost without compromising the performance. It can handle large datasets and requires low memory to run.</p><p>Let’s implement Light-GBM for Sentiment Classification:</p><pre>import lightgbm as lgb<br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import confusion_matrix, classification_report</pre><pre>target = reviews[&#39;label&#39;]</pre><pre>x_train, x_test, y_train, y_test = train_test_split(features, target, test_size=0.3)</pre><pre>clf = lgb.LGBMClassifier(max_depth=20,<br>                         n_estimators=25,<br>                         min_child_weight=0.0016,<br>                         n_jobs=-1)<br>clf.fit(X_train, y_train)</pre><pre>pred = clf.predict(x_test)</pre><pre>print(&quot;Test data Accuracy is :&quot;,accuracy_score(y_test , pred))<br>print(classification_report(y_test, pred))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*J6KG3jJAuSU_ZJM0y1X7gA.png" /><figcaption>Accuracy on the Testing dataset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*96ZdTSg7X4mfcPH4nefniA.png" /><figcaption>Classification Report</figcaption></figure><pre>import seaborn as sns<br>from sklearn.metrics import confusion_matrix</pre><pre>cm = confusion_matrix(y_test, pred)<br>cm_matrix = create_ticks(cm)</pre><pre>fig, ax = plt.subplots(figsize=(8, 6))<br>sns.heatmap(cm_matrix, annot=True, fmt=&#39;d&#39;, cmap=&#39;YlGnBu&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*yI4CGAP1pavvkNJB81BL8g.png" /><figcaption>Confusion Matrix</figcaption></figure><h3><strong>Industrial Use Cases</strong></h3><h4><strong>Twitter</strong></h4><p>Twitter allows businesses to engage personally with consumers. With so much data available, they have developed real-time sentiment classification models to support and manage the marketing strategies of several brands. Twitter’s Sentiment analysis allows companies to understand their customers, keep track of what’s being said about their brand and competitors, discover what is trending in the market.</p><h4>IBM</h4><p>IBM is among the few companies now using sentiment analysis to understand employee concerns, and they are also developing programs to improve the likelihood employees will stay on the job. This helps the human-resource managers figure out how workers feel about their company and where management can make changes to improve the experience of their employees.</p><h4><strong>Nielsen Holdings Inc.</strong></h4><p>Nielsen relies on Sentiment Analysis to discover the market trends and find the popularity of their customer’s products. Based on sentimental trends, they also provide consultation for building marketing strategies and campaigns.</p><h3>Possible Interview Questions</h3><p>Sentiment analysis project comes under that project category, which we can commonly find in resumes of beginners. But the important thing is that we should be prepared for upcoming questions on this topic. Some of them are:</p><ol><li>What are the steps you took to pre-process the data?</li><li>Why did you perform lemmatization instead of stemming?</li><li>How did you convert the text into the machine-readable or trainable format?</li><li>How does Light GBM work? What are the hyperparameters involved with the Light GBM model?</li><li>How can you say that your model is better, and what things can be done to improve accuracy further?</li></ol><h3><strong>Conclusion</strong></h3><p>We started with a brief introduction to the Sentiment Analysis and why it is required in the industries. Moving on, we applied a text preprocessing pipeline to our movie review dataset to remove the redundant expressions from the text. We implemented tokenization and Lemmatization to understand the context of those words used in the reviews and limit the recurring words appearing in diverse forms. Further, we performed a text exploratory analysis to understand the frequent unigrams and bigrams used in the reviews, visualize the clusters of positive, negative, and neutral words available in reviews. Finally, we applied the TF-IDF vectorizer to the processed reviews, built a Light GBM model to classify the reviews, and evaluated the performance on the testing dataset. We also looked at some industrial use-cases of Sentiment analysis.</p><p>Content Reviewer: Ravish Raj (<a href="https://medium.com/@ravishraj">https://medium.com/@ravishraj</a>)</p><p><em>Originally published at EnjoyAlgorithms website: </em><a href="https://www.enjoyalgorithms.com/blog/sentiment-analysis-using-machine-learning">https://www.enjoyalgorithms.com/blog/sentiment-analysis-using-machine-learning</a>/</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6d65e7e5be2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/enjoy-algorithm/sentiment-analysis-for-classifying-sentiment-of-movie-reviews-f6d65e7e5be2">Sentiment Analysis For Classifying Sentiment Of Movie Reviews</a> was originally published in <a href="https://medium.com/enjoy-algorithm">EnjoyAlgorithms</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Wine Quality Prediction Using k-NN Regressor]]></title>
            <link>https://medium.com/enjoy-algorithm/wine-quality-prediction-using-k-nn-regressor-de13087575dd?source=rss-ac4f401b071f------2</link>
            <guid isPermaLink="false">https://medium.com/p/de13087575dd</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Shashank Gupta]]></dc:creator>
            <pubDate>Tue, 02 Nov 2021 18:54:57 GMT</pubDate>
            <atom:updated>2021-11-02T18:54:57.832Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jj0qfjW_D0klkIQfhzkWLA.jpeg" /></figure><p>Data and its interpretation are helping many industries across the world. Machine learning models built over the data collected are solving some of the unsolved and challenging tasks. One of such tasks can be predicting the quality of wine along with some quantitative measurement. Judging the quality of Wine manually is really a tough task; <strong><em>even the professional Wine tasters have an accuracy of only 71%</em></strong>. Gaining the title of a Wine taster is a quite involved process. The <strong><em>Master Sommelier’s Diploma exam</em></strong> is the world’s most challenging wine tasting examination, and <strong><em>only 200 people had passed</em></strong> since the exam’s inception 40 years ago. With the current advancements in Machine Learning and Artificial Intelligence, predicting the quality of wine is a mere matter of minutes if we have all the required parameters.</p><h4>Key takeaways from this blog</h4><p>After reading this blog, we would be able to get insights of:</p><ol><li>Why do we need Machine Learning models to solve the problem of wine quality assessment?</li><li>What are the factors that affect wine quality?</li><li>Which machine learning models can be used to predict wine quality?</li><li>Some of the industry-based applications of the k-NN algorithm.</li><li>Possible interview questions on this project.</li></ol><h4>Let’s take a look at the available Wine Parameters:</h4><ul><li><strong>Fixed acidity:</strong> Nonvolatile, volatile acids of Wine(do not evaporate readily)</li><li><strong>Volatile acidity:</strong> The amount of acetic acid in wine</li><li><strong>Citric acid:</strong> Adds flavor to wine and found in small quantity</li><li><strong>Residual sugar:</strong> Sugar content after fermentation stops</li><li><strong>Chlorides:</strong> Residual Salt in the wine</li><li><strong>Free sulfur dioxide:</strong> The free form of SO2 exists in equilibrium between molecular SO2 (as a dissolved gas) and bisulfite ion; it prevents microbial growth and the oxidation of wine</li><li><strong>Total sulfur dioxide:</strong> Amount of free and bound forms of S02</li><li><strong>Density:</strong> The density of a substance is its mass per unite volume</li><li><strong>PH:</strong> Describes how acidic or basic a substance is on a scale from 0 to 14</li><li><strong>Sulfates:</strong> a wine additive that can contribute to sulfur dioxide gas (S02) levels</li><li><strong>Alcohol:</strong> Percentage alcohol content in the wine</li><li><strong>Quality:</strong> Score between 0 and 10</li></ul><p>Now that we have a basic understanding of parameters let’s dive into the data analysis.</p><h4><strong>Exploratory Data Analysis</strong></h4><p>In this blog, we are going to use the Kaggle <a href="https://www.kaggle.com/uciml/red-wine-quality-cortez-et-al-2009">Red Wine Quality Dataset</a>. It contains 1600 rows of unique red wines. This dataset is interesting because the problem can be interpreted in two ways:</p><ul><li><strong>Regression:</strong> If we consider the target variable as a continuous variable.</li><li><strong>Classification:</strong> If we consider the target variable as a discrete variable.</li></ul><blockquote>We will keep ourselves confined by approaching this problem as a Regression Task.</blockquote><p>Let’s load the data and take a look!</p><pre>import pandas as pd<br>wine_quality = pd.read_csv(&#39;winequality-red.csv&#39;)<br>wine_quality.head(5)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aX9xqqFctyiIt7rUDG8Kfg.png" /></figure><p>As we can see, almost all the parameters have float data type except for quality, which is also our target variable. Since all the independent features are continuous, we might as well learn something from the distributions. A distribution plot depicts the variation in the data distribution. Let’s plot the distribution for each variable using the Seaborn library.</p><pre>fig = plt.figure(figsize = [20,10])<br>cols = wine_quality.columns<br>cnt = 1<br>for col in cols :<br> plt.subplot(4,3,cnt)<br> sns.distplot(wine_quality[col],hist_kws=dict(edgecolor=”k”, linewidth=1,color=’blue’),color=’red’)<br> cnt+=1<br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ojscumQXLSnbCR_w9cy46g.png" /></figure><p>The majority of the distributions are approximately <strong>normal</strong>, while others have some skewness. The wine quality scores 5 and 6 are frequent than others.</p><h4>Interdependency of parameters</h4><p>We also need to understand the inter-dependency of parameters over each other. A correlation plot would be helpful in the visualization of such dependencies. Let’s plot the correlation heat map for understanding the dependencies!</p><pre>cmap = sns.diverging_palette(500, 10, as_cmap=True)<br>sns.heatmap(wine_quality.corr(), cmap=cmap, center=0, square=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*UuJqnd66twBYLHFGNhCJng.png" /></figure><p>From the above correlation heat-map, we can infer that the wine quality is positively correlated with the alcohol content and sulfates. On the contrary, Volatile acidity has a considerable negative correlation with Volatile acidity. It is reasonable that a lower level of acidity is favored in quality testings.</p><p>Let’s confirm the above-mentioned relationship using the reg-plots.</p><pre>fig, axs = plt.subplots(nrows=1, ncols=3, figsize=(20,5))<br>cols = [‘volatile acidity’, ‘alcohol’, ‘sulphates’]<br>for col, ax in zip(cols, axs.flat):<br>    sns.regplot(x = wine_quality[col],y = wine_quality[“quality”], color = ‘purple’, ax=ax)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V6kxV3bN1VdG7o5AS122jg.png" /></figure><p>Wine Quality has a confirmed negative relationship with Volatile acidity and a positive relationship with alcohol and sulfates.</p><p>Let’s dive deeper into the details by visualizing the dependency between Wine Quality and our numeric variables of interest (Independent Feature).</p><pre>cols = wine_quality.columns<br>cnt = 1<br>for col in cols :<br> plt.subplot(4,3,cnt)<br> sns.boxplot(x=”quality”,y=col,data=wine_quality,palette=”coolwarm”)<br> cnt = cnt + 1<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6KkuFSczXmaYrmayCvRABw.png" /></figure><p><strong>Let’s summarise our findings from the above boxplots:</strong></p><ul><li>Highly Rated Wines has comparatively higher Alcohol, Citric Acid, and Sulphates.</li><li>On the contrary, Wines with high volatile acidity, density, and pH are low in quality.</li><li>Wines Quality has no significant relationship with total sulfur dioxide, free sulfur dioxide, chlorides, residual sugar, and fixed acidity.</li></ul><h4><strong>Model Building</strong></h4><p>Assessing a wine manually is a tedious task and requires an experienced practitioner to evaluate the quality. We will address this problem by building a regression model that will take wine parameters as input and return a predicted quality score. Through this approach, we aim to eliminate the manual tasting and scoring process. To accomplish this task, we need to select a regression algorithm that suffices our requirements.</p><p>Following are some regression algorithms that can be used for predicting The Red Wine Quality.</p><ul><li>Linear Regression</li><li>Decision Tree Regressor</li><li>Support Vector Regressor</li><li>k-NN Regressor</li><li>Random Forest Regressor</li></ul><p>Linear Models are relatively less complex and explainable, but linear models perform poorly on data containing the outliers. Also, linear models fail to perform well on non-linear datasets. In such cases, non-linear regression algorithms Random Forest Regressor and XGBoost Regressor perform better in fitting the nonlinear data.</p><blockquote>Which algorithm is best suited for our use case?</blockquote><p>We don’t have significant outliers in this data, indicating that we can use linear as well as complex models. However, the model should have the following qualities:</p><ul><li>Simple and explainable</li><li>Provides accurate predictions</li><li>Robust to concept drift and outliers</li></ul><p>Keeping all the above-mentioned points in mind, we need to select a regression model. For this tutorial, we will be using the <strong>k-NN Regressor</strong>.</p><h4><strong>K Nearest Neighbors</strong> <strong>Regressor</strong></h4><p>k-NN Algorithm (K Nearest Neighbors) is a supervised machine learning algorithm that can solve classification and regression tasks. It is extensively used in statistical estimations and even in pattern recognition during the early 1970s. The k-NN algorithm uses feature similarity to predict the values of any new data points. It estimates the value of a data point by taking out the average of ‘K’ closest values in the euclidean space. The most commonly used method for calculating the distance between two data points is known as Euclidean Distance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OG_Wj1Nejhmrx8t-gUjhsg.png" /><figcaption>Source: Researchgate</figcaption></figure><p>Before implementing the k-NN Regressor, we need to scale the features as this algorithm demands homogenous features. We measure the distance between the pair of samples, which are influenced by the measurement units. To avoid this, we should normalize the data before implementing k-NN.</p><p>This algorithm has only one hyperparameter, the value of <strong>K,</strong> which indicates the count of samples that will be treated as the nearest neighbors. One way to find the optimum value of K is to derive a plot between the error obtained on the test set and K denoting values. Finally, choose the K corresponding to the minimum error rate.</p><p><strong>Let’s implement the k-NN Regressor:</strong></p><pre>from sklearn import neighbors<br>from sklearn.preprocessing import MinMaxScaler<br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import mean_squared_error</pre><pre>target = wine_quality[‘quality’]<br>features = wine_quality.drop(&#39;quality&#39;, axis = 1)</pre><pre>X_train, X_test, Y_train, Y_test = train_test_split(features, target, test_size=0.3)</pre><pre>scaler = MinMaxScaler(feature_range=(0, 1))</pre><pre>X_train = scaler.fit_transform(X_train)<br>X_train = pd.DataFrame(X_train)</pre><pre>X_test = scaler.fit_transform(X_test)<br>X_test = pd.DataFrame(X_test)</pre><pre>rms_error = []</pre><pre>for K in range(1,75):<br>    model = neighbors.KNeighborsRegressor(n_neighbors = K)<br>    model.fit(X_train, Y_train)  <br>    pred = model.predict(X_test) <br>    error = mean_squared_error(Y_test, pred, squared=False)<br>    rms_error.append(error, K)</pre><pre>x = np.linspace(1,75, num = 75)<br>y = rms_error</pre><pre>fig, ax = plt.figure(figsize = [8,5])<br>ax.plot(x,y)<br>annot_optimum(x,y)<br>plt.xlabel(&#39;K - Values&#39;)<br>plt.ylabel(&#39;RMSE Error&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*m_5cQ6syOa3-91R4eTseVg.png" /></figure><p>We found an optimum Model at K = 27 where the RMS Error is minimum. Our dataset was quite small, which enabled us to find the optimum K; As the dataset grows, the speed of the k-NN algorithm declines very fast, which is a limitation of this algorithm.</p><h4><strong>Pros and Cons of KNN Regressor</strong></h4><p><strong>Pros:</strong></p><ul><li>Intuitive and Simple</li><li>Only one hyper-parameter to tune</li><li>Efficient method for small datasets.</li><li>Constantly Improves with new training data</li><li>Can be used for both Classification &amp; Regression</li></ul><p><strong>Cons:</strong></p><ul><li>Requires feature scaling</li><li>Sensitive to Outliers</li><li>No Capability to handle missing values</li><li>Requires higher space complexity as well as higher time complexity</li></ul><h4><strong>Application of K Nearest Neighbors Algorithm</strong></h4><p><strong>HEINEKEN N.V</strong></p><p>Heineken is second the second largest producer of Beer in the world. However, they also own Zoetermeer Winery for wine production. Heineken relies on Regression analysis to keep track of the quality of their wine. As discussed above, even professional wine tasters are just 71% accurate in determining the quality of Wine.</p><p><strong>GRAMMARLY, INC.</strong></p><p>Grammarly is a cross-platform cloud-based writing assistant that reviews spelling, grammar, punctuation, clarity, engagement, and delivery mistakes. For categorizing similar sentences and textual documents, Grammarly relies on the KNN classification algorithm.</p><p><strong>NETFLIX</strong></p><p>Netflix uses the KNN Algorithm to categorize similar content-based shows. Netflix also uses KNN as a Recommendation Engine to recommend similar items; they compare the set of users who like each item — when a similar set of users like two different items, the items themselves are similar!</p><h4>Possible Interview Question</h4><p>Based on this project, the following questions can be asked in any machine learning interview:</p><ol><li>Is this problem statement a classification or regression problem?</li><li>What modifications do we need to do to change regression to classification and vice-versa?</li><li>Why k-NN? How did you decide the value of k?</li><li>Why is k-NN very slow? Can we improve the performance of k-NN?</li><li>What is the evaluation metric for your model? Did you compare your results with existing techniques?</li></ol><h4><strong>Conclusion</strong></h4><p>We started with a brief introduction to Wine Quality Tasting and problems in the manual Wine tasting approach. Moving on, we discussed the impact of each parameter and started the data analysis. Based on the correlation heat-map, we found out the most significant parameters. We further confirmed their impact on Wine Quality using Boxplots and Regplots. Finally, we built a K-Nearest Neighbors regression model to predict the Quality of Wine and looked at the pros and cons of using the k-NN Regressor model. We could have approached this problem as a Multiclass classification task.</p><p><strong>Enjoy Learning! Enjoy Algorithms!</strong></p><p>Content Reviewer: Ravish Raj (<a href="https://medium.com/@ravishraj">https://medium.com/@ravishraj</a>)</p><p><em>Originally published at EnjoyAlgorithms website: </em><a href="https://www.enjoyalgorithms.com/blog/wine-quality-prediction">https://www.enjoyalgorithms.com/blog/wine-quality-prediction</a>/</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de13087575dd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/enjoy-algorithm/wine-quality-prediction-using-k-nn-regressor-de13087575dd">Wine Quality Prediction Using k-NN Regressor</a> was originally published in <a href="https://medium.com/enjoy-algorithm">EnjoyAlgorithms</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Car Resale Value Prediction Using Random Forest Regressor]]></title>
            <link>https://medium.com/enjoy-algorithm/car-resale-value-prediction-using-random-forest-regressor-6ea3f790033d?source=rss-ac4f401b071f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ea3f790033d</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[daya-sceince]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Shashank Gupta]]></dc:creator>
            <pubDate>Tue, 02 Nov 2021 18:50:43 GMT</pubDate>
            <atom:updated>2021-11-02T18:50:43.594Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KKPft3rUMqVMqQ6-6PwRbw.jpeg" /></figure><p>Leading organizations are collecting tons of data every day to derive business decisions and solutions from it. With this huge amount of data, demand for Data Scientists and Data analysts is massively increasing. Machine Learning and Artificial Intelligence are transforming the world for a better tomorrow. Data is the new <strong>“oil”</strong> of this 21st century, and Machine Learning is the technology built over it. Let’s take a moment to understand the trending technological fields via the <strong>Gartner Hype</strong> curve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5qPgAXYH9YLmJXrIeiVo1g.png" /><figcaption>Gartner Hype Cycle</figcaption></figure><p>Nowadays, Machine Learning and Artificial Intelligence are applicable in almost every sector. Companies are adopting smart AI solutions in their product to eliminate manual interventions. Let’s keep ourselves confined to cars, and we will see how it has changed the driving experiences.</p><h4>Application of Machine Learning in the Automotive Industry</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZFAOfzT3e59Olp8n-0d3hg.jpeg" /></figure><p>In the automotive industry, machine learning is most often associated with product innovations. More than <strong>78 %</strong> of automotive companies invest in Machine Learning to regularly improve their user experience.</p><p>Let’s take a look at such available solutions:</p><p><strong>Autonomous Cars</strong>: Companies like Tesla has already implemented the self-driving feature in their cars. Tesla relies on its complex Computer Vision Algorithms and Sensors to gain full control over roads. Machine Learning allows self-driving cars to adapt to changing road conditions instantaneously.</p><p><strong>Real-Time Car Parking</strong>:<strong> </strong>There is a tremendous increase in the number of vehicles, and with the increasing number of cars, parking problems arise. Smart Parking Systems has been addressing such problems by leveraging the power of Machine Learning and IoT devices. The system minimizes human intervention and saves time, money, and energy.</p><p><strong>Preventive Maintenance Indicator</strong>: Every durable utility requires some timely maintenance; cars are no exception! A car requires adequate oil and coolant levels, air filter cleaning, and optimum tire pressure. ML and IoT-based Predictive Maintenace models help in keeping track of such requirements.</p><p><strong>Root Cause Analysis: </strong>Car Servicing companies use Machine Learning based systems for root cause analysis of car break-down events. These systems can analyze a huge stream of historical and current information, find anomalies and invisible patterns, and draw conclusions about a certain breakdown.</p><p>These are some applications of Machine Learning in the Automotive industry. However, In this blog, we will tackle a relatively simpler problem that is predicting the resale value of used cars using Regression analysis.</p><p>Now, let’s start by understanding the problem statement!</p><h4>Understanding Problem Statement</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HU_GhiVfwECwEOTHyosl2A.png" /></figure><p>Machine Learning has become a tool used in almost every task that requires estimation. Companies like Cars24 and Cardekho.com uses Regression analysis to estimate the used car prices. Now, think of ourselves as a competitor of Cars24, and we are required to build a model to estimate the price of used cars. The model should take car-related parameters and output a selling price.</p><p>The selling price of a used car depends on certain features as mentioned below:</p><ul><li>Fuel Type</li><li>Manufacturing Year</li><li>Miles Driven</li><li>Number of Historical Owners</li><li>Maintenance Record</li></ul><p>This is a supervised learning problem and can be solved using regression techniques. We need to predict the selling price of a car based on the given car features. Supervised Regression problems require labeled data where our target or dependent variable is the selling price of a car. All other features are independent variables.</p><p>Following are some regression algorithms that can be used for predicting the selling price.</p><ul><li>Linear Regression</li><li>Decision Tree Regressor</li><li>Support Vector Regressor</li><li>KNN Regressor</li><li>Random Forest Regressor</li></ul><p>Linear Models are relatively less complex and explainable, but linear models perform poorly on data containing the outliers. Linear models fail to perform well on non-linear datasets. In such cases, non-linear regression algorithms Random Forest Regressor and XGBoost Regressor perform better in fitting the nonlinear data.</p><p>In this tutorial, we will use Random Forest Regressor for predicting the selling price of cars. Our data contains some outliers, and treating them is entirely possible, but the performance of nonlinear regression models is insensitive to outliers.</p><h3><strong>Data Analysis</strong></h3><p>This section performs the Selling price prediction using a dataset consisting of <strong>8,128</strong> used car details. This dataset is prepared by Cardekho.com and available on <a href="https://www.kaggle.com/nehalbirla/vehicle-dataset-from-cardekho">Kaggle</a>.</p><pre>import pandas as pd</pre><pre>cars = pd.read_csv(&quot;car_data.csv&quot;)<br>cars.head(5)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bx1CjF_u0M5c-T00S4QEuA.png" /></figure><p>We have some categorical objects as well as continuous features here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4AqgKmw_rPdtxSjhYJCIHA.png" /></figure><h4><strong>Price Distribution for Different Fuel Type Cars</strong></h4><p>Let’s visualize the price of cars versus the car fuel type.</p><pre>sns.kdeplot(cars.loc[(cars[‘fuel’]==label), ‘selling_price’], color=clr, shade=True, label=label) </pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*TH8Allz1-wPI9pBqYk-fRg.png" /><figcaption>Selling Price Distribution for Different Fuel Type Cars</figcaption></figure><p><strong>Insights:</strong> Diesel Fuel type cars are generally expensive than petrol cars; the above plot supports our intuition. Gas fuel-type cars are relatively cheaper. CNG cars have a slight advantage over LPG cars in terms of fuel consumption and storage, and thus, the price of CNG cars is relatively higher than LPG cars.</p><h4><strong>Correlation Matrix</strong></h4><p>Visualizing the correlations is an effective way of determining the dependencies. In the given plot, the selling price has a high correlation with the manufacturing year, engine, max power, and transmission. The Engine and Manufacturing year has the same approximate correlation, so we can select any one of them in the final set of features.</p><pre>sns.heatmap(data = cars.corr(), cmap=”YlGnBu”, square=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*o3Hrafq_ImCSWXDLOpOmhA.png" /><figcaption>Correlation Heatmap</figcaption></figure><h4><strong>Pair Plot</strong></h4><p>A pairs plot allows us to see both distributions of single variables and relationships between two variables. Pair plots are a great method to identify trends for follow-up analysis and, fortunately, are easily implemented in Python!</p><pre>sns.pairplot(cars[[“selling_price”, “km_driven”, “engine”, “mileage”, “max_power”, “owner”]], hue=”owner”)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SjWEg2qzrBC81xRWeW-06A.png" /><figcaption>Pair Plot</figcaption></figure><p>As ownership is increasing, almost all the parameters are decreasing. For instance, the mileage of cars owned by the first owner is relatively higher than subsequent owners. The same goes for max power, engine, and km driven. This is also very intuitive!</p><p>Scatter plots in pair plots also help in the visualization of Outliers. Our data contains some minor outliers that we can safely ignore.</p><h3><strong>Random Forest Regression</strong></h3><p>Random Forest is a supervised learning algorithm that uses an ensemble learning approach for regression and classification. The main principle behind the ensemble methods is that<strong> Weak learners can form strong learners</strong>. Random Forest operates by constructing multiple decision trees at training time. These decision trees are independently trained on bootstrapped datasets. The final predicted value is calculated by taking the mean of predictions by all the individual trees.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*1ijC36UtRujF_RYkOMsbHQ.png" /></figure><h4><strong>Fitting the Model</strong></h4><p>Before building the model, we need to split the dataset into training and testing sets. We will make use of this test set for evaluating the performance of the model.</p><pre>from sklearn.ensemble import RandomForestRegressor<br>from sklearn.model_selection import train_test_split</pre><pre>target = cars[&#39;selling_price&#39;]<br>features = cars[cars.columns.difference([&#39;selling_price&#39;])]</pre><pre>#---Creating the training and testing dataset<br>X_train, X_test, Y_train, Y_test = train_test_split(features, target, test_size=0.3)</pre><pre>#---Loading the baseline Random Forest Regressor <br>rf = RandomForestRegressor()</pre><pre>#---Fitting the data over training set<br>rf.fit(X_train, Y_train)</pre><pre>#---Evaluating the performance over testing set<br>rf_confidence = rf.score(X_test, Y_test)<br>print(&quot;rf confidence: &quot;, rf_confidence)</pre><pre># rf confidence:  0.96997</pre><h4>Performance Evaluation</h4><p>In statistics, the coefficient of determination a.k.a <strong>“R squared”</strong>, is defined as the proportion of the variation in the dependent variable that is predictable from the independent variable(s). In our case, R squared is closer to 1, which indicates that the model is reliable in predicting the selling price. Random Forest is known for attaining high accuracy even without hyper-parameter tuning.</p><h4><strong>Residuals</strong></h4><p>A residual is a measure of how far away a point is vertically from the regression trend. Simply, it is the error between a predicted value and the observed actual value.</p><pre>visualizer = ResidualsPlot(rf)<br>visualizer.fit(X_train, Y_train) <br>visualizer.score(X_test, Y_test) <br>visualizer.show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*Gtph5eim0Tfm--FD7Y8juQ.png" /><figcaption>Residual Plot</figcaption></figure><p>Residuals are centered around zero, and the coefficient of determination “R-squared” is close to 1.</p><p>Pros and Cons of Random Forest Regressor —</p><h4>Pros:</h4><ul><li>Good at learning complex and non-linear relationships</li><li>Highly explainable and easy to interpret</li><li>Robust to outliers</li><li>No feature scaling is required</li></ul><h4>Cons:</h4><ul><li>Consumes more time</li><li>Requires high computational power</li></ul><h3><strong>Application of Regression Analysis</strong></h3><p><strong>CARS24</strong></p><p>CARS24 is India’s fast-growing auto-tech company to buy and sell used cars. CARS24 aligns well with what we have achieved here as they heavily rely on the Regression Algorithms to estimate the price of a used car for both selling and buying purposes. They also use regression for estimating the fuel efficiency of cars.</p><p><strong>AMERICAN EXPRESS</strong></p><p>Random Forest Regression is frequently used by American Express to predict the creditworthiness of a loan applicant. This helps the American Express lending team to make a good decision on whether to give the customer the loan or not.</p><p><strong>MERK &amp; CO.</strong></p><p>MERK uses regression analysis to identify the optimal combination of components in medicine and analyze a patient’s medical history to identify diseases. Past medical records are reviewed to establish the right dosage for the patients.</p><p><strong>Interactive Brokers LLC</strong></p><p>Interactive Brokers LLC is an American multinational brokerage firm. Their stock trading application uses Random Forest Regressor to predict the estimated loss or profit while purchasing a particular stock.</p><h3>Possible Interview Questions</h3><ol><li>How is Random Forest Classifier different from Random Forest Regressor?</li><li>What is an ensemble learning approach?</li><li>How will you ensure that your model is not getting overfitted?</li><li>What techniques will you use to cure the problem of overfitting?</li><li>Which input feature is affecting the car price the most?</li></ol><h3><strong>Conclusion</strong></h3><p>We started with understanding the use case of machine learning in the Automotive industry and how machine learning has transformed the driving experience. Moving on, we looked at the various factors that affect the resale value of a used car and performed exploratory data analysis (EDA). Further, we build a Random Forest Regression model to predict the resale value of a used car. Finally, we evaluated the performance of the model using the R squared score and Residual Plot.</p><p>We could have also used simpler regression algorithms like Linear Regression and Lasso Regression. Still, we need to make sure there are no outliers in the dataset before implementing them. Pair plots and scatter plots help visualize the outliers.</p><p>Content Reviewer: Ravish Raj (<a href="https://medium.com/@ravishraj">https://medium.com/@ravishraj</a>)</p><p><em>Originally published at EnjoyAlgorithms website: </em><a href="https://www.enjoyalgorithms.com/blog/car-resale-value-predictor-using-random-forest-regressor">https://www.enjoyalgorithms.com/blog/car-resale-value-predictor-using-random-forest-regressor</a>/</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ea3f790033d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/enjoy-algorithm/car-resale-value-prediction-using-random-forest-regressor-6ea3f790033d">Car Resale Value Prediction Using Random Forest Regressor</a> was originally published in <a href="https://medium.com/enjoy-algorithm">EnjoyAlgorithms</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Life Expectancy Prediction Using Linear Regression]]></title>
            <link>https://medium.com/enjoy-algorithm/life-expectancy-prediction-using-linear-regression-dfcab83fbff6?source=rss-ac4f401b071f------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfcab83fbff6</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[life-expectancy]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[linear-regression]]></category>
            <dc:creator><![CDATA[Shashank Gupta]]></dc:creator>
            <pubDate>Tue, 02 Nov 2021 18:45:17 GMT</pubDate>
            <atom:updated>2021-11-02T18:45:17.595Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OuIFnI-uHAicVSwIwpjpUg.jpeg" /></figure><p>Everything has an expiration date; humans are no exception either. With ongoing advancements in Machine Learning and Data Science, we can precisely predict the remaining life span of a person given the essential parameters. In this blog, we aim to explore the parameters affecting the life span of individuals living in distant countries and learn how the life span can be estimated with the help of statistical models. We will also focus on parameters that greatly impact the life span of an individual.</p><h3>Key takeaways from this blog:</h3><ul><li>Effective Data Visualization techniques</li><li>The intuition behind the Linear Regression model</li><li>Application of Linear Regression in predicting Life Expectancy</li><li>Evaluation techniques for the linear regression model</li><li>Use of life-expectancy prediction by different industries.</li></ul><p>Let’s start by understanding Life Expectancy.</p><h4><strong>What is Life Expectancy?</strong></h4><p>The term “life expectancy” refers to the number of years a person can expect to live. By definition, life expectancy is based on an estimate of the average age that members of a particular population group will be when they die. Intuitively, life expectancy depends on certain parameters, and as we work our way through the data analysis, we will analyze the factors affecting Life Expectancy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KKT_p1oxtNIYJSRPAb-aYg.png" /></figure><h3>Data Analysis</h3><p>For this demonstration, we make use of the <a href="https://www.kaggle.com/kumarajarshi/life-expectancy-who">Life Expectancy (WHO)</a> Kaggle dataset.</p><p>Let’s start by loading the data.</p><pre>import pandas as pd</pre><pre>life_exp = pd.read_csv(&#39;Life Expectancy Data.csv&#39;)<br>life_exp.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mnV7Wrg8_Z5WtXG3VXiHJA.png" /></figure><h4><strong>Distribution of Life Expectancy</strong></h4><p>The majority of lifespan lies between 45 to 90 years, with an average lifespan of 69 years.</p><pre>sns.histplot(life_exp[&#39;Life expectancy&#39;].dropna(), kde=True, color=&#39;orange&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1m_ddAUZBQUAYd9MdSiwGQ.png" /></figure><h4><strong>Correlation Heatmap</strong></h4><p>A correlation heat map is a graphical representation of a correlation matrix representing the correlation between different variables. This helps in understanding the linear dependencies of variables over each other. Correlation is always calculated between two variables, and it has a range of [-1, 1].</p><ul><li>A correlation value close to zero means the two variables are unrelated</li><li>An absolute correlation value close to 1 means the two variables are perfectly related.</li></ul><p>Let’s implement the heat map in python for dependency visualization:</p><pre>cmap = sns.diverging_palette(500, 10, as_cmap=True)<br>sns.heatmap(life_exp.corr(), cmap=cmap, center=0, annot=False, square=True);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*rxmgvJSRaaq57r7Escegjw.png" /></figure><p>Life expectancy has a considerable correlation with Adult Mortality, BMI, Schooling, HIV/AIDS, ICOR, and GDP. Following insights can be drawn based on the correlation heatmap:</p><ul><li>Life expectancy and Adult Mortality rates have a high negative correlation, which is also anticipated.</li><li>BMI has a positive correlation with Life expectancy.</li><li>GDP also has a positive correlation with Life expectancy, which can be inferred that as the country&#39;s GDP increases, the life expectancy also increases.</li><li>Not surprisingly, Schooling years have a high positive correlation with Life expectancy. Proper schooling leads to the adoption of healthy habits and discipline.</li></ul><blockquote>What is adult mortality?</blockquote><p>The adult mortality rate is shown in the probability that those who have reached age 15 will die before age 60 (shown per 1,000 persons).</p><pre>fig = px.scatter(to_bubble, x=&#39;GDP&#39;, y=&#39;Life expectancy&#39;,<br>                 size=&#39;Population&#39;, color=&#39;Continent&#39;,<br>                 hover_name=&#39;Country&#39;, log_x=True, size_max=40)<br>fig.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ui0MJfRqu1_nPiIbqs6duQ.png" /></figure><p>This bubble plot is very informative in understanding the trend of life expectancies for different continents. The size of the bubble defines the population in the respective countries. Following are the safe inferences we can make based on the bubble plot:</p><ul><li>African countries have a lower life expectancy as compared to other continents.</li><li>The majority range of life expectancy lies between 60 to 75 years for Asian countries. Asian countries also bear high populations.</li><li>South America and North America have similar life expectancy trends.</li><li>European countries having high GDP has a remarkable high life expectancy.</li></ul><p>Let’s analyze the impact of GDP for different continents versus Life expectancy.</p><pre>for continent, ax in zip(set(life_exp[&#39;Continent&#39;]), axs.flat):<br>    continents = life_exp[life_exp[&#39;Continent&#39;] == continent]<br>    sns.regplot(x = continents[&#39;GDP&#39;],y = continents[&#39;Life expectancy&#39;], color = &#39;red&#39;, ax = ax).set_title(continent)</pre><pre>plt.tight_layout()    <br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*agi5gWX_NLiKdI6wNhcVlw.png" /></figure><p>High GDP has a strong positive impact on life expectancy!</p><p>In other words, If someone is residing in a developed country that has a high GDP, then his life expectancy is expected to be relatively higher than a person living in a developing country.</p><blockquote>What is ICOR (Income Composition of Resources)?</blockquote><p>ICOR is the measure of how good a country is at utilizing its resources. ICOR is graded between 0 to 1, and higher ICOR indicates optimal utilization of available resources. ICOR has a considerably high correlation with Life expectancy. Let’s visualize the impact of ICOR on Life expectancy continent-wise.</p><pre>for continent, ax in zip(set(life_exp[&quot;Continent&quot;]), axs.flat):<br>    continents = life_exp[life_exp[&#39;Continent&#39;] == continent]<br>    sns.regplot(x = continents[&#39;Income composition of resources&#39;],y = continents[&quot;Life expectancy &quot;], color = &#39;blue&#39;, ax = ax).set_title(continent)</pre><pre>plt.tight_layout()    <br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qq67O2uSYTHDeH6lPEwwKA.png" /></figure><p>As expected, higher ICOR yields higher Life expectancy. If a country utilizes its resources productively, it is more likely to see its citizens live longer than expected.</p><h4><strong>Life Expectancy Prediction</strong></h4><p>Now the question comes, Is there any way to predict the Life expectancy based on the discussed 22 independent features? Yes, but first, we need to finalize a supervised regression algorithm that fits our task.</p><p>We have a bunch of algorithms for regression tasks, and each algorithm has its pros and cons. One algorithm might fetch superior results as compared to others but might lack in terms of explainability. Even if explainability is not compromised, the deployment of such complex algorithms is a tedious task. In other words, there is a trade-off between performance, model complexity and, model explainability. An optimal algorithm must be explainable, accurate, and easy to deploy, but there’s nothing like an ideal algorithm.</p><p>For instance, Linear Regression is a comparatively simple and explainable algorithm. Deployment of Linear Regression requires minimal efforts, but on the contrary, it lacks accuracy when the data is non-linear. Complex algorithms perform better on non-linear datasets, but then the model lacks explainability.</p><p>Let’s proceed with Linear Regression for this task.</p><h4><strong>Linear Regression</strong></h4><p>Linear Regression is a regression algorithm with a linear approach. It’s a supervised regression algorithm where we try to predict a continuous value of a given data point by generalizing the data we have in hand. The linear part indicates the linear approach for the generalization of data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*vpmsQEjv2Lfwpa7h-P116A.png" /></figure><p>The idea is to predict the dependent variable (Y) using a given independent variable (X). This can be accomplished by fitting a best fit line in the data. A line providing the least sum of residual error is the best fit line or regression line.</p><blockquote>What is a residual error?</blockquote><p>A residual error is a measure of how far away a point is vertically from the regression line. Simply, it is the error between a predicted value and the observed actual value. A line providing the least sum of residual error is the best fit line or regression line.</p><p>Let’s predict Life expectancy by using Linear Regression.</p><p>Before building the model, we need to split the dataset into training and testing sets. We will make use of this test set for evaluating the performance of the model.</p><pre>from sklearn.model_selection import train_test_split<br>from sklearn.linear_model import LinearRegression</pre><pre>target = life_exp[&#39;Life expectancy&#39;]<br>features = life_exp[life_exp.columns.difference([‘Life expectancy‘, &#39;Year&#39;])]</pre><pre>#----- Splitting the dataset -----#<br>x_train, x_test, y_train, y_test = train_test_split(pd.get_dummies(features), target, test_size=0.3)</pre><pre>#----- Linear Regression -----#<br>lr = LinearRegression()</pre><pre>#----- Fitting model over training data -----#<br>lr.fit(x_train, y_train)</pre><pre>#----- Evaluating the model over test data -----#<br>lr_confidence = lr.score(x_test, y_test)<br>print(&quot;lr confidence: &quot;, lr_confidence)</pre><pre>#lr confidence:  0.9538309850283277</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*uy7ZnKRVf9FHoDRcgeqVAw.png" /></figure><p>The coefficient of determination R-square came out to be closer to 1, which indicates the model optimally predicts the Life expectancies.</p><p>For validation of the model, let’s check the distribution of residuals.</p><pre>sns.histplot(residuals, kde=True, color=&quot;orange&quot;)<br>plt.title(&#39;Residual Plot&#39;)<br>plt.xlabel(&#39;Residuals: (Predictions - Actual)&#39;)<br>plt.ylabel(&#39;Density&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7_MibZPmMDFx_L4SRQBprQ.png" /></figure><p>Residual distribution is approximately normal, having a mean close to zero. This is exactly what we are looking for.</p><p>Let’s visualize the residuals in a scatter plot!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*fXseBOTGyJa7_zf6MCtbDQ.png" /></figure><p>Residuals are centered around zero, and the coefficient of determination R-square is close to 1. Close to 1 R-squared value indicates a good fit over the test dataset. With these results, we can conclude that our model is highly efficient in predicting Life Expectancy.</p><h3><strong>Industrial Application of Linear Regression</strong></h3><p><strong>WHO (Public Health Standards)</strong></p><p>World Health Organization (WHO) keeps track of the health status as well as many other related factors for all countries. They are responsible for monitoring the public health risk, promoting human health, and coordinating responses to health emergencies. WHO highly relies on statistical algorithms like Linear Regression for studying the Life expectancy and impact of pandemics over life-span.</p><p><strong>Blue Shield of California (Healthcare Insurance)</strong></p><p>Blue Shield of California(BSOC) is at the forefront of innovation in the healthcare domain. BSOC is a non-profit health insurance organization focused on providing the best possible medical treatment and insurance plans. <strong>BSOC takes advantage of the Linear Regression model for the estimation of medical expenses based on insurance data.</strong></p><p><strong>JPMorgan Chase &amp; Co. (Finance)</strong></p><p>JPMorgan Chase is a global leader in financial services offering solutions to the world’s most important corporations and government institutions. <strong>JPMC has generalized the use of Linear Regression in their Capital Asset Pricing Model (CAPM)</strong>, where risky assets are merged with non-risky assets to reduce the unsystematic risk. Moreover, JPMC uses Linear Regression for Forecasting and Financial Analysis.</p><p><strong>Johnson &amp; Johnson (Pharmaceutical)</strong></p><p><strong>Johnson &amp; Johnson (J&amp;J)</strong> is an American multinational corporation that develops medical devices, pharmaceuticals, and consumer packaged goods. J&amp;J uses Linear Regression for estimating the remaining shelf life of medicine stocks.</p><p><strong>Walmart (Retail Corporation)</strong></p><p>Walmart<strong> </strong>is a renowned retailing corporation that operates as different hypermarkets, departmental stores, grocery stores, and garments buying houses. Walmart relies on Regression analysis for sales forecasting and better decision-making.</p><h3>Possible Interview Questions</h3><p>Life expectancy prediction is one of the most popular machine learning projects that interviewers commonly find in fresher resumes. So, the possible interview questions that interviewers can ask are:</p><ol><li>How did you approach the Linear Regression? Why not more sophisticated algorithms for higher accuracy?</li><li>What is R_Square? How does it reflect the accuracy of your model? What is the range of R_Square?</li><li>What things can be done further to increase this machine learning model performance?</li><li>What are the industrial sectors where this machine learning project can be beneficial?</li><li>Can you name some hyperparameters involved in this project?</li></ol><h3><strong>Conclusion</strong></h3><p>We started with understanding Life Expectancy and learned the factors affecting it. We further visualized the affecting parameters and correlated them to derive inferences. Finally, we covered the Linear Regression and implemented it to predict Life expectancy.</p><p>One can extend their life span by adopting a healthy lifestyle, proper education, and getting vaccinated. Of course, Demographic location plays an important role. In our analysis, we found that people living in Europe have a higher lifespan than other continents. A country’s GDP and Income composition affect Life Expectancy more broadly.</p><p>Some parameters like pollution and environmental index have been missing in this analysis and are expected to be highly related to Life Expectancy.</p><p>Content Reviewer: Ravish Raj (<a href="https://medium.com/@ravishraj">https://medium.com/@ravishraj</a>)</p><p><em>Originally published at EnjoyAlgorithms website: </em><a href="https://www.enjoyalgorithms.com/blog/life-expectancy-prediction-using-linear-regression">https://www.enjoyalgorithms.com/blog/life-expectancy-prediction-using-linear-regression</a>/</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfcab83fbff6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/enjoy-algorithm/life-expectancy-prediction-using-linear-regression-dfcab83fbff6">Life Expectancy Prediction Using Linear Regression</a> was originally published in <a href="https://medium.com/enjoy-algorithm">EnjoyAlgorithms</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>