1-
21import numpy as np
32from matplotlib import pyplot as plt
43from sklearn import datasets
54
5+
66# Ridge Regression function
77# reference : https://en.wikipedia.org/wiki/Ridge_regression
8- def ridge_cost_function (x : np .ndarray , y : np .ndarray , theta : np .ndarray , alpha : float ) -> float :
8+ def ridge_cost_function (
9+ x : np .ndarray , y : np .ndarray , theta : np .ndarray , alpha : float
10+ ) -> float :
911 """
1012 Compute the Ridge regression cost function with L2 regularization.
1113
@@ -27,12 +29,21 @@ def ridge_cost_function(x: np.ndarray, y: np.ndarray, theta: np.ndarray, alpha:
2729 """
2830 m = len (y )
2931 predictions = np .dot (x , theta )
30- cost = (1 / (2 * m )) * np .sum ((predictions - y ) ** 2 ) + \
31- (alpha / 2 ) * np .sum (theta [1 :] ** 2 )
32+ cost = (1 / (2 * m )) * np .sum ((predictions - y ) ** 2 ) + (alpha / 2 ) * np .sum (
33+ theta [1 :] ** 2
34+ )
3235
3336 return cost
3437
35- def ridge_gradient_descent (x : np .ndarray , y : np .ndarray , theta : np .ndarray , alpha : float , learning_rate : float , max_iterations : int ) -> np .ndarray :
38+
39+ def ridge_gradient_descent (
40+ x : np .ndarray ,
41+ y : np .ndarray ,
42+ theta : np .ndarray ,
43+ alpha : float ,
44+ learning_rate : float ,
45+ max_iterations : int ,
46+ ) -> np .ndarray :
3647 """
3748 Perform gradient descent to minimize the
3849 cost function and fit the Ridge regression model.
@@ -63,8 +74,10 @@ def ridge_gradient_descent(x: np.ndarray, y: np.ndarray, theta: np.ndarray, alph
6374
6475 return theta
6576
77+
6678if __name__ == "__main__" :
6779 import doctest
80+
6881 doctest .testmod ()
6982
7083 # Load California Housing dataset
@@ -84,7 +97,9 @@ def ridge_gradient_descent(x: np.ndarray, y: np.ndarray, theta: np.ndarray, alph
8497 learning_rate = 0.01
8598 max_iterations = 1000
8699
87- optimized_theta = ridge_gradient_descent (x , y , theta_initial , alpha , learning_rate , max_iterations )
100+ optimized_theta = ridge_gradient_descent (
101+ x , y , theta_initial , alpha , learning_rate , max_iterations
102+ )
88103 print (f"Optimized theta: { optimized_theta } " )
89104
90105 # Prediction
@@ -95,11 +110,10 @@ def predict(x, theta):
95110
96111 # Plotting the results (here we visualize predicted vs actual values)
97112 plt .figure (figsize = (10 , 6 ))
98- plt .scatter (y , y_pred , color = 'b' , label = ' Predictions vs Actual' )
99- plt .plot ([min (y ), max (y )], [min (y ), max (y )], color = 'r' , label = ' Perfect Fit' )
113+ plt .scatter (y , y_pred , color = "b" , label = " Predictions vs Actual" )
114+ plt .plot ([min (y ), max (y )], [min (y ), max (y )], color = "r" , label = " Perfect Fit" )
100115 plt .xlabel ("Actual values" )
101116 plt .ylabel ("Predicted values" )
102117 plt .title ("Ridge Regression: Actual vs Predicted Values" )
103118 plt .legend ()
104119 plt .show ()
105-
0 commit comments