2
2
from matplotlib import pyplot as plt
3
3
from sklearn import datasets
4
4
5
+
5
6
# Ridge Regression function
6
7
# reference : https://en.wikipedia.org/wiki/Ridge_regression
7
- 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 :
8
11
"""
9
12
Compute the Ridge regression cost function with L2 regularization.
10
13
@@ -31,7 +34,15 @@ def ridge_cost_function(x: np.ndarray, y: np.ndarray, theta: np.ndarray, alpha:
31
34
32
35
return cost
33
36
34
- def ridge_gradient_descent (x : np .ndarray , y : np .ndarray , theta : np .ndarray , alpha : float , learning_rate : float , max_iterations : int ) -> np .ndarray :
37
+
38
+ def ridge_gradient_descent (
39
+ x : np .ndarray ,
40
+ y : np .ndarray ,
41
+ theta : np .ndarray ,
42
+ alpha : float ,
43
+ learning_rate : float ,
44
+ max_iterations : int ,
45
+ ) -> np .ndarray :
35
46
"""
36
47
Perform gradient descent to minimize the cost function and fit the Ridge regression model.
37
48
@@ -62,9 +73,9 @@ def ridge_gradient_descent(x: np.ndarray, y: np.ndarray, theta: np.ndarray, alph
62
73
return theta
63
74
64
75
65
-
66
76
if __name__ == "__main__" :
67
77
import doctest
78
+
68
79
doctest .testmod ()
69
80
70
81
# Load California Housing dataset
@@ -84,18 +95,31 @@ def ridge_gradient_descent(x: np.ndarray, y: np.ndarray, theta: np.ndarray, alph
84
95
learning_rate = 0.01
85
96
max_iterations = 1000
86
97
98
+ < << << << HEAD
87
99
optimized_theta = ridge_gradient_descent (x , y , theta_initial , alpha , learning_rate , max_iterations )
88
100
print (f"Optimized theta: { optimized_theta } " )
89
101
90
102
# Prediction
91
103
def predict (x , theta ):
92
104
return np .dot (x , theta )
93
105
y_pred = predict (x , optimized_theta )
106
+ == == == =
107
+ optimized_theta = ridge_gradient_descent (
108
+ X , y , theta_initial , alpha , learning_rate , max_iterations
109
+ )
110
+ print (f"Optimized theta: { optimized_theta } " )
111
+
112
+ # Prediction
113
+ def predict (X , theta ):
114
+ return np .dot (X , theta )
115
+
116
+ y_pred = predict (X , optimized_theta )
117
+ >> >> >> > 2 b4bf7dba7715b721dc9597852100a44acf47566
94
118
95
119
# Plotting the results (here we visualize predicted vs actual values)
96
120
plt .figure (figsize = (10 , 6 ))
97
- plt .scatter (y , y_pred , color = 'b' , label = ' Predictions vs Actual' )
98
- plt .plot ([min (y ), max (y )], [min (y ), max (y )], color = 'r' , label = ' Perfect Fit' )
121
+ plt .scatter (y , y_pred , color = "b" , label = " Predictions vs Actual" )
122
+ plt .plot ([min (y ), max (y )], [min (y ), max (y )], color = "r" , label = " Perfect Fit" )
99
123
plt .xlabel ("Actual values" )
100
124
plt .ylabel ("Predicted values" )
101
125
plt .title ("Ridge Regression: Actual vs Predicted Values" )
0 commit comments