Simple Linear Regression - Python Code
import numpy as np
import matplotlib.pyplot as plt
x=np.array([1,2,3,4,5])
y=np.array([1.2,1.8,2.6,3.2,3.8])
xmean=np.mean(x)
ymean=np.mean(y)
nr=np.sum((x-xmean)*(y-ymean))
dr=np.sum((x-xmean) ** 2)
b1=nr/dr
b0=ymean-b1*xmean
print(f"Estimated coefficients : b0={b0},b1={b1}")
ypred_line=b0+b1*x
print(f"y_predicted_line : {ypred_line}")
print('Prediction for x=7')
x_new=7
ypred_new=b0+b1*x_new
print(f"Prediction for x :{x_new}, y:{ypred_new}")
plt.scatter(x,y,color='blue',label='Original Data')
plt.plot(x,ypred_line,color='red',label='Regression Line')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Simple Linear Regression')
plt.legend()
plt.grid(True)
plt.show()
Comments