Linear Regression Code
Linear Regression Code
LAB REPORT
Submitted By Submitted To
𝑓𝑤,𝑏(𝑥) = 𝑦̂ = 𝑤𝑥 + 𝑏
Where,
w = Weight matrix or slope of the
line b = Bias or the intercept of the
line
𝑦̂ = predicted output
Linear regression can be further divided into two types of the algorithm:
1. Simple Linear Regression: If a single independent variable is used to predict the
value of a numerical dependent variable, then such a Linear Regression algorithm is
called Simple Linear Regression.
2. Multiple Linear regression: If more than one independent variable is used to predict
the value of a numerical dependent variable, then such a Linear Regression algorithm
is called Multiple Linear Regression.
Code to Implement Linear Regression using Python:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df=pd.read_csv("AI_Lab1.csv")
x=np.array(df[['x']])
y=np.array(df[['y']])
plt.scatter(x,y)
plt.plot(x,y)
plt.xlabel('Values of X')
plt.ylabel('Values of Y')
plt.show()
x_mean=np.mean(x)
y_mean=np.mean(y)
print('Mean of X=',x_mean,'Mean of Y=',y_mean)
num=0
den=0
for i in range(len(x)):
num+=(x[i]-x_mean)*(y[i]-y_mean)
den+=(x[i]-x_mean)**2
m=num/den
c=y_mean-(m*x_mean)
print("Intercept is ", float(c), "Slope is ", float(m))
y_predict=c+m*x
y_predict
plt.scatter(x,y,c='red')
plt.plot(x,y_predict)
plt.show()
num_r=0
den_r=0
for i in range(len(x)):
num_r+=(y[i]-y_predict[i])**2
den_r+=(y[i]-y_mean)**2
r_sq=1-(num_r/den_r)
print("The value of coefficient of determination of R_Square is ",
float(r_sq ))
Conclusion:
This experiment was about a basic understanding of what linear regression is and how to
implement them easily using python programming language. In this experiment we did not
use scikit library as it makes it easier to implement linear regression. Rather, we tried to
understand and implement linear regression from scratch.