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: pochireddy.p
RegisterNumber: 212223240115
'''
import numpy as np
import matplotlib.pyplot as plt
X=np.array(eval(input("Enter the input x values in array:")))
Y=np.array(eval(input("Enter the input y values in array:")))
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
print("The slope of the predicted line is : ",m)
b=Y_mean - m*X_mean
print("The y-intercept is :",b)
Y_pred=m*X+b
print("The 'y' predicted values are :",Y_pred)
plt.scatter(X,Y,color='black')
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.