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.
'''
Program for Univariate linear regression using the least squares method.
Developed by: your name: Jegathish s
RegisterNumber: 21005410
'''
import numpy as np
import matplotlib.pyplot as plt
# Preprocessing Input data
X = np.array(eval(input()))
Y = np.array(eval(input()))
# Building the model
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
#y=mx+c
c=YMean-m*XMean
print (m, c)
#Predict the output
Y_Pred=m*X+c
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.