<?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 Davide Valiante on Medium]]></title>
        <description><![CDATA[Stories by Davide Valiante on Medium]]></description>
        <link>https://medium.com/@davidevaliante?source=rss-6dd24b156204------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*G6DA5FyGbbH5rDuP.</url>
            <title>Stories by Davide Valiante on Medium</title>
            <link>https://medium.com/@davidevaliante?source=rss-6dd24b156204------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 12:25:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@davidevaliante/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[Linear Regression in Python]]></title>
            <link>https://medium.com/@davidevaliante/linear-regression-in-python-2af8ea1c3076?source=rss-6dd24b156204------2</link>
            <guid isPermaLink="false">https://medium.com/p/2af8ea1c3076</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[linear-regression]]></category>
            <dc:creator><![CDATA[Davide Valiante]]></dc:creator>
            <pubDate>Tue, 13 Mar 2018 17:21:06 GMT</pubDate>
            <atom:updated>2020-06-04T09:58:50.442Z</atom:updated>
            <content:encoded><![CDATA[<p>This is meant to be a basic introduction to machine learning focused on a practical approach. For some in depth theory awareness (there is some beautiful math going on here) i highly suggest <a href="http://www-bcf.usc.edu/~gareth/ISL/index.html">this</a> book .</p><blockquote>“Hey but that’s written in R… weren’t we supposed to work with Python ?”</blockquote><p>We don’t care about <strong>R</strong> in that book, but we care about the theory behind <strong>Statistical Learning</strong> in general, so the language itself doesn’t make any difference for us. In case you want to follow along that book there is <a href="https://github.com/JWarmenhoven/ISLR-python">this</a> <strong>GitHub </strong>repo <em>“translating”</em> every example in that book into Python.</p><h4><strong>Last note before starting</strong></h4><p>We used this approch to monitor our user growth over time on <a href="https://www.spikeslot.com/">SPIKE Slot</a> which, as the name suggestes is an informative websites about online slots and online casinos but has a similar dataset as the one used in this example. This lecture relies on <a href="https://www.udemy.com/python-for-data-science-and-machine-learning-bootcamp/">Jose’s Portilla’s “Python for data science and Machine Learning Bootcamp” </a>example on Linear Regression. If you are interested in this course (Jose’s is one of the best teacher on Udemy in my opinion) go check it out, it’s really worth it as introduction material.</p><h3>Let’s Start with some tools</h3><p>First of all, some imports</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21884a3f3d7a4e2fe68d8c28e3983f23/href">https://medium.com/media/21884a3f3d7a4e2fe68d8c28e3983f23/href</a></iframe><p>Then we are going to load some Ecommerce data to work with, using pandas</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2fe23315efea7e9fb4cd23e7a1124946/href">https://medium.com/media/2fe23315efea7e9fb4cd23e7a1124946/href</a></iframe><p>If we check the first five elements of this csv file using the .head() method of our dataframe we get a pick to our data :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j8W_GZrRAbY5DyOrZm54QQ.png" /></figure><h3>Some preliminary Analysis</h3><p>We can also call the .describe() and .info()method on our dataframe and get a preliminary overview of our dataset</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*gl62xtK7528ZXkOxfHDybQ.png" /><figcaption>result of the .describe() method</figcaption></figure><p>Let’s briefly analyze the <strong>mean</strong> values of our columns to have a picture of our customers :</p><ul><li><strong>Avg. Session Length :</strong> that is the average time each customer spent inside our service <em>(we don’t know the ratio between time spent from the website/from mobile). We can safely assume that the base </em><strong><em>unit</em></strong><em> used for this column is a </em><strong><em>minute</em></strong></li><li><strong>Time on App :</strong> that is the average time each customer used our service from a mobile device. <em>We can assume that the base unit used for this column is </em><strong><em>Hour/Year</em></strong></li><li><strong>Time on Website :</strong> that is the average time each customer used our service from the website. <em>We can assume that the base unit used for this column is </em><strong><em>Hour/Year</em></strong></li><li><strong>Length of Membership :</strong> that is the average time each customer has been affiliated with our service. <em>We can assume that the base unit used for this column is </em><strong><em>Year</em></strong></li><li><strong>Yearly Amount Spent :</strong> that is the average amount of money spent by each customer in a single year <em>(Once again we don’t know the website/mobile ratio)</em>. <em>We can assume that the base unit used for this column is </em><strong><em>Dollar/Year</em></strong></li></ul><p>Next, let’s check if there is there is some missing value in our columns calling .info() on the dataframe</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*561eXwxxx-GVcSJxwlGbbg.png" /><figcaption>result of the .info() method</figcaption></figure><p>500 entries and every columns has 500 non-null values, <strong>we are good to go !</strong></p><blockquote>“Ok that’s cool and all but…what we gonna do with this data ?”</blockquote><p>We want to find some correlation between <strong>Yearly Amount Spent</strong> and the other data in order to find the strength/weaknesses of our service.</p><h3>Data Visualization</h3><blockquote><strong>“A picture is worth a thousand words</strong>”</blockquote><p>That’s indeed true so let’s plot some graphs using seaborn ! First of all let’s check our the distribution plot of our target column (<strong><em>Yearly Amount Spent</em></strong>)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/07dec3128cddaf1f56fcdb5b41d0bb6d/href">https://medium.com/media/07dec3128cddaf1f56fcdb5b41d0bb6d/href</a></iframe><p>Result :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*dMNI9ZrcGNvlOQHYW4czVw.png" /></figure><p><em>The values are normally distributed, you can raise the </em><em>bins for higher resolution</em></p><p>Next lets gather some information plotting the <strong>Yearly Amount Spent</strong> against <strong>Time on Website</strong> and <strong>Time on App</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3bd2ecde77e24bbf05f210f474f04bea/href">https://medium.com/media/3bd2ecde77e24bbf05f210f474f04bea/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SJG9xpvO5IOhm3Zw7BC1aA.png" /></figure><p>That’s good, but a little bit confusing, let’s use the kind=&#39;hex&#39; option of <strong>jointplot</strong> to cluster the information in a nicer way</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f1e5827a91290ebb82f41761b78c6b2/href">https://medium.com/media/0f1e5827a91290ebb82f41761b78c6b2/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KEg3xtPCNj-tPg2l8Q1qmA.png" /></figure><p>Much better isn’t it ? With this visualization we can already speculate that the <strong>Time on App</strong> variable is slightly more important than <strong>Time on Website</strong>. While most of the clusters are <strong><em>darker</em></strong> around the center in both plots, the <strong>Time on App</strong> seems to have some kind of <strong><em>“slope”</em></strong> attachted to it. We can use lmplot() to undercover this behaviour</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/336330d89ce7e67958ae796d650c1955/href">https://medium.com/media/336330d89ce7e67958ae796d650c1955/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*zRHnSfuAaurIgU-qpdcV7Q.png" /></figure><p>Looks like we were right ! let’s do the same to check <strong>Time on Website</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9aeeacea2e82030fa5e147e4cb5f40b0/href">https://medium.com/media/9aeeacea2e82030fa5e147e4cb5f40b0/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*rY9vrsZa6ds1duNdzqE6GQ.png" /></figure><p>There is some slope, but it’s not steep enough for our taste.</p><h4>Exploratory Result</h4><p>Looks like the more time our customers spend on the mobile app the higher the Yearly Amount Spent gets. This is already a pretty good qualitative result, but we can do much better than that !</p><h3>Training data and Testing data</h3><p>The point of this section is to split our data into 2 sets of tuples :</p><ul><li>A <strong>Training Set</strong> made of many <em>(X,Y)</em> points from our data. This will be the information we feed to our computer in order to estimate a line which can predict future (<em>yet to be known</em>) values.</li><li>A <strong>Test Set</strong> made of many <em>(K,W)</em> values from our data. This will be the information we’ll use to test how good of an approximation our line model actually is.</li><li><strong>Y</strong> will be our target variable (the value we want to predict), in this case <strong>Yearly Amount Spent. </strong>We can grab this column calling<strong> </strong><strong>y=customers[&#39;Yearly Amount Spent] </strong>returning a 500-length array</li><li><strong>X</strong> is a slightly more complicated object. It’s a matrix with columns [‘Avg. Session Length’,’Time on App’,’Time on Website’,’Length of Membership’]. We can easily grab this matrix by calling x=customers[[&#39;Avg. Session Length&#39;, &#39;Time on App&#39;, &#39;Time on Website&#39;, &#39;Length of Membership&#39;]] returning a 500 x 4 matrix</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/966c87fa0c0388783c785a4e67d0762f/href">https://medium.com/media/966c87fa0c0388783c785a4e67d0762f/href</a></iframe><p>Let’s take a closer look to the parameters passed to train_test_split()</p><ul><li>test_size goes from 0.0 up to 1.0 and basically tells the <em>proportion </em>of data to be put in the <strong>X_Test</strong> and <strong>Y_Test. </strong>By setting it to 0.3 we’ll have 30% of our initial data in the<strong> Test Set. </strong>Our test set is now made of <strong>150 (X_Test, Y_Test) </strong>points, while our <strong>Train Set</strong> will be made of<strong> 350 (X_Train,Y_Train) </strong>points (remember that our initial dataset had 500 customers entry)</li><li>random_seed is an optional parameter and it just ensures that the randomly picked values for the <strong>Test Set</strong> are the same as the ones shown below</li></ul><h3>Model Training</h3><p>It’s time to make our LinearRegression happen ! we need to import the <em>linear model</em> from <strong>sklearn </strong>and instantiate it</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a1b34c99ae8d76ae26af1441ed3a9ed/href">https://medium.com/media/3a1b34c99ae8d76ae26af1441ed3a9ed/href</a></iframe><p>Next we have to train our linear model with our <strong>Train Data</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32314bf751b269cb5fc23fcb2608af3e/href">https://medium.com/media/32314bf751b269cb5fc23fcb2608af3e/href</a></iframe><p>We are basically asking <strong>sklearn</strong> to give a us a linear model based off this set of data</p><h3><strong>Coefficients of the linear model</strong></h3><p>We now have a new object to work with ! Let’s start by printing the coefficients with print(my_linear_model.coef_) which gives us this list</p><pre>[25.98154972 38.59015875  0.19040528 61.27909654]</pre><blockquote>“Ok what the hell is that?”</blockquote><p>Those are the coefficients for each column in order ! This simply means that :</p><ul><li>If we keep <strong><em>every other column</em></strong> fixed and we increase <strong>Avg. Session Length</strong> by <strong>1</strong> unit (so by <strong>1 Minute</strong>), then the <strong>Yearly Amount Spent</strong> increases by 25.98154972 dollars.</li><li>If we keep <strong><em>every other column</em></strong> fixed and we increase <strong>Time on App </strong>by <strong>1</strong> unit (so by <strong>1 Hour/Year</strong>), then the <strong>Yearly Amount Spent</strong> increases by 38.59015875 dollars.</li><li>If we keep <strong><em>every other column</em></strong> fixed and we increase <strong>Time on Website </strong>by <strong>1</strong> unit (so by <strong>1 Hour/Year</strong>), then the <strong>Yearly Amount Spent</strong> increases by 0.19040528 dollars.</li><li>If we keep <strong><em>every other column</em></strong> fixed and we increase <strong>Length of Membership </strong>by <strong>1</strong> unit (so by <strong>1Year</strong>), then the <strong>Yearly Amount Spent</strong> increases by 61.27909654 dollars.</li></ul><p>This partially confirms that Time on App is important for the growth of the <strong>Yearly Amount Spent </strong>and it also shows that the most prominent coefficient is the Length of Membership. The main difference between our linear model and our exploratory analysis is that now we have <strong>numbers</strong> to prove our claim !</p><blockquote>“Wait, how do we know this is a good model ?”</blockquote><p>That’s what our <strong>Test Set</strong> has been created for ! We can let our model predict()values based off our <strong>Test Set </strong>and then check if they match the<strong> actual value </strong>we had in the begin</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da311e5a4f3b43dc629ff2d8422de9d9/href">https://medium.com/media/da311e5a4f3b43dc629ff2d8422de9d9/href</a></iframe><p>This basically asks our model :</p><blockquote>“Hey, take this list of value, plug it inside your function and give me back a list of results”</blockquote><p>and the answer of our model is</p><pre>array([456.44186104, 402.72005312, 409.2531539 , 591.4310343 ,<br>       590.01437275, 548.82396607, 577.59737969, 715.44428115,<br>       473.7893446 , 545.9211364 , 337.8580314 , 500.38506697,<br>       552.93478041, 409.6038964 , 765.52590754, 545.83973731,<br>       693.25969124, 507.32416226, 573.10533175, 573.2076631 ,<br>       397.44989709, 555.0985107 , 458.19868141, 482.66899911,<br>       559.2655959 , 413.00946082, 532.25727408, 377.65464817,<br>       535.0209653 , 447.80070905, 595.54339577, 667.14347072,<br>       511.96042791, 573.30433971, 505.02260887, 565.30254655,<br>       460.38785393, 449.74727868, 422.87193429, 456.55615271,<br>       598.10493696, 449.64517443, 615.34948995, 511.88078685,<br>       504.37568058, 515.95249276, 568.64597718, 551.61444684,<br>       356.5552241 , 464.9759817 , 481.66007708, 534.2220025 ,<br>       256.28674001, 505.30810714, 520.01844434, 315.0298707 ,<br>       501.98080155, 387.03842642, 472.97419543, 432.8704675 ,<br>       539.79082198, 590.03070739, 752.86997652, 558.27858232,<br>       523.71988382, 431.77690078, 425.38411902, 518.75571466,<br>       641.9667215 , 481.84855126, 549.69830187, 380.93738919,<br>       555.18178277, 403.43054276, 472.52458887, 501.82927633,<br>       473.5561656 , 456.76720365, 554.74980563, 702.96835044,<br>       534.68884588, 619.18843136, 500.11974127, 559.43899225,<br>       574.8730604 , 505.09183544, 529.9537559 , 479.20749452,<br>       424.78407899, 452.20986599, 525.74178343, 556.60674724,<br>       425.7142882 , 588.8473985 , 490.77053065, 562.56866231,<br>       495.75782933, 445.17937217, 456.64011682, 537.98437395,<br>       367.06451757, 421.12767301, 551.59651363, 528.26019754,<br>       493.47639211, 495.28105313, 519.81827269, 461.15666582,<br>       528.8711677 , 442.89818166, 543.20201646, 350.07871481,<br>       401.49148567, 606.87291134, 577.04816561, 524.50431281,<br>       554.11225704, 507.93347015, 505.35674292, 371.65146821,<br>       342.37232987, 634.43998975, 523.46931378, 532.7831345 ,<br>       574.59948331, 435.57455636, 599.92586678, 487.24017405,<br>       457.66383406, 425.25959495, 331.81731213, 443.70458331,<br>       563.47279005, 466.14764208, 463.51837671, 381.29445432,<br>       411.88795623, 473.48087683, 573.31745784, 417.55430913,<br>       543.50149858, 547.81091537, 547.62977348, 450.99057409,<br>       561.50896321, 478.30076589, 484.41029555, 457.59099941,<br>       411.52657592, 375.47900638])</pre><p>While the actual values are stored in our <strong>Y_Test </strong>variable which looks like this :</p><pre>18     452.315675<br>361    401.033135<br>104    410.069611<br>4      599.406092<br>156    586.155870<br>350    535.480775<br>32     588.712606<br>205    712.396327<br>81     462.897636<br>414    532.724805<br>489    327.377953<br>474    492.556834<br>95     543.340166<br>355    403.766902<br>65     765.518462<br>39     537.846195<br>368    708.935185<br>236    501.928265<br>318    564.790969<br>435    571.216005<br>12     408.640351<br>211    548.518529<br>289    467.427849<br>243    490.600443<br>241    571.471034<br>382    410.602944<br>457    534.771485<br>320    368.654785<br>64     540.263400<br>335    443.441860<br>          ...    <br>143    350.058200<br>271    628.047804<br>56     520.898794<br>475    535.321610<br>272    582.491924<br>433    434.144202<br>154    595.803819<br>200    504.870432<br>53     451.457447<br>385    414.935061<br>312    319.928870<br>51     442.667252<br>468    553.994674<br>345    461.790959<br>233    463.745981<br>237    376.336901<br>317    404.824529<br>450    475.015407<br>324    559.199048<br>170    421.966794<br>266    554.003093<br>133    542.711558<br>430    556.186369<br>15     461.780742<br>13     573.415867<br>147    479.731938<br>346    488.387526<br>423    461.112248<br>17     407.704548<br>259    375.398455<br>Name: Yearly Amount Spent, Length: 150, dtype: float64</pre><p>The number on the left column is just the customer id, while the number on the right column is the actual <strong>Yearly Amount Spent</strong></p><p>We can already check how good our model just by looking at the difference between the values <strong>predicted</strong> by our <strong>linear model</strong> and the <strong>real values.</strong></p><p>Let’s check the <strong>first entry</strong> on both:</p><p>Our <strong>predicted value</strong> is 456.44186104 while the <strong>real value</strong> is 452.315675. Our model overstimated by 4,12618604 dollars which is equal to ~0.9% of the predicted value. For this single observation our model had an outstanding accuracy of 99,1%.</p><blockquote>“Yeah, that’s cool, but there are 149 values left to check, maybe we just got lucky for the first one and everything else is screwed ! i don’t want to check 149 more values !”</blockquote><p>You are right, so let’s use a graph. After all if the predicted values and the real values are really that close we should have a scatterplot which resembles the equation of f(x) = x, which is basically just a 45° straight line.</p><pre>seaborn.jointplot( Y_Test, my_linear_model.predict(X_Test))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*MXbCLTIvhD_q6KmTIhRzmw.png" /></figure><p>We can clearly see that, even if there is some noise in the plot, it’s really really close to the <strong>bisector line</strong>, this means that our <strong>predictions</strong> are really really close to the <strong>real</strong> <strong>values.</strong></p><blockquote>This shows that our linear model can predict() future values with great accuracy !</blockquote><h3><strong>Mean Absolute Error, Mean Squared Error, and the Root Mean Squared Error.</strong></h3><p>Lastly we can also take a pick to the error metrics</p><pre>from sklearn import metrics</pre><pre>print(&#39;Mean Absolute Error:&#39;, metrics.mean_absolute_error(y_test, predictions))</pre><pre>print(&#39;Mean Squared Error:&#39;, metrics.mean_squared_error(y_test, predictions))</pre><pre>print(&#39;Root Mean Squared Error:&#39;, np.sqrt(metrics.mean_squared_error(y_test, predictions)))</pre><pre># OUTPUT :</pre><pre>Mean Absolute Error: 7.22814865343<br>Mean Squared Error: 79.813051651<br>Root Mean Squared Error: 8.93381506698</pre><p>Or just take a look to the histogram of the differences by calling :</p><pre>plt.figure(figsize=(12,7))</pre><pre>seaborn.distplot((Y_Test-lm.predict(X_Test)),bins=60)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*pcl-w-1sJfT69UT2jE7Z1w.png" /></figure><p>This also shows that the differences between <strong>real values</strong> and <strong>predicted values </strong>are <strong>normally distributed</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2af8ea1c3076" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>