Skip to content

Commit 51ec21b

Browse files
author
Narra_Venkata_Raghu_Charan
authored
Create linear-regression-without-libraries.py
1 parent e706727 commit 51ec21b

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import numpy as np
2+
import matplotlib.pyplot as plt
3+
4+
# Sample Data (Height vs. Weight, for example)
5+
# X represents height in cm, Y represents weight in kg
6+
X = np.array([150, 160, 170, 180, 190])
7+
Y = np.array([50, 60, 65, 70, 80])
8+
n = len(X)
9+
10+
# Mean of X and Y
11+
mean_x = np.mean(X)
12+
mean_y = np.mean(Y)
13+
14+
# Calculating the coefficients for Linear Regression
15+
numerator = np.sum((X - mean_x) * (Y - mean_y)) # Σ((Xi - X̄) * (Yi - Ȳ))
16+
denominator = np.sum((X - mean_x) ** 2) # Σ((Xi - X̄)^2)
17+
18+
# Slope (m) and Intercept (b) for y = mx + b
19+
m = numerator / denominator # Slope
20+
b = mean_y - (m * mean_x) # Intercept
21+
22+
print(f"Slope (m): {m}")
23+
print(f"Intercept (b): {b}")
24+
25+
# Prediction using the regression model
26+
def predict(x):
27+
return m * x + b
28+
29+
# Predicted values for X
30+
Y_pred = predict(X)
31+
32+
# Plotting the results
33+
plt.scatter(X, Y, color="blue", label="Data Points") # Plot original data points
34+
plt.plot(X, Y_pred, color="red", label="Regression Line") # Plot regression line
35+
36+
plt.xlabel("Height (cm)")
37+
plt.ylabel("Weight (kg)")
38+
plt.title("Linear Regression Example")
39+
plt.legend()
40+
41+
# Save the plot as an image file
42+
plt.savefig("linear_regression_plot.png")
43+
print("Plot saved as 'linear_regression_plot.png'")

0 commit comments

Comments
 (0)