To implement univariate Linear Regression to fit a straight line using least squares.
- Hardware โ PCs
- Anaconda โ Python 3.7 Installation / Jupyter notebook
- 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.
/*
Program to implement univariate Linear Regression to fit a straight line using least squares.
Developed by:AKSHARA C
RegisterNumber: 212223220004
*/
import numpy as np
import matplotlib.pyplot as plt
x=np.array(eval(input()))
y=np.array(eval(input()))
x_mean=np.mean(x)
y_mean=np.mean(y)
num=0
denom=0
for i in range(len(x)):
num += (x[i]-x_mean)*(y[i]-y_mean)
denom += (x[i]-x_mean)**2
m=num/denom
b=y_mean-m*x_mean
print(m,b)
y_pred=m*x+b
print(y_pred)
plt.scatter(x,y)
plt.plot(x,y_pred,color='red')
plt.show()
Thus the univariate Linear Regression was implemented to fit a straight line using least squares using python programming.