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: Y SHAVEDHA
RegisterNumber: 212221230095
*/
#IMPORT LIBRARIES
import numpy as np
import matplotlib.pyplot as plt
#GETTING VALUES OF X AND Y FROM USER
x=np.array(eval(input("Enter the values of x: ")))
y=np.array(eval(input("Enter the values of y: ")))
#FINDING THE MEAN OF X AND Y INPUTS
x_mean=np.mean(x)
print("x_mean=",x_mean)
y_mean=np.mean(y)
print("y_mean=",y_mean)
nume,deno=0,0
for i in range(len(x)):
nume+=((x[i]-x_mean)*(y[i]-y_mean))
deno+=(x[i]-x_mean)**2
#SLOPE
m=nume/deno
print("Slope m = ",m)
#INTERCEPT #Sample Input
b=y_mean-(m*(x_mean)) #8,2,11,6,5,4,12,9,6,1 #3,10,3,6,8,12,1,4,9,14
print("b= ",b)
#LINE EQN
y_pred=m*x+b
print("Y pred= ",y_pred)
#When x=3
y_p3=m*3+b;
print("when x=3,y=",y_p3)
#GRAPH
print("Graph")
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.