<?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 Nathan Toubiana on Medium]]></title>
        <description><![CDATA[Stories by Nathan Toubiana on Medium]]></description>
        <link>https://medium.com/@toubiana.nathan?source=rss-90c8085403a0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*L6-el2cq8QHwWeatg63AHQ.jpeg</url>
            <title>Stories by Nathan Toubiana on Medium</title>
            <link>https://medium.com/@toubiana.nathan?source=rss-90c8085403a0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 06:42:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@toubiana.nathan/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[An introduction to SVD and its widely used applications]]></title>
            <link>https://medium.com/data-science/an-introduction-to-svd-and-its-widely-used-applications-f5b8f19cb6cb?source=rss-90c8085403a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5b8f19cb6cb</guid>
            <category><![CDATA[svd]]></category>
            <category><![CDATA[algebra]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[apc]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Nathan Toubiana]]></dc:creator>
            <pubDate>Sat, 01 Jun 2019 23:37:01 GMT</pubDate>
            <atom:updated>2019-06-04T20:25:45.711Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*J1mWANZ5afCD9mmJ" /></figure><p>If you’re in the data science world (or close to it), you probably already heard of SVD a thousand times even if you haven’t used it. Whether it’s for PCA (Principal Components Analysis) or recommendation algorithms, SVD is a powerful technique widely used today in a lot of models — we’ll describe what it is and show how it’s used in some key methods.</p><p><em>Note: we won’t cover the code part but only the theory.</em></p><h3>What’s SVD?</h3><p>SVD means <strong>Singular Value Decomposition</strong>. The SVD of a matrix <em>X</em> of dimension <em>n×d</em> is given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/214/1*dNMFT1mkqzOFRfovh8aSxg.png" /></figure><p>Where:</p><ul><li><em>U</em> and <em>V</em> are square orthogonal:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/168/1*IipDz2_edMIg7urxAfbS4A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/178/1*qBGsTIKmLOTInTYyR7QTrg.png" /></figure><ul><li><em>D</em> is diagonal of dimension <em>d×n</em></li></ul><p>Some additional notes:</p><ul><li><strong>D is not necessarily square</strong></li><li>The SVD of a matrix can be done <strong>for any matrix</strong></li><li>SVD is <strong>different from the eigenvalue decomposition</strong> of a matrix.</li></ul><p>Let’s define the <strong>eigenvalue decomposition</strong> of a matrix. First, it exists for a matrix<em> X</em> if and only if <em>X</em> is square and the eigenvectors form a base in the matrix dimension space. If that’s the case, then one can write:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/212/1*KE9xfHmTURE_4xzZXTE0Ww.png" /></figure><p>where <em>P</em> is the matrix of the eigenvectors and D<em>elta</em> is a diagonal matrix of the eigenvalues of <em>X </em>— here, D<em>elta</em> is square.</p><p>In some sense, <strong>SVD is a generalization of eigenvalue decomposition</strong> since it can be applied to any matrix.</p><h3>SVD used in PCA</h3><p>PCA means <strong>Principal Components Analysis</strong>. Given an input matrix <em>X</em>, it consists in <strong>finding components</strong> <em>p_i</em> that are linear combinations of the original coordinates:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*Qnds0TeZJP07r6Y8A04_DA.png" /></figure><p>in such a way that:</p><ul><li>The components are <strong>orthogonal</strong> (<em>E[p_ip_j]=0</em>)</li><li>The components are <strong>ordered</strong> in such a way that <em>p_1</em> explains the largest percentage of variance, and <em>p_2</em> has the second largest (that has not been explained by <em>p_1</em>) and so on.</li></ul><p>We assume here that <strong><em>X</em> is normalized</strong> (<em>E(x_i)=0</em> and <em>Var(x_i)=1</em> for each feature).</p><p>One can show that the components<em> p</em> are given by</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/1*jOm0d64YjaLdRj7WClJ7qg.png" /></figure><p>where <em>Gamma</em> is the matrix found when doing the <strong>eigenvalue decomposition of the variance-covariance matrix</strong> of <em>X</em>. Note that this is possible because the variance-covariance matrix is symmetric and <strong>any symmetric matrix has an eigen value decomposition</strong>. Also note that the otrhogonality of <em>Gamma</em> implies</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*e4Dvt7xlm6pOlE_hPwckfQ.png" /></figure><p>Note also that since <em>E(x)=0</em>, <em>E(p)=0</em>. And</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*EZK0ybul2EPMWsHXLoO1uA.png" /></figure><p>where <strong>D<em>elta</em> is the matrix of the eigenvalues of the variance-covariance matrix</strong> of <em>X</em> placed in descending order. The key thing to remember here is that <strong>the principal components of <em>X</em> are found through a linear transformation using the eigenvectors of the variance-covariance matrix</strong>.</p><p>Once we have the components, we can reduce our data by keeping only the top <em>k</em> (<em>k</em> being arbitrary) components.</p><blockquote>But do we really need to compute this eigenvalue decomposition?</blockquote><p>No! And that’s where SVD comes in. Indeed, using the formulas of SVD above, the <strong>eigenvectors of the variance-covariance matrix are given by the matrix <em>U</em></strong> of the SVD of <em>X</em>. And the <strong>eigen values are the squares of the singular values</strong> from the SVD of <em>X</em>.</p><p>We can thus <strong>use SVD to perform PCA</strong>, and keep the top <em>k</em> singular values of <em>X</em> to approximate given the top <em>k</em> principal components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*7a-lvSgldIicycgHT8IMyg.png" /></figure><p>In some common cases, doing <strong>PCA through SVD is numerically more efficient</strong> than through the eigenvalue decomposition of the variance-covariance matrix (it takes some extra time to compute the variance-convariance matrix).</p><h3>SVD used in matrix completion</h3><p>For most recommendation algorithms, the input matrix being very sparse, matrix factorization methods are key since the space needs to be ‘reduced’ to a smaller latent one. SVD plays a central role in it.</p><p>The general matrix factorization problem formulated as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*p5je7E3wp4Zzr608ltOW1w.png" /></figure><p>Under the constraint that <strong>the rank of <em>M</em></strong> is less or equal than an arbitrary integer <em>r</em>. One can prove that the <strong>solution</strong> of this problem is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/190/1*5EBQoFj-7ViNqJXXM-MngA.png" /></figure><p>where</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*XUYLDUmMlX3ZgfBjC1htDA.png" /></figure><p>and <em>D_r</em> is constructed from <em>D</em> by keeping just the first <em>r </em>singular values.</p><p>One can note that we can’t easily solve the above problem when the matrix <em>X</em> has missing values. There are several methods to cope with that. One of them is to start with an initial solution and to iterate by doing SVDs until convergence. We won’t get into the details of the methods here, but the bottom line is that <strong>SVD can also be used in matrix completion, </strong>since it involves doing matrix factorization.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5b8f19cb6cb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/an-introduction-to-svd-and-its-widely-used-applications-f5b8f19cb6cb">An introduction to SVD and its widely used applications</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[All you need to know about Linear Regression algebra to be interview-ready]]></title>
            <link>https://medium.com/data-science/all-you-need-to-know-about-linear-regression-to-be-interview-ready-fc58a00a0b8c?source=rss-90c8085403a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc58a00a0b8c</guid>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[algebra]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Nathan Toubiana]]></dc:creator>
            <pubDate>Thu, 23 May 2019 12:53:00 GMT</pubDate>
            <atom:updated>2019-05-24T14:44:12.844Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*03OJTwqgvqGS9nPF" /><figcaption>Photo by <a href="https://unsplash.com/@johnmoeses?utm_source=medium&amp;utm_medium=referral">John Moeses Bauan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>All the algebra you need to know about Linear Regression to be interview-ready</h3><p>Linear Regression (LR) is one of the most simple and important algorithm there is in data science. Whether you’re interviewing for a job in data science, data analytics, machine learning or quant research, you might end up having to answer specific algebra questions about LR. Here’s all you need to know to feel confident about your LR knowledge.</p><p><em>Note: this article is all about theory, no coding. It also assumes that you are already at least a little familiar with algebra.</em></p><h3><strong>Know your assumptions</strong></h3><p>Although this article assumes that you’re already somewhat familiar with LR, let’s remind the formula and assumptions. Given N observations, an output vector Y (dimension Nx1) and p inputs X1, X2, …, Xp (each input vector being of dimension Nx1), <strong>LR assumes that the regression function E(Y|X) is linear in the inputs</strong>. Y thus statisfies:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*kr1FkhHPnJwOIgYA6wCN7Q.png" /></figure><p>where <strong>epsilon is the error terms</strong>. The linear assumption is actually <strong>the only assumption strictly necessary for LR</strong> later in this article we’ll se that we can add more assumptions to infer more results.</p><p>Although this above formula may seem simple, it’s not always easy to find the coefficients (beta) — moving forward, we’ll call hat betas our estimates of the coefficients.</p><h3>Know the key metrics definitions</h3><p>Here are the 3 metrics you definitely need to know (by heart):</p><ul><li>The <strong>RSS</strong> is the Residual Sum of Squares</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*VluvChYLI9Qv6xWofwaPpw.png" /></figure><p>where <em>y_i</em> is the output for observation <em>i</em> and <em>ŷ_i </em>is the estimated output for observation i<em>:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*Mduh39LxsS_VT_HO4DKoeA.png" /></figure><ul><li><strong>TSS</strong> is the Total Sum of Squares</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*mxsJBISHVlJ8OeTrbyvzdQ.png" /></figure><p>where</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*sCcADzoMBvmSe2bywwe8Jw.png" /></figure><ul><li><strong>R-squared</strong>, which is a measure of the linear relationship betwween X and Y</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*pHIDS2QVLr5pg789FRLsVw.png" /></figure><p>As long as you know these formulas you should be able to infer all the other results by logical reasoning.</p><h3><strong>Know the solution: how (and when) to compute it</strong></h3><p>As we said before, the key of LR is finding estimations of the coefficents. We find these by <strong>minimizing the RSS. </strong>To do so, let’s define X and Y by</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*pptlEJyXbFDmL7TlPRhDLQ.png" /></figure><p>Note that we have to add a column of 1s to the input matrix in order to take into account the intercept beta_0. Our minimization problem is equivalent to solving:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*ynuur03BGGGX0P-e6pzupA.png" /></figure><p>So we can compute the <strong>gradient</strong> of the right term:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*vZTonMpA0ouMOlxN_6DKtw.png" /></figure><p>Which is supposed to be equal to 0 for our estimation beta hat.</p><p><strong>Assuming that X</strong>⊤<strong>X is non singular, </strong>this gives us an explicit solution<strong>:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*wRpfeZTfPdbef653HTlydQ.png" /></figure><p>This is a formula you need to know, but you should also be able to prove it, as done above. The assumption of non singularity is key here. We also infer the formula of y estimated:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*RFs1rIOhTjgrd3nKej6MHA.png" /></figure><p>It can also be useful to know the explicit solution in <strong>dimension Nx1 </strong>(1 input variable):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/334/1*4Xj2IalzFa036xaTvvbk9A.png" /></figure><p>Where <em>x</em> is here a vector (not a matrix) — it’s easy to remember when you already have the more general solution: X⊤X becomes the variance of the input (in 1-dimension, inverting a term is equivalent to dividing by that term) and X⊤y becomes the covariance term. You can also compute this solution by doing a similar calculus, in dimension 1.</p><h3>Be comfortable with hypothesis testing (assuming normal errors)</h3><p>In an interview, it’s also important to have some statistical notions for LR.</p><p>This section assumes that you have the basics in statistical tests (including <a href="https://en.wikipedia.org/wiki/T-statistic">t stats</a>, <a href="https://en.wikipedia.org/wiki/F-distribution">f-stats</a> and <a href="https://en.wikipedia.org/wiki/Statistical_hypothesis_testing">hypothesis testing</a>).</p><p>Assuming normal errors, i.e</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/1*3vqNfSNUOQKmCzRX4X6oaQ.png" /></figure><p>(let’s not forget that epsilon is a vector here!) then our estimated solution satisfies:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*xbxzcrRe24EnFO_P8CYPCQ.png" /></figure><p>and thus</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*GmfuzN6xm3uoiMnmW-kRhw.png" /></figure><p>which brings us to</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*I16vPbKE-KvpW0HlsK9nhQ.png" /></figure><p>This finding helps evaluating the <strong>null hypothesis</strong> that a coefficient beta_j is null: we can compute the <strong>t-score</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*bvC06jnIStsWv7n0Llu1fg.png" /></figure><p><strong>Under the null hypothesis</strong>, t_j follows a t-distribution with N-p-1 degrees of freedom, and <strong>for N large enough</strong>, follows a normal distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*TypzkyKIsz4rYm3xFtWZQw.png" /></figure><p>Computing this score can help you assess the null hypothesis. For example, <strong>finding a |t_j| score higher than 1.96 will ensure significance at the 5% level that the coefficient beta_j is not null.</strong></p><p>You can also compute <strong>confidence intervals</strong> for a given coefficient: an approximate <strong>(1–2*alpha)-confidence interval</strong> is given by</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*p_LNBj4bZ_D70UoniLLPng.png" /></figure><p>where we use the areas under the standard normal curve to compute:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*UEWMvf3RY-FU2-kPtzTxMQ.png" /></figure><p>We can also test the <strong>hypothesis that every coeffcicient is null</strong> by computing the F-stat</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*9aFhz88SvRboLXknZsfQcA.png" /></figure><p>which under the null hypothesis, follows an F(p, N-p-1) distribution. Hence, large values of F constitue evidence against the null hypothesis.</p><h3>Bonus 1: why do we do least squares?</h3><p>When we looked for the optimal estimation of beta, we instinctively jumped to least squares optimization, but why? First, we can prove (we won’t here, check <a href="http://www.unm.edu/~lspear/geog525/24linreg2.pdf">this article</a> for more details) that <strong>the least squares estimator is unbiased</strong>, i.e</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/162/1*pKYC_XODvRTsiU795s20iQ.png" /></figure><p>Next, there’s actually a theorem that proves that the least squares estimator <strong>has the smallest variance</strong>. This is the <a href="https://en.wikipedia.org/wiki/Gauss%E2%80%93Markov_theorem">Gauss-Markov theorem</a>: it shows that <strong>the best unbiased estimator is the least squares</strong>.</p><h3><strong>Bonus 2: what to do when </strong>X⊤X <strong>is not fully ranked?</strong></h3><p>First, let’s see when this happens. Let’s remind ourselves that X is of dimension (N, p+1). X⊤X is then (p+1, p+1). We can show that <strong>X⊤X is fully ranked if and only if X is of rank p+1,</strong> <strong>which forces N&gt;p</strong>. You can see the proof <a href="https://math.stackexchange.com/questions/691812/proof-of-when-is-a-xtx-invertible">here</a>. This means that the features are linearly independent (but not necessarily uncorrelated).</p><p>When this is not the case (when we have more features than observations), we can use <strong>shrinkage methods</strong> such as ridge regression. Indeed, when we add a term to the diagonal of X⊤X, the problem becomes feasible. For the example of <strong>ridge regression</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*L9ABwykfGRGkQL8c3bFobA.png" /></figure><p>has a solution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*VvncLQxOX9PsAFOP4JQBCQ.png" /></figure><p>indeed, because X⊤X, is <a href="https://en.wikipedia.org/wiki/Definiteness_of_a_matrix">positive semi-definite</a>, its eigenvalues are all positive, adding a positive term to the diagonal makes it fully ranked. So this makes the problem non-singular. This is one the reasons we have to apply <strong>regularization techniques</strong> for cases when p&gt;&gt;N.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc58a00a0b8c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/all-you-need-to-know-about-linear-regression-to-be-interview-ready-fc58a00a0b8c">All you need to know about Linear Regression algebra to be interview-ready</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From a python project to an open source package: an A to Z guide]]></title>
            <link>https://medium.com/free-code-camp/from-a-python-project-to-an-open-source-package-an-a-to-z-guide-c34cb7139a22?source=rss-90c8085403a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/c34cb7139a22</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Nathan Toubiana]]></dc:creator>
            <pubDate>Thu, 16 May 2019 17:10:01 GMT</pubDate>
            <atom:updated>2019-05-24T02:03:55.423Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6oy_MuppfAXGuTjG" /><figcaption>Photo by <a href="https://unsplash.com/@cdr6934?utm_source=medium&amp;utm_medium=referral">Chris Ried</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>Written by </em><a href="https://medium.com/@gabi10004"><em>Gabriel Lerner</em></a><em> and </em><a href="https://medium.com/@toubiana.nathan"><em>Nathan Toubiana</em></a></p><p>Excited about your python project? Do you want to share it with a wider audience? Packaging and publishing your package is a great way to get other people interested in your project. Here is a simple step by step guide to build and publish your first python package.</p><p>We’ll describe all the steps we’ve been through to create S<a href="https://github.com/nathan-toubiana/scitime">citime</a>, a package that gives an estimate of algorithm training times (you can learn more about Scitime <a href="https://medium.freecodecamp.org/two-hours-later-and-still-running-how-to-keep-your-sklearn-fit-under-control-cc603dc1283b?source=friends_link&amp;sk=98e79add47516c38eeec59cf755df938">here</a>).</p><p><em>Note</em>: We will assume that you already have a project in GitHub that you would like to package and publish.</p><h3>Step 0: Have your project licensed</h3><p>Before doing anything else, your project should have a license since it’s going to be open source. Depending on how you’d like your package to be used, many licenses are available. Some usual licenses for open source projects are <a href="https://en.wikipedia.org/wiki/MIT_License">MIT</a> , <a href="https://en.wikipedia.org/wiki/BSD_licenses">BSD</a> or <a href="https://opensource.org/licenses/GPL-2.0">GPL</a>.</p><p>To add a license to your project, simply add a <a href="https://github.com/nathan-toubiana/scitime/blob/master/LICENSE">LICENSE</a> file to the repository root by following the steps described <a href="https://help.github.com/en/articles/adding-a-license-to-a-repository">here</a>.</p><h3>Step 1: make your code publish-ready</h3><p>There are a few preliminary things you need to do to have your project package-able:</p><ul><li><strong>Your project structure</strong> needs to be in place. Usually, the root of the repository contains a folder with the name of the repository — this is where the core project code should be. What’s outside of this folder is the extra code that’s necessary to run and build the package (tests, documentation, etc.)</li><li>The core folder should include one (or more) module(s) and an <a href="https://github.com/nathan-toubiana/scitime/blob/master/scitime/__init__.py"><strong>__init__.py</strong></a> file which imports the classes/functions you’ll want the end user to have access to. This file can also include the version of the package, to make it easily accessible to the end user.</li><li>Ideally, a <strong>proper </strong><a href="https://github.com/nathan-toubiana/scitime/blob/master/scitime/_log.py"><strong>logging system</strong></a> (instead of prints) should be set by using the logging package.</li><li>When relevant, your core code should be organized in one or more <a href="https://medium.freecodecamp.org/lets-get-classy-how-to-create-modules-and-classes-with-python-44da18bb38d1"><strong>classes</strong></a><strong>.</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d9ad9fa901432c1b5432b0268474b09/href">https://medium.com/media/0d9ad9fa901432c1b5432b0268474b09/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c474220b96bc7a6bc6c744695ca981b/href">https://medium.com/media/8c474220b96bc7a6bc6c744695ca981b/href</a></iframe><h3>Step 2: Create a setup.py with setuptools</h3><p>Once your project has a set structure, you should then add a setup.py file at the root of the repository. This mostly helps to automate all the publishing and version maintaining processes. Here’s an example of what a setup.py should look like (source <a href="https://github.com/nathan-toubiana/scitime/blob/master/setup.py">here</a>).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/732af02dc9814faec2af3a95887e86f3/href">https://medium.com/media/732af02dc9814faec2af3a95887e86f3/href</a></iframe><p>A few notes:</p><ul><li>If your package has <em>minimum</em> dependencies, a clean way to handle these is to add them in the setup file, through the install_requires argument. If you’d like to share all transitive dependencies, you can also traditionnally point to them in a <a href="https://github.com/nathan-toubiana/scitime/blob/master/requirements.txt">requirement.txt</a> (however, only minimum dependencies have to be in setup.py)</li><li>If you want metadata (from the repository) to be downloaded when anyone installs the package, you should add these through the package_data argument</li><li>More information about the setup() function can be found <a href="https://setuptools.readthedocs.io/en/latest/setuptools.html">here</a></li></ul><blockquote>Note: steps 3 to 6 are optional (but highly recommended), however you can jump straight to step 7 if you want to publish your package right now.</blockquote><h3>Step 3: Set local tests and test coverage checks</h3><p>If it is not already the case, at this point, your project should definitely have unit tests. Although there are many frameworks that can help you do that, one simple way of doing it is using <a href="https://docs.pytest.org/en/latest/">pytest</a>. All tests should be in a dedicated folder (named tests/ or testing/ for example). In that folder, put all the test files you need in order to cover as much of your core code as possible. Here’s an <a href="https://docs.pytest.org/en/latest/example/simple.html">example</a> of how to write a unit test. Here’s also one of our S<a href="https://github.com/nathan-toubiana/scitime/blob/master/testing/test_estimator.py">citime’s test files</a>.</p><p>Once in place, you can run your tests locally by running python -m pytest from the repository root.</p><p>Once your tests are created, you should also be able to estimate the coverage. This is important as you want to maximize the amount of code that’s tested in your project (to reduce the amount of unexpected bugs).</p><p>A lot of frameworks are available for this as well, for Scitime we used <a href="https://codecov.io/?gclid=Cj0KCQjwtr_mBRDeARIsALfBZA5cqcHXz1WyYyrLQqmAvD4fybMlnkeJwNXwBVFixpov8Mn4amFKg_AaAnTeEALw_wcB">codecov</a>. You can decide on a threshold of minimum coverage allowed by creating a <a href="https://github.com/nathan-toubiana/scitime/blob/master/.codecov.yml">.codecov.yml</a> file and also decide on what files to include in the coverage analysis by creating a <a href="https://github.com/nathan-toubiana/scitime/blob/master/.coveragerc">.coveragerc</a> file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6e750b67cc71cec0ab4749735d402ec/href">https://medium.com/media/a6e750b67cc71cec0ab4749735d402ec/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c85f5a83ebacf6577224bfb2ee4c4c53/href">https://medium.com/media/c85f5a83ebacf6577224bfb2ee4c4c53/href</a></iframe><h3>Step 4: Standardize syntax and code style</h3><p>You’ll also need to make sure that your code follows the <a href="https://www.python.org/dev/peps/pep-0008/">PEP8 guidelines</a> (i.e has a standard style and that the syntax is correct). Again, a lot of tools can help here. We used <a href="http://flake8.pycqa.org/en/latest/">flake8</a>.</p><h3>Step 5: Create a proper documentation</h3><p>Now that your project has tests and a good to structure, it should be a good time to add a proper documentation. First thing is to have a nice readme file that will show up on your Github repo root. Once this is done, here are a few additional “nice to have”:</p><ul><li><strong>Pull Request &amp; issue templates</strong>: when a new PR or issue is created, these files permit you to template the descriptions as you wish. Follow these <a href="https://help.github.com/en/articles/creating-a-pull-request-template-for-your-repository">steps</a> for PRs and these <a href="https://help.github.com/en/articles/manually-creating-a-single-issue-template-for-your-repository">steps</a> for issues to create them. Here are Scitime’s PR <a href="https://github.com/nathan-toubiana/scitime/blob/master/.github/PULL_REQUEST_TEMPLATE.md">template</a> and issue <a href="https://github.com/nathan-toubiana/scitime/tree/master/.github/ISSUE_TEMPLATE">template</a>.</li><li><strong>A contribution guide</strong>. This should be a short guide on how you want external users to contribute to your package. Here’s Scitime’s contribution <a href="https://github.com/nathan-toubiana/scitime/blob/master/.github/CONTRIBUTING.md">guide</a>.</li><li><strong>A </strong><a href="https://help.github.com/en/articles/adding-a-code-of-conduct-to-your-project"><strong>code of conduct</strong></a> (here’s S<a href="https://github.com/nathan-toubiana/scitime/blob/master/.github/CODE_OF_CONDUCT.md">citime’s</a>).</li><li><strong>Tags and a description</strong> (see screenshot below).</li><li><strong>Badges</strong> in the readme file (here’s a nice <a href="https://medium.freecodecamp.org/how-to-use-badges-to-stop-feeling-like-a-noob-d4e6600d37d2">article</a> on how to set these up).</li></ul><p>As the readme file should be quite synthesized, it’s also pretty standard to have a more in-depth documentation. You can use <a href="http://www.sphinx-doc.org/en/master/">sphinx</a> to do so, and then host the documentation on <a href="https://readthedocs.org/">readthedocs</a> (here’s Scitime’s <a href="https://scitime.readthedocs.io/en/latest/">example</a>). The documentation related files are usually in a docs/ folder (as done for S<a href="https://github.com/nathan-toubiana/scitime/tree/master/docs">citime</a>). Here’s a nice sphinx &amp; readthedocs <a href="https://docs.readthedocs.io/en/stable/intro/getting-started-with-sphinx.html">tutorial</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hdZytumS_XOhDaO8FBf7eQ.png" /><figcaption>Example of a repo that has tags and a description</figcaption></figure><h3>Step 6: Set up continuous integration</h3><p>At this point, your project is not far away from being ready to be published. However, it seems a little overwhelming to have to deal with updating the docs, running the tests and checking the style and coverage after each commit. Fortunately, <strong>Continuous Integration</strong> (CI) helps you with that. You can use webhooks to GitHub to automate all these things after each commit. Here’s the set of CI tools we used for Scitime:</p><ul><li>For running tests, we used <a href="https://docs.travis-ci.com/">travis-ci</a> and <a href="https://www.appveyor.com/">appveyor</a> (for tests on windows platforms). For travis-ci, besides setting up the webhooks on the repository, you also have to create a <a href="https://github.com/nathan-toubiana/scitime/blob/master/.travis.yml">.travis.yml</a> file in which you can not only run tests but also upload updated coverage outputs and check style and format. Same goes for appveyor by creating a <a href="https://github.com/nathan-toubiana/scitime/blob/master/appveyor.yml">appveyor.yml</a> file</li><li>Codecov and readthdocs also have dedicated webhooks</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/065e6fd9e2572e3b4caaa0ea8ffe99d6/href">https://medium.com/media/065e6fd9e2572e3b4caaa0ea8ffe99d6/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b116ea526e4e722342609b8e80053b4f/href">https://medium.com/media/b116ea526e4e722342609b8e80053b4f/href</a></iframe><p>This should make the whole process of updating the repository a lot easier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HOlH29e_Bj74-vkNqNLA0A.png" /><figcaption>Example of commit history with integrated webhooks</figcaption></figure><h3>Step 7: Create your first release and publication</h3><p>At this point, your soon-to-be package should look similar to this:</p><pre>your_package/<br>   __init__.py<br>   your_module.py</pre><pre>docs/<br>tests/<br>setup.py<br>travis.yml<br>appveyor.yml<br>.coveragerc<br>.codecov.yml<br>README.md<br>LICENSE</pre><pre>.github/<br>   CODE_OF_CONDUCT.md<br>   CONTRIBUTING.md<br>   PULL_REQUEST_TEMPLATE.md<br>   ISSUE_TEMPLATE/</pre><p>It’s now ready to be published! The first thing to do is to create your first release on GitHub — this is to keep track of the state of your project at a given point in time, a release should be created each time the version changes. You can follow <a href="https://help.github.com/en/articles/creating-releases">this</a> to create the release.</p><p>Once done, the only thing left to do is to publish your package. The most common platforms to publish a python package are <a href="https://pypi.org/">PyPI</a> and <a href="https://conda.io/en/latest/">Conda</a>. We will describe how to publish in both:</p><ul><li><strong>For PyPI</strong>, you first need to create an <a href="https://pypi.org/account/register/">account</a>, and then follow these <a href="https://realpython.com/pypi-publish-python-package/">steps</a> using twine. This should be fairly straightforward, and PyPI also provides a test environment that can be used right before the actual deploy. The latter basically consists of creating a source distribution (python setup.py sdist) and uploading it with twine (twine upload dist/*). Once done, there should be a PyPI page corresponding to your package (here’s S<a href="https://pypi.org/project/scitime/0.0.2/">citime’s</a>) and anyone should be able to install your package running the pip command.</li><li><strong>For conda</strong>, we recommend publishing your package through <a href="https://conda-forge.org/">conda-forge</a> which is a community that helps you publish and maintain your package through their conda channel. You can follow these <a href="https://conda-forge.org/#add_recipe">steps</a> to add your package to the community, you will then be added to the conda-forge GitHub <a href="https://github.com/conda-forge">organization</a> and be able to maintain your package quite easily (here’s Scitime’s conda-forge <a href="https://anaconda.org/conda-forge/scitime">page</a>) — anyone should then be able to install your package running the conda command.</li></ul><h3>All done!</h3><p>You should now have your package finally published and available to anyone! Although most of the work is done, you’ll still have to maintain your project as you need to make some updates: this basically means changing the versions each time you make significant changes, creating new releases and going through step 7 again.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c34cb7139a22" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/from-a-python-project-to-an-open-source-package-an-a-to-z-guide-c34cb7139a22">From a python project to an open source package: an A to Z guide</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Two hours later and still running? How to keep your sklearn.fit under control.]]></title>
            <link>https://medium.com/free-code-camp/two-hours-later-and-still-running-how-to-keep-your-sklearn-fit-under-control-cc603dc1283b?source=rss-90c8085403a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc603dc1283b</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-sc]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[timer]]></category>
            <dc:creator><![CDATA[Nathan Toubiana]]></dc:creator>
            <pubDate>Wed, 13 Mar 2019 15:36:10 GMT</pubDate>
            <atom:updated>2019-03-18T21:45:49.549Z</atom:updated>
            <content:encoded><![CDATA[<h3>Two hours later and still running? How to keep your sklearn.fit under control</h3><p><em>Written by </em><a href="https://medium.com/@gabi10004"><em>Gabriel Lerner</em></a><em> and </em><a href="https://medium.com/@toubiana.nathan"><em>Nathan Toubiana</em></a></p><p>All you wanted to do was test your code, yet two hours later your Scikit-learn fit shows no sign of ever finishing. Scitime is a package that predicts the runtime of machine learning algorithms so that you will not be caught off guard by an endless fit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aVzJTznRRfP1lM7AXe9yLw.jpeg" /><figcaption>Image by Kevin Ku on <a href="https://unsplash.com/photos/aiyBwbrWWlo">unsplash.com</a></figcaption></figure><p>Whether you are in the process of building a machine learning model or deploying your code to production, knowledge of how long your algorithm will take to fit is key to streamlining your workflow. With Scitime you will be able in a matter of seconds to estimate how long the fit should take for the most commonly used Scikit Learn algorithms.</p><p>There have been a couple of research articles (such as <a href="https://www.sciencedirect.com/science/article/pii/S0004370213001082">this one</a>) published on that subject. However, as far as we know, there’s no practical implementation of it. The goal here is not to predict the exact runtime of the algorithm but more to give a rough approximation.</p><h3>What is Scitime?</h3><p>Scitime is a python package requiring at least python 3.6 with <a href="https://github.com/pandas-dev/pandas">pandas</a>, <a href="https://github.com/scikit-learn/scikit-learn">scikit-learn</a>, <a href="https://github.com/giampaolo/psutil">psutil</a> and <a href="https://github.com/joblib/joblib">joblib</a> dependencies. You will find the Scitime repo <a href="https://github.com/nathan-toubiana/scitime">here</a>.</p><p>The main function in this package is called “<em>time</em>”. Given a matrix vector X, the estimated vector Y along with the Scikit Learn model of your choice, <em>time</em> will output both the estimated time and its confidence interval. The package currently supports the following Scikit Learn algorithms with plans to add more in the near future:</p><ul><li><a href="https://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html">KMeans</a></li><li><a href="https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestRegressor.html">RandomForestRegressor</a></li><li><a href="https://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html">SVC</a></li><li><a href="https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html">RandomForestClassifier</a></li></ul><h3>Quick Start</h3><p>Let’s install the package and run the basics.</p><p>First create a new virtualenv (this is optional, to avoid any version conflicts!)</p><pre>❱ virtualenv env<br>❱ source env/bin/activate</pre><p>and then run:</p><pre>❱ (env) pip install scitime</pre><p>or with conda:</p><pre>❱ (env) conda install -c conda-forge scitime</pre><p>Once the installation has succeeded, you are ready to estimate the time of your first algorithm.</p><p>Let’s say you wanted to train a kmeans clustering, for example. You would first need to import the scikit-learn package, set the kmeans parameters, and also choose the inputs (a.k.a <em>X)</em>, here generated <a href="https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_blobs.html#sklearn.datasets.make_blobs">randomly</a> for simplicity.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03cd1ab29b3838848d1320ad4621bb44/href">https://medium.com/media/03cd1ab29b3838848d1320ad4621bb44/href</a></iframe><p>Running this before doing the actual fit would give an approximation of the runtime:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf5a067fae01d17f7cbbece972e498c5/href">https://medium.com/media/cf5a067fae01d17f7cbbece972e498c5/href</a></iframe><p>As you can see, you can get this info only in one extra line of code! The inputs of the <em>time</em> function are exactly what’s needed to run the fit (that is the algo itself, and X), which makes it even easier to use.</p><p>Looking more closely at the last line of the above code, the first output (<em>estimation: </em>15 seconds in this case) is the predicted runtime you’re looking for. Scitime will also output it with a confidence interval (<em>lower_bound</em> and <em>upper_bound: </em>10 and 30 seconds in this case). You can always compare it to the actual training time by running:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/14d002c295944f1f9e50f6b82538d654/href">https://medium.com/media/14d002c295944f1f9e50f6b82538d654/href</a></iframe><p>In this case, on our local machine, the estimation is 15 seconds, whereas the actual training time is 20 seconds (but you might not get the same results, as we’ll explain later).</p><p><strong>As a quick usage guide:</strong></p><p><em>Estimator(meta_algo, verbose, confidence) class:</em></p><ul><li><strong>meta_algo</strong>: The estimator used to predict the time, either ‘RF’ or ‘NN’ (see details in next paragraph) — defaults to‘RF’</li><li><strong>verbose</strong>: Control of the amount of log output (either 0, 1, 2 or 3) — defaults to 0</li><li><strong>confidence</strong>: Confidence for intervals — defaults to 95%</li></ul><p><em>estimator.time(algo, X, y) function:</em></p><ul><li><strong>algo</strong>: algo whose runtime the user wants to predict</li><li><strong>X</strong>: numpy array of inputs to be trained</li><li><strong>y</strong>: numpy array of outputs to be trained (set to <em>None</em> if the algo is unsupervised)</li></ul><p>Quick note: to avoid any confusion, it’s worth highlighting that <strong>algo</strong> and <strong>meta_algo</strong> are two different things here: <strong>algo</strong> is the algorithm whose runtime we want to estimate, <strong>meta_algo</strong> is the algorithm used by Scitime to predict the runtime.</p><h3>How Scitime works</h3><p>We are able to predict the runtime to fit by using our own estimator, we call it meta algorithm (<em>meta_algo</em>), whose weights are stored in a dedicated pickle file in the package metadata. For each Scikit Learn model, you will find a corresponding meta algo pickle file in Scitime’s code base.</p><p>You might be thinking:</p><blockquote>Why not manually estimate the time complexity with big O notations?</blockquote><p>That’s a fair point. It’s a valid way of approaching the problem and something we thought about at the beginning of the project. One thing however is that we would need to formulate the complexity explicitly for each algo and set of parameters which is rather challenging in some cases, given the number of factors playing a role in the runtime. The meta_algo basically does all the work for you, and we’ll explain how.</p><p>Two types of meta algos have been trained to estimate the time to fit (both from Scikit Learn):</p><ul><li>The <strong>RF</strong> meta algo, a <a href="https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestRegressor.html">RandomForestRegressor</a> estimator.</li><li>The <strong>NN</strong> meta algo, a basic <a href="https://scikit-learn.org/stable/modules/generated/sklearn.neural_network.MLPRegressor.html">MLPRegressor</a> estimator.</li></ul><p>These meta algos estimate the time to fit using an array of ‘meta’ features. Here’s a summary of how we build these features:</p><p>Firstly, we fetch the shape of your input matrix X and output vector y. Second, the parameters you feed to the Scikit Learn model are taken into consideration as they will impact the training time as well. Lastly, your specific hardware, unique to your machine such as available memory and cpu counts are also considered.</p><p>As shown earlier, we also provide confidence intervals on the time prediction. The way these are computed depends on the meta algo chosen:</p><ul><li>For <strong>RF</strong>, since any random forest regressor is a combination of multiple trees (also called <em>estimators</em>), the confidence interval will be based on the distribution of the set of predictions computed by each estimator.</li><li>For <strong>NN</strong>, the process is a little less straightforward: we first compute a set of <a href="https://en.wikipedia.org/wiki/Mean_squared_error">MSE</a>s along with the number of observations on a test set, grouped by predicted duration bins (that is from 0 to 1 second, 1 to 5 seconds, and so on), and we then compute a <a href="https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.stats.t.html">t-stat</a> to get the lower and upper bounds of the estimation. As we don’t have a lot of data for very long models, the confidence interval for such data might get very broad.</li></ul><h3>How we built it</h3><p>You might be thinking:</p><blockquote>How did you get enough data on the training time of all these sciki- learn fits over various parameters and hardware configurations?</blockquote><p>The (unglamorous) answer is we generated the data ourselves using a combination of computers and VM hardwares to simulate what the training time would be on the different systems. We then fitted our meta algos on these randomly generated data points to build an estimator meant to be reliable regardless of your system.</p><p>While the <a href="https://github.com/nathan-toubiana/scitime/blob/master/scitime/estimate.py">estimate.py</a> file handles the runtime prediction, the <a href="https://github.com/nathan-toubiana/scitime/blob/master/scitime/_model.py"><em>_model.py</em></a> file helped us generate data to train our meta algos, using our dedicated Model class. Here’s a corresponding code sample, for kmeans:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c8964fd82e3d580bf2e284f56ae2c1a/href">https://medium.com/media/1c8964fd82e3d580bf2e284f56ae2c1a/href</a></iframe><p>Note that you can also use the file <a href="https://github.com/nathan-toubiana/scitime/blob/master/_data.py"><em>_data.py</em></a> directly with the command line to generate data or train a new model. Related instructions can be found in the repo Readme file.</p><p>When generating data points, you can edit the parameters of the Scikit Learn models you want to train on. You can head to <a href="https://github.com/nathan-toubiana/scitime/blob/master/scitime/_config.json"><em>scitime/_config.json</em></a> and edit the parameters of the models as well as the number of rows and columns you would want to train with.</p><p>We use an <a href="https://docs.python.org/2/library/itertools.html#itertools.product">itertool</a> function to loop through every possible combination, along with a drop rate set between 0 and 1 to control how quickly the loop will jump through the different possible iterations.</p><h3>How accurate is Scitime?</h3><p>Below, we highlight how our predictions perform for the specific case of kmeans. Our generated dataset contains ~100k data points, which we split into a train and test sets (75% — 25%).</p><p>We grouped training predicted times by different time buckets and computed the <a href="https://en.wikipedia.org/wiki/Mean_absolute_percentage_error">MAPE</a> and <a href="https://en.wikipedia.org/wiki/Root-mean-square_deviation">RMSE</a> over each of those buckets for all our estimators using the RF meta-algo and the NN meta-algo.</p><p>Please note that these results were performed on a restricted data set, so they might be different on unexplored data points (such as other systems / extreme values of certain model parameters). For this specific training set, the <a href="https://en.wikipedia.org/wiki/Coefficient_of_determination">R-squared</a> is around 80% for NN and 90% for RF.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=%2F%2Fembed.chartblocks.com%2F1.0%2F%3Fc%3D5c51ad613ba0f67f019825ef%26t%3D85cd6e8548ffbde&amp;url=https%3A%2F%2Fpublic.chartblocks.com%2Fc%2F5c51ad613ba0f67f019825ef%3Ft%3D85cd6e8548ffbde&amp;image=https%3A%2F%2Fwww.gravatar.com%2Favatar%2F88db25f59181d9e605b35cd92ffb16c9%3Fd%3Dmm&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=chartblocks" width="800" height="450" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f8793b215b2d8ed62ced89337a0b95b/href">https://medium.com/media/4f8793b215b2d8ed62ced89337a0b95b/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=%2F%2Fembed.chartblocks.com%2F1.0%2F%3Fc%3D5c51afcd3ba0f6bc019825f1%26t%3Db12fe48d8a6c219&amp;url=https%3A%2F%2Fpublic.chartblocks.com%2Fc%2F5c51afcd3ba0f6bc019825f1%3Ft%3Db12fe48d8a6c219&amp;image=https%3A%2F%2Fwww.gravatar.com%2Favatar%2F88db25f59181d9e605b35cd92ffb16c9%3Fd%3Dmm&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=chartblocks" width="800" height="450" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b0b65e9418d604839ebc03592c2572f/href">https://medium.com/media/5b0b65e9418d604839ebc03592c2572f/href</a></iframe><p>As we can see, not surprisingly, the accuracy is consistently higher on the train set than on the test, for both NN and RF. We also see that RF seems to perform way better than NN overall. The MAPE for RF is around 20% on the train set and 40% on the test set. The NN MAPE is surprisingly very high.</p><p>Let’s slice the MAPE (on test set) by the number of predicted seconds:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=%2F%2Fembed.chartblocks.com%2F1.0%2F%3Fc%3D5c51b1f43ba0f62c039825ef%26t%3D9f4eeaef6599bd0&amp;url=https%3A%2F%2Fpublic.chartblocks.com%2Fc%2F5c51b1f43ba0f62c039825ef%3Ft%3D9f4eeaef6599bd0&amp;image=https%3A%2F%2Fwww.gravatar.com%2Favatar%2F88db25f59181d9e605b35cd92ffb16c9%3Fd%3Dmm&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=chartblocks" width="800" height="450" frameborder="0" scrolling="no"><a href="https://medium.com/media/d9816221485f368e46a83ac8e58491e1/href">https://medium.com/media/d9816221485f368e46a83ac8e58491e1/href</a></iframe><p>One important thing to keep in mind is that for some cases the time prediction is sensitive to the meta algo chosen (RF or NN). In our experience RF has performed very well within the data set input ranges, as shown above. However, for out of range points, NN might perform better, as suggested by the end of the above chart. This would explain why NN MAPE is quite high while the RMSE is decent: it performs poorly on small values.</p><p>As an example, if you try to predict the runtime of a kmeans with default parameters and with an input matrix of a few thousand lines, the RF meta algo will be precise because our training dataset contains similar data points. However, for predicting very specific parameters (for instance, a very high number of clusters), NN might perform better because it extrapolates from the training set, whereas RF doesn’t. NN performs worse on the above charts because these plots are only based on data close to the set of inputs of the training data.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=%2F%2Fembed.chartblocks.com%2F1.0%2F%3Fc%3D5c5129e83ba0f605529825ef%26t%3D80647ceb4f87f55&amp;url=https%3A%2F%2Fpublic.chartblocks.com%2Fc%2F5c5129e83ba0f605529825ef%3Ft%3D80647ceb4f87f55&amp;image=https%3A%2F%2Fwww.gravatar.com%2Favatar%2F88db25f59181d9e605b35cd92ffb16c9%3Fd%3Dmm&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=chartblocks" width="800" height="450" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4b972e6fdc303112561e5493ec6426c/href">https://medium.com/media/a4b972e6fdc303112561e5493ec6426c/href</a></iframe><p>However, as shown in this graph, the out of range values (thin lines) are extrapolated by the NN estimator, whereas the RF estimator predicts the output stepwise.</p><p>Now let’s look at the most important ‘meta’ features for the example of kmeans:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=%2F%2Fembed.chartblocks.com%2F1.0%2F%3Fc%3D5c51dc593ba0f6aa119825ef%26t%3D419ebdf96bb2529&amp;url=https%3A%2F%2Fpublic.chartblocks.com%2Fc%2F5c51dc593ba0f6aa119825ef%3Ft%3D419ebdf96bb2529&amp;image=https%3A%2F%2Fwww.gravatar.com%2Favatar%2F88db25f59181d9e605b35cd92ffb16c9%3Fd%3Dmm&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=chartblocks" width="800" height="450" frameborder="0" scrolling="no"><a href="https://medium.com/media/6aa56fe234707d1969b78b1aa0b30e29/href">https://medium.com/media/6aa56fe234707d1969b78b1aa0b30e29/href</a></iframe><p>As we can see, only 6 features account for more than 80% of the model variance. Among them, the most important is a parameter of the scikit-learn kmeans class itself (number of clusters), but a lot of external factors have great influence on the runtime such as number of rows/columns and available memory.</p><h3>Limitations</h3><p>As mentioned earlier, the first limitation is related to the confidence intervals: they may be very wide, especially for NN, and for heavy models (that would take at least an hour).</p><p>Additionally, the NN might perform poorly on small to medium predictions. Sometimes, for small durations, the NN might even predict a negative duration, in which case we automatically switch back to RF.</p><p>Another limitation of the estimator arise for when ‘special’ algo parameter values are used. For example, in a RandomForest scenario, when max_depth is set to <em>None</em>, the depth could take any value. This might result in a much longer time to fit which is more difficult for the meta algo to pick up, although we did our best to account for them.</p><p>When running <em>estimator.time(algo, X, y)</em> we do require the user to enter the actual X and y vector which seems unnecessary, as we could simply request the shape of the data to estimate the training time. The reason for this is that we actually try to fit the model before predicting the runtime, in order to raise any instant errors. We run <em>algo.fit(X, y)</em> in a subprocess for one second to check for any fit error up after which we move on to the prediction part. However, there are times where the algo (and / or the input matrix) are so big that running <em>algo.fit(X,y)</em> will throw a memory error eventually, which we can’t account for.</p><h3>Future improvements</h3><p>The most effective and obvious way to improve the performance of our current predictions would be to generate more data points on different systems to better support a wide range of hardware/parameters.</p><p>We will be looking at adding more supported Scikit Learn algos in the near future. We could also implement other algos such as <a href="https://github.com/Microsoft/LightGBM">lightGBM</a> or <a href="https://github.com/dmlc/xgboost">xgboost</a>. Feel free to contact us if there’s an algorithm you would like us to implement in the next iterations of Scitime!</p><p>Other interesting avenues for improving the performance of the estimator would be to include more granular information about the input matrix such as variance, or correlation with output. We currently generate data completely randomly, for which the fit time might be higher than for real world datasets. So in some cases it might overestimate the training time.</p><p>In addition we could track finer hardware specific information such as frequency of the cpu, or current cpu usage.</p><p>Ideally, as the algorithm might change from a scikit-learn version to another, and thus have an impact on the runtime, we would also account for it, for example by using the version as a ‘meta’ feature.</p><p>As we acquire more data to fit our meta algos, we might think of using more complex meta algos, such as sophisticated neural networks (using regularization techniques like dropout or batch normalization). We could even consider using <a href="https://www.tensorflow.org/">tensorflow</a> to fit the meta algo (and add it as optional): it would not only help us get a better accuracy, but also build more robust confidence intervals using <a href="https://towardsdatascience.com/uncertainty-estimation-for-neural-network-dropout-as-bayesian-approximation-7d30fc7bc1f2">dropout</a>.</p><h3>Contributing to Scitime and sending us your feedback</h3><p>First, any kind of feedback, especially on the performance of the predictions and on ideas to improve this process of generating data, is very much appreciated!</p><p>As discussed before, you can use our repo to generate your own data points in order to train your own meta algorithm. When doing so, you can help make Scitime better by sharing your data points found in the result csv (<em>~/scitime/scitime/[algo]_results.csv</em>) so that we can integrate it to our model.</p><p>To generate your own data you can run a command similar to this one (from the package repo source):</p><pre>❱ python _data.py --verbose 3 --algo KMeans --drop_rate 0.99</pre><p>Note: if run directly using the code source (with the <em>Model</em> class), do not forget to set <em>write_csv</em> to true, otherwise the generated data points will not be saved.</p><p><em>We use GitHub issues to track all bugs and feature requests. Feel free to open an issue if you have found a bug or wish to see a new feature implemented. More info can be found about how to contribute in the Scitime repo.</em></p><p><em>For issues with training time predictions, when submitting feedback, including the full dictionary of parameters you are fitting into your model might help, so that we can diagnose why the performance is subpar for your specific use case. To do so simply set the verbose parameter to 3 and copy paste the log of the parameter dic in the issue description.</em></p><p><em>Find the </em><a href="https://github.com/nathan-toubiana/scitime"><em>code source</em></a></p><p><em>Find the </em><a href="https://scitime.readthedocs.io/"><em>documentation</em></a></p><h3>Credits</h3><ul><li><a href="https://github.com/gabrielRTR"><em>Gabriel Lerner</em></a><em> &amp; </em><a href="https://github.com/nathan-toubiana"><em>Nathan Toubiana</em></a><em> are the main contributors of this package and co-authors of this article</em></li><li><em>Special thanks to </em><a href="https://github.com/philippemizrahi"><em>Philippe Mizrahi</em></a><em> for helping along the way</em></li><li><em>Thanks for all the help we got from early reviews / beta testing</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc603dc1283b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/two-hours-later-and-still-running-how-to-keep-your-sklearn-fit-under-control-cc603dc1283b">Two hours later and still running? How to keep your sklearn.fit under control.</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>