How to derive equation from Numpy's polyfit?
<p>Given an array of x and y values, the following code will calculate a regression curve for these data points.</p>

<pre><code># calculate polynomial
z = np.polyfit(x, y, 5)
f = np.poly1d(z)

# calculate new x's and y's
x_new = np.linspace(x[0], x[-1], 50)
y_new = f(x_new)

plt.plot(x,y,'o', x_new, y_new)
plt.xlim([x[0]-1, x[-1] + 1 ])
plt.show()
</code></pre>

<p>How can I use the above to derive the actual equation for this curve?</p>

<p>Construct a simple example:</p>

<pre><code>In [94]: x=np.linspace(0,1,100)
In [95]: y=2*x**3-3*x**2+x-1

In [96]: z=np.polyfit(x,y,3)
In [97]: z
Out[97]: array([ 2., -3.,  1., -1.])
</code></pre>

<p>The <code>z</code> coefficients correspond to the [2,-3,1,-1] I used to construct <code>y</code>.</p>

<pre><code>In [98]: f=np.poly1d(z)
In [99]: f
Out[99]: poly1d([ 2., -3.,  1., -1.])
</code></pre>

<p>The <code>str</code>, or print, string for <code>f</code> is a representation of this polynomial equation.  But it's the <code>z</code> coeff that defines the equation.</p>

<pre><code>In [100]: print(f)
   3     2
2 x - 3 x + 1 x - 1
In [101]: str(f)
Out[101]: '   3     2\n2 x - 3 x + 1 x - 1'
</code></pre>

<p>What else do you mean by 'actual equation'?</p>

<p><code>polyval</code> will evaluate <code>f</code> at a specific set of <code>x</code>.  Thus to recreate <code>y</code>, use <code>polyval(f,x)</code>:</p>

<pre><code>In [107]: np.allclose(np.polyval(f,x),y)
Out[107]: True
</code></pre>

python numpy