A user is learning python/numpy and wondering if anyone can help with doing a linear regression curve equation in python/numpy?
We can use the following code implement a linear regression curve in Python
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
#just some data. Make sure that they are stored in an array, not in a list!!!:
y = np.array([1, 3.8, 7.1, 10.6, 12.6])
x = np.array([0, 1, 2, 3, 4])
#make sure that x is the first argument of linFunc!!
def linFunc(x, k, d):
return k*x+d
#fitting Algorithm. Cop gives you the 'best' values of k and d, cov is the covariance Matrix.
cop, cov = curve_fit(linFunc, x, y)
xplot = np.linspace(0, 4, 10**4)
plt.figure("data and fitted line")
plt.plot(x, y, 'ro', label = "datapoints")
plt.plot(xplot, linFunc(xplot, *cop), 'b--', label = "fittet function")
plt.xlabel("x-axis")
plt.ylabel("y-axis")
plt.legend()
plt.show()