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:LOGESHWARI.P
RegisterNumber:212221230055
import matplotlib.pyplot as plt
x=[5,6,3,2,6,7,1,2]
y=[2,3,6,5,8,3,5,8]
plt.scatter(x,y)
plt.show()
import numpy as np
import matplotlib.pyplot as plt
#assign input
x=np.array([0,1,2,3,4,5,6,7,8,9])
y=np.array([1,3,2,5,7,8,8,9,10,12])
#mean values of input
x_mean=np.mean(x)
print(x_mean)
y_mean=np.mean(y)
print(y_mean)
num=0
denum=0
for i in range(len(x)):
num+=(x[i]-x_mean)*(y[i]-y_mean)
denum+=(x[i]-x_mean)**2
#find m
m=num/denum
#find b
b=y_mean-m*x_mean
print("m",m)
print("b",b)
#find y_pred
y_pred=m*x+b
print(y_pred)
#plot graph
plt.scatter(x,y)
plt.plot(x,y_pred,color='green')
plt.show()
Thus the univariate Linear Regression was implemented to fit a straight line using least squares using python programming.