Skip to content

Commit 1f27232

Browse files
dineshsuthar31pre-commit-ci[bot]cclauss
authored
Add regression visualization (#14637)
* Add visualization support for linear regression * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Fix linting and plotting issues * Apply ruff auto fixes * Fix spelling issue * Update linear_regression.py --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Christian Clauss <cclauss@me.com>
1 parent 1eb999e commit 1f27232

1 file changed

Lines changed: 59 additions & 10 deletions

File tree

machine_learning/linear_regression.py

Lines changed: 59 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,31 @@
11
"""
22
Linear regression is the most basic type of regression commonly used for
3-
predictive analysis. The idea is pretty simple: we have a dataset and we have
3+
predictive analysis. The idea is pretty simple: we have a dataset, and we have
44
features associated with it. Features should be chosen very cautiously
55
as they determine how much our model will be able to make future predictions.
66
We try to set the weight of these features, over many iterations, so that they best
7-
fit our dataset. In this particular code, I had used a CSGO dataset (ADR vs
8-
Rating). We try to best fit a line through dataset and estimate the parameters.
7+
fit our dataset. In this particular code, I used a CSGO dataset (ADR vs
8+
Rating). We try to best fit a line through the dataset and estimate the parameters.
99
"""
1010

1111
# /// script
1212
# requires-python = ">=3.13"
1313
# dependencies = [
1414
# "httpx2",
1515
# "numpy",
16+
# "matplotlib",
1617
# ]
1718
# ///
1819

1920
import httpx2
21+
import matplotlib.pyplot as plt
2022
import numpy as np
2123

2224

2325
def collect_dataset():
2426
"""Collect dataset of CSGO
2527
The dataset contains ADR vs Rating of a Player
26-
:return : dataset obtained from the link, as matrix
28+
:return : dataset obtained from the link, as a matrix
2729
"""
2830
response = httpx2.get(
2931
"https://raw.githubusercontent.com/yashLadha/The_Math_of_Intelligence/"
@@ -41,13 +43,13 @@ def collect_dataset():
4143

4244

4345
def run_steep_gradient_descent(data_x, data_y, len_data, alpha, theta):
44-
"""Run steep gradient descent and updates the Feature vector accordingly_
46+
"""Run steep gradient descent and update the Feature vector accordingly_
4547
:param data_x : contains the dataset
4648
:param data_y : contains the output associated with each data-entry
4749
:param len_data : length of the data_
4850
:param alpha : Learning rate of the model
49-
:param theta : Feature vector (weight's for our model)
50-
;param return : Updated Feature's, using
51+
:param theta : Feature vector (weights for our model)
52+
;param return : Updated features, using
5153
curr_features - alpha_ * gradient(w.r.t. feature)
5254
>>> import numpy as np
5355
>>> data_x = np.array([[1, 2], [3, 4]])
@@ -99,19 +101,24 @@ def run_linear_regression(data_x, data_y):
99101

100102
theta = np.zeros((1, no_features))
101103

104+
err = []
105+
102106
for i in range(iterations):
103107
theta = run_steep_gradient_descent(data_x, data_y, len_data, alpha, theta)
104108
error = sum_of_square_error(data_x, data_y, theta)
105109
print(f"At Iteration {i + 1} - Error is {error:.5f}")
106110

107-
return theta
111+
if i % 1000 == 0:
112+
print(f"At Iteration {i + 1} - Error is {error:.5f}")
113+
114+
return theta, err
108115

109116

110117
def mean_absolute_error(predicted_y, original_y):
111118
"""Return sum of square error for error calculation
112119
:param predicted_y : contains the output of prediction (result vector)
113120
:param original_y : contains values of expected outcome
114-
:return : mean absolute error computed from given feature's
121+
:return : mean absolute error computed from given features
115122
116123
>>> predicted_y = [3, -0.5, 2, 7]
117124
>>> original_y = [2.5, 0.0, 2, 8]
@@ -122,6 +129,44 @@ def mean_absolute_error(predicted_y, original_y):
122129
return total / len(original_y)
123130

124131

132+
# visualization
133+
def plot_regression(data_x, data_y, theta):
134+
"""
135+
Plot regression line with dataset points
136+
"""
137+
138+
x = np.array(data_x[:, 1]).flatten()
139+
y = np.array(data_y).flatten()
140+
141+
predictions = theta[0, 0] + theta[0, 1] * x
142+
143+
plt.scatter(x, y)
144+
145+
plt.plot(x, predictions)
146+
147+
plt.xlabel("ADR")
148+
plt.ylabel("Rating")
149+
150+
plt.title("Linear Regression Best Fit")
151+
152+
plt.show()
153+
154+
155+
def plot_loss(err):
156+
"""
157+
Plot training loss curve
158+
"""
159+
160+
plt.plot(err)
161+
162+
plt.xlabel("Iterations")
163+
plt.ylabel("Loss")
164+
165+
plt.title("Training Loss Curve")
166+
167+
plt.show()
168+
169+
125170
def main() -> None:
126171
"""Driver function"""
127172
data = collect_dataset()
@@ -130,7 +175,11 @@ def main() -> None:
130175
data_x = np.c_[np.ones(len_data), data[:, :-1]].astype(float)
131176
data_y = data[:, -1].astype(float)
132177

133-
theta = run_linear_regression(data_x, data_y)
178+
theta, err = run_linear_regression(data_x, data_y)
179+
180+
plot_regression(data_x, data_y, theta)
181+
plot_loss(err)
182+
134183
len_result = theta.shape[1]
135184
print("Resultant Feature vector : ")
136185
for i in range(len_result):

0 commit comments

Comments
 (0)