@@ -49,9 +49,10 @@ def run_steep_gradient_descent(data_x, data_y, len_data, alpha, theta):
49
49
sum_grad = np .dot (prod , data_x )
50
50
theta = theta - (alpha / len_data ) * sum_grad
51
51
return theta
52
- except Exception as e :
52
+ except ( TypeError , ValueError ) as e :
53
53
print (f"Error in gradient descent: { e } " )
54
- return theta # Return current theta even if an error occurs
54
+ return theta
55
+
55
56
56
57
57
58
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):
67
68
sum_elem = np .sum (np .square (prod ))
68
69
error = sum_elem / (2 * len_data )
69
70
return error
70
- except Exception as e :
71
+ except ( TypeError , ValueError ) as e :
71
72
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
+
73
75
74
76
75
77
def run_linear_regression (data_x , data_y ):
@@ -89,11 +91,12 @@ def run_linear_regression(data_x, data_y):
89
91
theta = run_steep_gradient_descent (data_x , data_y , len_data , alpha , theta )
90
92
error = sum_of_square_error (data_x , data_y , len_data , theta )
91
93
print (f"At Iteration { i + 1 } - Error is { error :.5f} " )
92
- except Exception as e :
94
+ except ( OverflowError , ValueError ) as e :
93
95
print (f"Error during linear regression: { e } " )
94
96
return theta
95
97
96
98
99
+
97
100
def mean_absolute_error (predicted_y , original_y ):
98
101
"""Return sum of square error for error calculation
99
102
:param predicted_y : contains the output of prediction (result vector)
@@ -103,9 +106,10 @@ def mean_absolute_error(predicted_y, original_y):
103
106
try :
104
107
total = sum (abs (y - predicted_y [i ]) for i , y in enumerate (original_y ))
105
108
return total / len (original_y )
106
- except Exception as e :
109
+ except ( TypeError , ZeroDivisionError ) as e :
107
110
print (f"Error in calculating mean absolute error: { e } " )
108
- return float ('inf' )
111
+ return float ("inf" )
112
+
109
113
110
114
111
115
def main ():
@@ -125,9 +129,10 @@ def main():
125
129
print ("Resultant Feature vector : " )
126
130
for i in range (len_result ):
127
131
print (f"{ theta [0 , i ]:.5f} " )
128
- except Exception as e :
132
+ except ( IndexError , TypeError ) as e :
129
133
print (f"Error in main execution: { e } " )
130
134
131
135
136
+
132
137
if __name__ == "__main__" :
133
138
main ()
0 commit comments