E. Weglarz - 7 months ago 110

Python Question

I am looking to obtain the coefficients and intercept using a polynomial regression (polyfit) in Numpy, but am not sure how to write the script to get a polynomial function.

I have made code the code for a linear regression, which I have attached below:

`import matplotlib.pyplot as plt`

import sys

from numpy import *

import numpy as np

import numpy.polynomial.polynomial as poly

import pylab

from scipy import stats

from scipy.interpolate import *

from datetime import datetime, timedelta

#Open dataset1,dataset2 data

data1 = np.loadtxt('/home/script/2_columns', delimiter=',', skiprows=0)

data2 = np.loadtxt('/home/script/2_columns_a', delimiter=',', skiprows=0)

#Define first column as dataset1

#Define second column as dataset2

x = data1[:,0]

y = data1[:,1]

#The stuff...

slope, intercept, r_value, p_value, std_err = stats.linregress(x,y)

Answer

Do you need the stats? If not, and you just need the coefficients, it's really quite simple using `numpy.polyfit`

:

```
import numpy as np
# from your code
data1 = np.loadtxt('/home/script/2_columns', delimiter=',', skiprows=0)
x = data1[:,0]
y = data1[:,1]
degree = 3
coeffs = np.polyfit(x, y, degree)
# now, coeffs is an array which contains the polynomial coefficients
# in ascending order, i.e. x^0, x^1, x^2
intercept, linear, quadratic, cubic = coeffs
```

If you do need the other values, please specify what you need, since for example the `r_value`

is the correlation coefficient between `x`

and `y`

, which isn't very useful when you don't expect the data to be linear.