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: BALAMURUGAN S
RegisterNumber: 212223230027
*/
import numpy as np
import matplotlib.pyplot as plt
#preprocessing input data
X=np.array(eval(input()))
Y=np.array(eval(input()))
#mean
X_mean=np.mean(X)
Y_mean=np.mean(Y)
num=0 #for slope
denom=0 #for slope
#to find sum of (xi-x') & (yi-y') & (xi-x')^2
for i in range(len(X)):
num+=(X[i]-X_mean)*(Y[i]-Y_mean)
denom+=(X[i]-X_mean)**2
#to find slope
m=num/denom
b=Y_mean-m*X_mean
print(m,b)
#to find predicted value
Y_predicted=m*X+b
print(Y_predicted)
#to plot graphplt.scatter(X,Y)
plt.plot(X,Y_predicted,color="red")
plt.show()
Thus the univariate Linear Regression was implemented to fit a straight line using least squares using python programming.