To implement univariate Linear Regression to fit a straight line using least squares.
- Hardware – PCs
- Anaconda – Python 3.7 Installation / Moodle-Code Runner
- Get the independent variable X and dependent variable Y.
- Calculate the mean of the X -values and the mean of the Y -values.
- Find the slope m of the line of best fit using the formula.
- Compute the y -intercept of the line by using the formula:
- Use the slope m and the y -intercept to form the equation of the line.
- Obtain the straight line equation Y=mX+b and plot the scatterplot.
import numpy as np
import matplotlib.pyplot as plt
x=np.array(eval(input()))
y=np.array(eval(input()))
xmean=np.mean(x)
ymean=np.mean(y)
num,den=0,0
for i in range (len(x)):
num+=(x[i]-xmean)*(y[i]-ymean)
den+=(x[i]-xmean)**2
m=num/den
c=ymean-(m*xmean)
print(m,c)
y_pred =m*x+c
print(y_pred)
plt.scatter(x,y)
plt.plot(x,y_pred,color="orange")
plt.show()
Thus the univariate Linear Regression was implemented to fit a straight line using least squares.