Skip to content

Commit 93c1efb

Browse files
committed
update linear_regression.py file
1 parent 1a93fd5 commit 93c1efb

File tree

1 file changed

+13
-8
lines changed

1 file changed

+13
-8
lines changed

machine_learning/linear_regression.py

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -49,9 +49,10 @@ def run_steep_gradient_descent(data_x, data_y, len_data, alpha, theta):
4949
sum_grad = np.dot(prod, data_x)
5050
theta = theta - (alpha / len_data) * sum_grad
5151
return theta
52-
except Exception as e:
52+
except (TypeError, ValueError) as e:
5353
print(f"Error in gradient descent: {e}")
54-
return theta # Return current theta even if an error occurs
54+
return theta
55+
5556

5657

5758
def sum_of_square_error(data_x, data_y, len_data, theta):
@@ -67,9 +68,10 @@ def sum_of_square_error(data_x, data_y, len_data, theta):
6768
sum_elem = np.sum(np.square(prod))
6869
error = sum_elem / (2 * len_data)
6970
return error
70-
except Exception as e:
71+
except (TypeError, ValueError) as e:
7172
print(f"Error in calculating sum of square error: {e}")
72-
return float('inf') # Return infinity in case of an error
73+
return float("inf")
74+
7375

7476

7577
def run_linear_regression(data_x, data_y):
@@ -89,11 +91,12 @@ def run_linear_regression(data_x, data_y):
8991
theta = run_steep_gradient_descent(data_x, data_y, len_data, alpha, theta)
9092
error = sum_of_square_error(data_x, data_y, len_data, theta)
9193
print(f"At Iteration {i + 1} - Error is {error:.5f}")
92-
except Exception as e:
94+
except (OverflowError, ValueError) as e:
9395
print(f"Error during linear regression: {e}")
9496
return theta
9597

9698

99+
97100
def mean_absolute_error(predicted_y, original_y):
98101
"""Return sum of square error for error calculation
99102
:param predicted_y : contains the output of prediction (result vector)
@@ -103,9 +106,10 @@ def mean_absolute_error(predicted_y, original_y):
103106
try:
104107
total = sum(abs(y - predicted_y[i]) for i, y in enumerate(original_y))
105108
return total / len(original_y)
106-
except Exception as e:
109+
except (TypeError, ZeroDivisionError) as e:
107110
print(f"Error in calculating mean absolute error: {e}")
108-
return float('inf')
111+
return float("inf")
112+
109113

110114

111115
def main():
@@ -125,9 +129,10 @@ def main():
125129
print("Resultant Feature vector : ")
126130
for i in range(len_result):
127131
print(f"{theta[0, i]:.5f}")
128-
except Exception as e:
132+
except (IndexError, TypeError) as e:
129133
print(f"Error in main execution: {e}")
130134

131135

136+
132137
if __name__ == "__main__":
133138
main()

0 commit comments

Comments
 (0)