{"id":81,"date":"2013-09-23T00:56:59","date_gmt":"2013-09-23T06:56:59","guid":{"rendered":"http:\/\/inductivebias.com\/Blog\/?p=81"},"modified":"2014-05-05T04:03:30","modified_gmt":"2014-05-05T10:03:30","slug":"least-squares-curve-fitting","status":"publish","type":"post","link":"http:\/\/inductivebias.com\/Blog\/least-squares-curve-fitting\/","title":{"rendered":"Least Squares Curve Fitting"},"content":{"rendered":"<div style=\"word-wrap: normal; -webkit-hyphens: none; -moz-hyphens: none; hyphens: none;\"><span style=\"font-size: small;\"><strong><a href=\"http:\/\/inductivebias.com\/Blog\/wp-content\/uploads\/2013\/09\/LeastSquaresPoly5.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"size-thumbnail wp-image-88 alignleft\" alt=\"LeastSquaresPoly5\" src=\"http:\/\/inductivebias.com\/Blog\/wp-content\/uploads\/2013\/09\/LeastSquaresPoly5-150x150.jpg\" width=\"150\" height=\"150\" srcset=\"http:\/\/inductivebias.com\/Blog\/wp-content\/uploads\/2013\/09\/LeastSquaresPoly5-150x150.jpg 150w, http:\/\/inductivebias.com\/Blog\/wp-content\/uploads\/2013\/09\/LeastSquaresPoly5.jpg 300w\" sizes=\"auto, (max-width: 150px) 100vw, 150px\" \/><\/a>Today we&#8217;re talking about linear least squares curve fitting, but don&#8217;t be fooled by the name. I&#8217;ll show how to use it to fit polynomials and other functions, how to derive it, and how to calculate it efficiently using a Cholesky matrix decomposition.<\/strong><\/span><!--more--><\/p>\n<p style=\"text-align: left;\">\nWe&#8217;ve got one set of input vectors where each one also has a corresponding output vector, and we&#8217;ve got a second set of input vectors that don&#8217;t yet have outputs. We want to learn the relationship between inputs and outputs using the first group and then use it to predict the outputs for the second group. This is your classic supervised learning problem, but unlike the Naive Bayes algorithm in the last post, this time we want to get actual numbers, not just which class the input belongs to.\u00a0 We can do this by fitting a line or a polynomial to our data, and both of these functions can be fit using linear least squares.\n<\/p>\n<h2><span style=\"color: #000080;\">Derivation<\/span><\/h2>\n<p>Let&#8217;s say we have an input vector X, and we want to find the linear function that best predicts an output scalar y. That is y = C*X (C dot X) where C is the vector of coefficients we&#8217;re solving for. In reality we have several X&#8217;s each with it&#8217;s own y, so X becomes a matrix with each row being a single input vector and Y becomes a vector of all of the outputs for each input vector.<\/p>\n<p style=\"text-align: center;\"><img src='http:\/\/l.wordpress.com\/latex.php?latex=%5Cbegin%7Bbmatrix%7D%20X_1%20%5C%5C%20X_2%20%5C%5C%20...%20%5Cend%7Bbmatrix%7D%20C%20%3D%20%5Cbegin%7Bbmatrix%7D%20y_1%20%5C%5C%20y_2%20%5C%5C%20...%20%5Cend%7Bbmatrix%7D&amp;bg=FFFFFF&#038;fg=000000&#038;s=2' title='\\begin{bmatrix} X_1 \\\\ X_2 \\\\ ... \\end{bmatrix} C = \\begin{bmatrix} y_1 \\\\ y_2 \\\\ ... \\end{bmatrix}' style='vertical-align:1%' class='tex' alt='\\begin{bmatrix} X_1 \\\\ X_2 \\\\ ... \\end{bmatrix} C = \\begin{bmatrix} y_1 \\\\ y_2 \\\\ ... \\end{bmatrix}' \/><\/p>\n<p style=\"text-align: left;\">If the number of training points is exactly the same as the length of an input vector of a training point then the X matrix will be square and all we have to do is solve the resulting system of linear equations for the C vector.\u00a0 Barring some sort of matrix singularity, this C vector will produce a function which goes perfectly through all of the training points. Realistically, the number of training points (think thousands) will far exceed the number of input variables (think dozens). It&#8217;s usually not possible to pick a C which perfectly hits every training point, so we have to pick one that fits them as well as possible. In the case of least squares this means picking the one that gets the least sum of squares of the error for each training point, hence the name of the algorithm.<\/p>\n<p style=\"text-align: center;\"><img src='http:\/\/l.wordpress.com\/latex.php?latex=%5Cunderset%7BC%7D%7B%5Carg%5Cmin%7D%20%28XC-Y%29%5E2&amp;bg=FFFFFF&#038;fg=000000&#038;s=2' title='\\underset{C}{\\arg\\min} (XC-Y)^2' style='vertical-align:1%' class='tex' alt='\\underset{C}{\\arg\\min} (XC-Y)^2' \/><\/p>\n<p style=\"text-align: left;\">That is, we want to find the C vector that gives the minimum value if we multiplied it by our X matrix and subtracted the desired output and squared it. How do we do this? It&#8217;s simple calculus. Remember <a href=\"http:\/\/en.wikipedia.org\/wiki\/Fermat%27s_theorem_%28stationary_points%29\">Fermat&#8217;s theorem<\/a>? Probably not by name, but it&#8217;s the thing where you set the derivative equal to zero to find minimums and maximums.<\/p>\n<p style=\"text-align: center;\">\u00a0<img src='http:\/\/l.wordpress.com\/latex.php?latex=f%28X%29%20%3D%20%28XC-Y%29%5E2%5C%5C%20%7B%7B%5Cpartial%20f%7D%20%5Cover%20%7B%5Cpartial%20C%7D%20%7D%20%3D%202%7BX%5ET%7D%28XC-Y%29%20%3D%200%5C%5C%202%7BX%5ET%7DXC-2%7BX%5ET%7DY%20%3D%200%5C%5C%20%7BX%5ET%7DXC%20%3D%20%7BX%5ET%7DY%20&amp;bg=FFFFFF&#038;fg=000000&#038;s=2' title='f(X) = (XC-Y)^2\\\\ {{\\partial f} \\over {\\partial C} } = 2{X^T}(XC-Y) = 0\\\\ 2{X^T}XC-2{X^T}Y = 0\\\\ {X^T}XC = {X^T}Y ' style='vertical-align:1%' class='tex' alt='f(X) = (XC-Y)^2\\\\ {{\\partial f} \\over {\\partial C} } = 2{X^T}(XC-Y) = 0\\\\ 2{X^T}XC-2{X^T}Y = 0\\\\ {X^T}XC = {X^T}Y ' \/><\/p>\n<p style=\"text-align: left;\">This looks exactly like our previous formula except with an X transposed prefacing each side. If X is an n by m matrix where n is the number of data points and m is the length of an input vector then X^T * X will be m by m and X^T * Y will be m by 1. This is good because it means the system of equations we need to solve to find C is square, so it has a unique solution, but its size is also independent of the number of training\u00a0 points. In addition any matrix of the form X^T * X has a few other useful properties we can take advantage of. Specifically, it is symmetric (that is Mij = Mji), and it is positive definite (that is a^T X a &gt; 0 for all a). The savings from symmetricness is fairly straightforward: almost half of the matrix doesn&#8217;t need to be calculated or considered because it&#8217;s going to be the same as the other half. The positive definiteness guarantees that out solution is a minimum, and it turns out to be a requirement for the method we&#8217;ll use.<\/p>\n<h2 style=\"word-wrap: normal; -webkit-hyphens: none; -moz-hyphens: none; hyphens: none;\"><span style=\"color: #000080;\">Solving the System of Equations<br \/>\n<\/span><\/h2>\n<p style=\"text-align: left;\">At this point we have a system of linear equations which we could solve using your generic linear algebra class Gaussian elimination. However, that&#8217;s not a very good idea for two reasons: it&#8217;s\u00a0unstable and it&#8217;s slow.\u00a0 Unstable in this case meaning the loss of precision from using computer arithmetic will be compounded by the operation, and slow meaning, well, slow.<\/p>\n<p style=\"text-align: left;\">There are two algorithms I consider good candidates for solving this problem: Cholesky decomposition and QR decomposition.\u00a0 Both of these techniques work by breaking the matrix into two matrices that produce a problem which is easier (i.e. computationally cheaper) to solve. The primary difference being that the Cholesky runs on the already calculated X^T*X, while the QR computes its factorization of X^T*X directly from X itself.\u00a0 The QR is a bit more stable since some accuracy is lost when computing X^T*X, but the Cholesky is faster and in my experience plenty stable enough. We&#8217;ll be using the Cholesky today. Let our X^T * X be A, and the Cholesky decomposition is arranged as follows.<\/p>\n<p style=\"text-align: center;\"><a href=\"http:\/\/inductivebias.com\/Blog\/wp-content\/uploads\/2013\/09\/WikipediaCholesky.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-129\" alt=\"WikipediaCholesky\" src=\"http:\/\/inductivebias.com\/Blog\/wp-content\/uploads\/2013\/09\/WikipediaCholesky.png\" width=\"497\" height=\"152\" srcset=\"http:\/\/inductivebias.com\/Blog\/wp-content\/uploads\/2013\/09\/WikipediaCholesky.png 497w, http:\/\/inductivebias.com\/Blog\/wp-content\/uploads\/2013\/09\/WikipediaCholesky-300x91.png 300w\" sizes=\"auto, (max-width: 497px) 100vw, 497px\" \/><\/a><\/p>\n<p style=\"text-align: left;\">The important thing to note here is that L is lower diagonal. This means solving a system of equations with it is as simple as back-substitution.\u00a0 I&#8217;m not going to go much into the derivation of the decomposition itself, but suffice to say you could set the multiplied out form equal to A and work out the formulas. One of which looks like the following:<\/p>\n<p style=\"text-align: center;\"><a href=\"http:\/\/inductivebias.com\/Blog\/wp-content\/uploads\/2013\/09\/WikipediaCholeskyFormula.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-130\" alt=\"WikipediaCholeskyFormula\" src=\"http:\/\/inductivebias.com\/Blog\/wp-content\/uploads\/2013\/09\/WikipediaCholeskyFormula.png\" width=\"194\" height=\"60\" \/><\/a><\/p>\n<p style=\"text-align: left;\">If you looked at this and immediately thought &#8220;well, that seems silly to take the square root and then just end up multiplying it back together in the next step&#8221; then congratulations you&#8217;re smarter than I am. I&#8217;m pretty sure I had to be told that it&#8217;s possible to factor out the diagonal terms in a separate matrix D and avoid those square-roots entirely without really adding any extra work. This form is called the LDL decomposition, and it looks something like this:<\/p>\n<p style=\"text-align: center;\"><a href=\"http:\/\/inductivebias.com\/Blog\/wp-content\/uploads\/2013\/09\/LDL.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-132\" alt=\"LDL\" src=\"http:\/\/inductivebias.com\/Blog\/wp-content\/uploads\/2013\/09\/LDL.png\" width=\"579\" height=\"152\" srcset=\"http:\/\/inductivebias.com\/Blog\/wp-content\/uploads\/2013\/09\/LDL.png 579w, http:\/\/inductivebias.com\/Blog\/wp-content\/uploads\/2013\/09\/LDL-300x78.png 300w\" sizes=\"auto, (max-width: 579px) 100vw, 579px\" \/><\/a><\/p>\n<p style=\"text-align: center;\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-133\" alt=\"LDLformula1\" src=\"http:\/\/inductivebias.com\/Blog\/wp-content\/uploads\/2013\/09\/LDLformula1.png\" width=\"184\" height=\"53\" \/><\/p>\n<p style=\"text-align: center;\"><a href=\"http:\/\/inductivebias.com\/Blog\/wp-content\/uploads\/2013\/09\/LDLFormula2.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-134\" alt=\"LDLFormula2\" src=\"http:\/\/inductivebias.com\/Blog\/wp-content\/uploads\/2013\/09\/LDLFormula2.png\" width=\"403\" height=\"60\" srcset=\"http:\/\/inductivebias.com\/Blog\/wp-content\/uploads\/2013\/09\/LDLFormula2.png 403w, http:\/\/inductivebias.com\/Blog\/wp-content\/uploads\/2013\/09\/LDLFormula2-300x44.png 300w\" sizes=\"auto, (max-width: 403px) 100vw, 403px\" \/><\/a><\/p>\n<p style=\"text-align: left;\">This is what I recommend using to solve linear least squares problems. Calculating the decomposition is as simple as just plugging these formulas into your code, but you do need to be a bit careful as both formulas make use of earlier calculations of each other. You have to walk through and calculate the D&#8217;s for each row at the same time you calculate a row of L.<\/p>\n<p style=\"text-align: left;\"><script src=\"https:\/\/gist.github.com\/6666615.js\"><\/script><noscript><pre><code class=\"language-java java\">double[][] L = new double[inputs][ inputs];\ndouble D[] = new double[inputs] ;\n\/\/for each column j\nfor (int j = 0; j &lt; inputs; j++){\n  D[j] = XTX[j][j];\/\/calculate Dj\n  for (int k = 0; k &lt; j; k++){\n    D[j] -= L[j][k] * L[j][k] * D[k];\n  }\n  \/\/calculate jth column of L\n  L[j][j] = 1 ; \/\/ don't really need to save this but its a 1\n  for (int i = j + 1; i &lt; inputs; i++){\n    L[i][j] = XTX[i][j];\n    for (int k = 0; k &lt; j; k++){\n      L[i][j] -= L[i][k] * L[j][k] * D[k];\n    }\n    L[i][j] \/= D[j];\n  }\n}<\/code><\/pre><\/noscript><\/p>\n<p style=\"text-align: left;\">Alright, so you&#8217;ve got L and D factors of your X^T*X, but what you really want to do is solve for C back in the original equations. This can be achieved by solving the system of equations with each matrix from the outside to the inside. Since L is triangular, forward substitution can be used to solve for what D(L^T)C should equal. Since D is diagonal a few divisions will give us what (L^T)c should equal. Finally, a step of backward substitution gives us the final C.<\/p>\n<p style=\"text-align: left;\"><img src='http:\/\/l.wordpress.com\/latex.php?latex=%7BX%5ET%7D%20X%20C%20%3D%20%7BX%5ET%7D%20Y%20&amp;bg=FFFFFF&#038;fg=000000&#038;s=2' title='{X^T} X C = {X^T} Y ' style='vertical-align:1%' class='tex' alt='{X^T} X C = {X^T} Y ' \/> Original equation<\/p>\n<p><img src='http:\/\/l.wordpress.com\/latex.php?latex=L%20D%20%7BL%5ET%7D%20C%20%3D%20B&amp;bg=FFFFFF&#038;fg=000000&#038;s=2' title='L D {L^T} C = B' style='vertical-align:1%' class='tex' alt='L D {L^T} C = B' \/> stick in the LDL and rename RHS<\/p>\n<p><img src='http:\/\/l.wordpress.com\/latex.php?latex=L%20p%20%3D%20B&amp;bg=FFFFFF&#038;fg=000000&#038;s=2' title='L p = B' style='vertical-align:1%' class='tex' alt='L p = B' \/> solve this with forward substitution<\/p>\n<p><img src='http:\/\/l.wordpress.com\/latex.php?latex=D%20%7BL%5ET%7D%20C%20%3Dp&amp;bg=FFFFFF&#038;fg=000000&#038;s=2' title='D {L^T} C =p' style='vertical-align:1%' class='tex' alt='D {L^T} C =p' \/><\/p>\n<p><img src='http:\/\/l.wordpress.com\/latex.php?latex=D%20q%20%3Dp&amp;bg=FFFFFF&#038;fg=000000&#038;s=2' title='D q =p' style='vertical-align:1%' class='tex' alt='D q =p' \/> solve this with a few divisions<\/p>\n<p><img src='http:\/\/l.wordpress.com\/latex.php?latex=%7BL%5ET%7D%20C%20%3Dq&amp;bg=FFFFFF&#038;fg=000000&#038;s=2' title='{L^T} C =q' style='vertical-align:1%' class='tex' alt='{L^T} C =q' \/> Solve this with backward substitution.<\/p>\n<p style=\"text-align: left;\"><script src=\"https:\/\/gist.github.com\/6666802.js\"><\/script><noscript><pre><code class=\"language-java java\">public double[] solvesystem(double L[][], double D[], double XTY[]){\n  \/\/back substitution with L\n  double p[] = new double[XTY.length] ;\n  for (int j = 0; j &lt; inputs; j++){\n    p[j] = XTY[j] ;\n    for (int i = 0; i &lt; j; i++){\n      p[j] -= L[j][i] * p[i];\n    }\n  }\n  \/\/Multiply by inverse of D matrix\n  double q[] = new double[p.length] ;\n  for (int k = 0; k &lt; inputs; k++){\/\/inverse of diagonal\n    q[k] = p[k]\/D[k];\/\/is 1 \/ each element\n  }\n  \/\/ forward substitution with L^T\n  double c[] = new double[q.length];\n  for (int j = inputs - 1; j &gt;= 0; j--){\n    c[j] = q[j] ;\n    for (int i = j + 1; i &lt; inputs; i++){\n      c[j] -= L[i][j] * c[i];\n    }\n  }\n  return c ;\n}<\/code><\/pre><\/noscript><\/p>\n<h2><span style=\"color: #000080;\">Improvements<\/span><\/h2>\n<p style=\"text-align: left;\">Huzzah, we have achieved linear least squares. The name\u00a0<strong>linear<\/strong> least squares is a bit misleading because it&#8217;s linear in the <em>parameters <\/em>not the <em>input variables<\/em>. In actuality you can do pretty much whatever you want to the input variables as long as you do the same thing before training that you do when you apply the function.\u00a0 Linear least squares will find the best fit linear combination of whatever you feed into it. By far the most common thing I see done is to use polynomials of the data. When given the inputs [a b c] instead of passing them in raw, pass something like [1 a b c a^2 b^2 c^2]\u00a0 then performing the linear least squares fit gives you a quadratic polynomial fit*.<\/p>\n<p style=\"text-align: left;\">There is one more significant improvement that can be made to this algorithm before we can call it a day.\u00a0 The LDL decomposition is the same size as X^T*X, and its construction never references\u00a0 an element of X^T * X for which the L element has already been computed. This means we can compute the entire decomposition in place in a single matrix. We can place the D over top of the diagonal of the L (which is all 1&#8217;s so we don&#8217;t need to save it), and then we proceed to write L and D right on top of where X^T*X used to be.\u00a0 Similarly, we don&#8217;t need to use new vectors to store each of our intermediate substitution steps. We can write p,q, and even c right over top of where X^T*Y used to be.<\/p>\n<p style=\"text-align: left;\">This won&#8217;t save us very many operations, but it can have a significant impact on performance because of the way computer cache works. By accessing less data and accessing it in a very structured sequential way we increase the chance that what we want is already in cache near the processor, and this reduces the number of times our program has to go out to main memory to find what it needs. So without further ado, here&#8217;s the final version of the code which fits a least squares polynomial from multiple inputs to multiple outputs using an in-place LDL decomposition.<\/p>\n<p style=\"text-align: left;\"><script src=\"https:\/\/gist.github.com\/6665144.js\"><\/script><noscript><pre><code class=\"language-java java\">\/\/performs a least squares fit of a polynomial function of the given degree\n\/\/mapping each input[k] vector to each output[k] vector\n\/\/returns the coefficients in a matrix\npublic static double[][] fitpolynomial(double input[][], double output[][], int degree){\n   double[][] X = new double[input.length][];\n   \/\/Run the input through the polynomialization and add the bias term\n   for (int k = 0; k &lt; input.length; k++){\n      X[k] = polynomial(input[k], degree);\n   }\n   int inputs = X[0].length ;\/\/number of inputs after the polynomial\n   int outputs = output[0].length ;\/\/number of outputs\n   int datapoints = X.length ;\/\/number of data points\n   \/\/calculate X^T*X\n   double[][] XTX = new double[inputs][] ;\/\/XTX is symmetric\n   for (int i = 0; i &lt; inputs; i++){\/\/so we only have to\n      XTX[i] = new double[i+1] ;\/\/build the lower triangle\n      for (int j = 0; j &lt;= i; j++){\n         for (int k = 0; k &lt; datapoints; k++){\n            XTX[i][j] += X[k][i] * X[k][j];\n         }\n      }\n   }\n   \/\/calculate the LDL decomposition in place with D over top of the diagonal\n   for (int j = 0; j &lt; inputs; j++){\n      for (int k = 0; k &lt; j; k++){\/\/D starts as XTXjj then subtracts\n         XTX[j][j] -= XTX[j][k] * XTX[j][k] * XTX[k][k];\/\/Ljk^2 * Dk\n      }\n      for (int i = j + 1; i &lt; inputs; i++){\/\/L over the lower diagonal\n         for (int k = 0; k &lt; j; k++){\/\/Lij starts as XTXij then subtracts\n            XTX[i][j] -= XTX[i][k] * XTX[j][k] * XTX[k][k];\/\/Ljk^2*D[k]\n         }\n         XTX[i][j] \/= XTX[j][j];\/\/divide Lij by Dj\n      }\n   }\n   double[][] matrix = new double[outputs][] ;\n   \/\/perform the substitution for each output separately\n   for (int o = 0; o &lt; outputs; o++){\n      double[] XTY = new double[inputs];\n      \/\/multiply this output column by X^T to get RHS of least squares problem\n      for (int j = 0; j &lt; inputs; j++){\n         for (int k = 0; k &lt; datapoints; k++){\n            XTY[j] += output[k][o]* X[k][j];\n         }\n      }\n      \/\/in-place forward substitution with L\n      for (int j = 0; j &lt; inputs; j++){\n         for (int i = 0; i &lt; j; i++){\n            XTY[j] -= XTX[j][i] * XTY[i];\n         }\n      }\n      \/\/Multiply by inverse of D matrix\n      for (int k = 0; k &lt; inputs; k++){\/\/inverse of diagonal\n         XTY[k] \/= XTX[k][k];\/\/is 1 \/ each element\n      }\n      \/\/ in-place backward substitution with L^T\n      for (int j = inputs - 1; j &gt;= 0; j--){\n         for (int i = j + 1; i &lt; inputs; i++){\n            XTY[j] -= XTX[i][j] * XTY[i];\n         }\n      }\n      \/\/copy into final matrix row for this output\n      matrix[o] = XTY;\n   }\n   return matrix ;\n}\n\n\n\/\/applies a polynomial built with the fitpolynomial method\npublic static double[] applypolynomial(double input[], double matrix[][], int degree){\n   double[] i = polynomial(input, degree);\/\/apple the same polynomial\n   double[] o = new double[matrix.length];\n   for (int j = 0; j &lt; o.length; j++){\/\/multiply by the matrix\n      for (int k = 0; k &lt; i.length; k++){\n         o[j] += matrix[j][k] * i[k];\n      }\n   }\n   return o;\/\/return result\n}\n\n\n\/\/Creates a new input vector which is a 1, and each input raised to integer powers up to degree\n\/\/when called with degree=1 this simply adds a bias value to the input vector\n\/\/otherwise it creates a separable polynomial of the given degree\npublic static double[] polynomial(double[] input, int degree)\n{\ndouble[] output = new double[1 + input.length * degree];\/\/1 is for the constant\nint i = 1, k, j;\nfor (k = 0; k &lt; input.length; k++){\n    for (j = 1; j &lt;= degree; j++){\n        output[i] = (double)Math.pow(input[k], j);\n        i++;\n    }\n}\noutput[0] = 1; \/\/constant\nreturn output;\n}<\/code><\/pre><\/noscript><\/p>\n<h2><span style=\"color: #000080;\">Conclusion<\/span><\/h2>\n<p style=\"text-align: left;\">This time I took the liberty of running a few tests to help visualize the results. Here&#8217;s a\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 y = f(x) example with a degree 5 polynomial:<\/p>\n<p style=\"text-align: left;\"><a href=\"http:\/\/inductivebias.com\/Blog\/wp-content\/uploads\/2013\/09\/LeastSquaresPoly5-2.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-142\" alt=\"LeastSquaresPoly5-2\" src=\"http:\/\/inductivebias.com\/Blog\/wp-content\/uploads\/2013\/09\/LeastSquaresPoly5-2.jpg\" width=\"505\" height=\"483\" srcset=\"http:\/\/inductivebias.com\/Blog\/wp-content\/uploads\/2013\/09\/LeastSquaresPoly5-2.jpg 505w, http:\/\/inductivebias.com\/Blog\/wp-content\/uploads\/2013\/09\/LeastSquaresPoly5-2-300x286.jpg 300w\" sizes=\"auto, (max-width: 505px) 100vw, 505px\" \/><\/a><\/p>\n<p style=\"text-align: left;\">And here&#8217;s an f(X,Y) = (R,G,B) test where the polynomial is fit to make the background match the color of the points:<\/p>\n<p style=\"text-align: left;\"><a href=\"http:\/\/inductivebias.com\/Blog\/wp-content\/uploads\/2013\/09\/Poly5colortest.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-143\" alt=\"Poly5colortest\" src=\"http:\/\/inductivebias.com\/Blog\/wp-content\/uploads\/2013\/09\/Poly5colortest.jpg\" width=\"502\" height=\"478\" srcset=\"http:\/\/inductivebias.com\/Blog\/wp-content\/uploads\/2013\/09\/Poly5colortest.jpg 502w, http:\/\/inductivebias.com\/Blog\/wp-content\/uploads\/2013\/09\/Poly5colortest-300x285.jpg 300w\" sizes=\"auto, (max-width: 502px) 100vw, 502px\" \/><\/a><\/p>\n<p style=\"text-align: left;\">The inductive bias of a linear least squares fit curve is that the function you&#8217;re trying to match is a linear combination of the functions you pass in.\u00a0 The complexity of the resultant function will always be exactly what you select up-front, which can be a good or bad thing. Using higher degree polynomials can create unpredictable wiggles between training data, while using lower degree polynomials may not be complex enough to fit your desired function. In either case the resultant function is likely to be wildly inaccurate outside the range of your training data.<\/p>\n<p>Polynomials are inherently smooth. This often works in our favor when dealing with noisy data in that simply fitting the polynomial will act to give us a smoother representation of our data, but it does mean that polynomials may return a soft boundary where in fact a very hard edge exists.<\/p>\n<p style=\"text-align: left;\">Any algorithm that works by way of minimizing squared error will have a weakness to outliers. For instance if you have 10 points with the same input with 9 outputting 0&#8217;s or 1&#8217;s and one outputting 10,000, the resulting least squares function will return 1,000. Often in a case like this it would be better to ignore the wildly differing point, and if you&#8217;re dealing with data where you expect to have some points that are just flat out wrong you may want to consider a different technique.<\/p>\n<p style=\"text-align: left;\">Even considering all the downsides, fitting a polynomial is often one of the first things I try when given a new data-set. It&#8217;s fast, it&#8217;s easy, it works on both classification and regression problems, and I can look at the polynomial itself to get an idea of the basic relationships between variables. It&#8217;s rarely going to give you the highest possible accuracy, but I&#8217;d bet on it over Naive Bayes any day of the week.<\/p>\n<p style=\"text-align: left;\">* Regardless of technique, stability of a polynomial fit is going to depend heavily on the range of your data. I highly recommend normalizing your data points before attempting anything above a quadratic polynomial. This is explained briefly in <a href=\"http:\/\/inductivebias.com\/Blog\/decision-trees-and-forests\/\">the article on decision forests<\/a>.<\/p>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>Today we&#8217;re talking about linear least squares curve fitting, but don&#8217;t be fooled by the name. I&#8217;ll show how to use it to fit polynomials and other functions, how to derive it, and how to calculate it efficiently using a Cholesky matrix decomposition.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[4,5],"tags":[],"class_list":["post-81","post","type-post","status-publish","format-standard","hentry","category-machine-learning-algorithm","category-tutorial"],"_links":{"self":[{"href":"http:\/\/inductivebias.com\/Blog\/wp-json\/wp\/v2\/posts\/81","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/inductivebias.com\/Blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/inductivebias.com\/Blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/inductivebias.com\/Blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/inductivebias.com\/Blog\/wp-json\/wp\/v2\/comments?post=81"}],"version-history":[{"count":63,"href":"http:\/\/inductivebias.com\/Blog\/wp-json\/wp\/v2\/posts\/81\/revisions"}],"predecessor-version":[{"id":284,"href":"http:\/\/inductivebias.com\/Blog\/wp-json\/wp\/v2\/posts\/81\/revisions\/284"}],"wp:attachment":[{"href":"http:\/\/inductivebias.com\/Blog\/wp-json\/wp\/v2\/media?parent=81"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/inductivebias.com\/Blog\/wp-json\/wp\/v2\/categories?post=81"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/inductivebias.com\/Blog\/wp-json\/wp\/v2\/tags?post=81"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}