Python NumPy Mini Projects :Linear Regression from Scratch
Let us implement Linear Regression in Python using NumPy. We use the student’s score analysis system.
Implementation:
Let us create a data set like this as follows…
|
Hours Studied |
Marks Obtained |
|
2 |
38 |
|
1 |
20 |
|
3 |
56 |
|
4 |
89 |
|
5 |
76 |
Let us find the solution for the equation
y = mx + b
where,
- y =
marks
- x =
study hours
- m =
slope
- b =
intercept
Code:
#import the numpy
import numpy as np
#create arrays for input. One is for study hour. Another one
is for Mark obtained.
x = np.array([2, 1, 3, 4, 5])
y = np.array([38, 20, 56, 89, 76])
#assign the initial values
m = 0
b = 0
learning_rate = 0.01
epochs = 1000
n = len(x)
#calculate the values
for i in range(epochs):
y_pred = m * x + b
dm = (-2/n) * np.sum(x
* (y - y_pred))
db = (-2/n) * np.sum(y
- y_pred)
m = m - learning_rate
* dm
b = b - learning_rate
* db
#print the results
print("Slope:", m)
print("Intercept:", b)
hours = 6
prediction = m * hours + b
print("Predicted Marks:", prediction)
Output:
Slope: 16.320751456501725
Intercept: 6.825080657627279
Predicted Marks: 104.74958939663763
That’s all. The mini project to implement Linear Regression
using NumPy in Python was done successfully. Hope, you understood the concept. Keep
Coding!!
Comments
Post a Comment