-
Notifications
You must be signed in to change notification settings - Fork 0
/
implementations.py
210 lines (167 loc) · 6.15 KB
/
implementations.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
import numpy as np
from helpers import batch_iter
""" Utility functions """
def loss_mse(y, tx, w):
"""Calculate the mean squared error loss.
Parameters:
y (np.ndarray): Target values, shape (n_samples,)
tx (np.ndarray): Feature matrix, shape (n_samples, n_features)
w (np.ndarray): Weights, shape (n_features,)
Returns:
float: Mean Squared Error loss
"""
return 1/2 * np.square(y - tx @ w).mean()
def compute_gradient_linreg(y, tx, w):
"""
Calculate the gradient of the square mean error loss function of a linear regression model, with respect to the weights w.
Parameters:
y : np.ndarray(N) : labels (0 or 1)
tx : np.ndarray(N, D) : features, including the constant feature
w : np.ndarray(D) : weights
Returns:
g: np.ndarray(D) : gradient of the loss with respect to w
"""
return -1/len(y) * np.transpose(tx) @ (y - tx @ w)
def sigmoid(x):
""" Sigmoid function
Parameters:
x : {float, np.ndarray, int} : input
Returns:
{float, np.ndarray} : sigmoid(x)
"""
return 1. / (1 + np.exp(-x))
def log_reg_grad(y, tx, w):
""" Compute the gradient of the logistic regression loss
Parameters:
y : np.ndarray(N) : labels (0 or 1)
tx : np.ndarray(N, D) : features
w : np.ndarray(D) : weights
Returns:
grad : np.ndarray(D) : gradient
"""
N = tx.shape[0]
probas = sigmoid(tx @ w) # (N)
grad = tx.T @ (probas - y) / N # (D)
return grad
def log_reg_loss(y, tx, w):
""" Compute the logistic regression loss
Parameters:
y : np.ndarray(N) : labels (0 or 1)
tx : np.ndarray(N, D) : features
w : np.ndarray(D) : weights
Returns:
loss : float : loss value (negative log likelihood)
"""
z = tx @ w # (N)
### negative log likelihood (derived from -y*log(p) - (1-y)*log(1-p))
loss = np.sum(
np.log(1 + np.exp(z)) - y * z
) / tx.shape[0]
return loss
""" Main functions """
def mean_squared_error_sgd(y, tx, initial_w, max_iters, gamma):
"""
Perform the given number of iterations of stochastic gradient descent for linear regression using square mean error as loss.
Parameters:
y : np.ndarray(N) : labels (0 or 1)
tx : np.ndarray(N, D) : features, including the constant feature
initial_w : np.ndarray(D) : initial weights
max_iters : int : maximum number of iterations
gamma : float : step size
Returns:
w : np.ndarray(D) : final parameter vector
loss : float : final loss
"""
w = initial_w
batches = batch_iter(y, tx, 1, max_iters)
for n_iter, batch in enumerate(batches):
y_batch, xt_batch = batch
g = compute_gradient_linreg(y_batch, xt_batch, w)
w = w - gamma * g
return w, loss_mse(y, tx, w)
def mean_squared_error_gd(y, tx, initial_w, max_iters, gamma):
"""
Perform the given number of iterations of gradient descent for linear regression using square mean error as loss.
Parameters:
y : np.ndarray(N) : labels (0 or 1)
tx : np.ndarray(N, D) : features, including the constant feature
initial_w : np.ndarray(D) : initial weights
max_iters : int : maximum number of iterations
gamma : float : step size
Returns:
w : np.ndarray(D) : final parameter vector
loss : float : final loss
"""
w = initial_w
for n_iter in range(max_iters):
g = compute_gradient_linreg(y, tx, w)
w = w - gamma * g
return w, loss_mse(y, tx, w)
def least_squares(y, tx):
"""
Computes the least squares solution to the linear regression problem.
Parameters:
y (np.ndarray): Target values, shape (n_samples,)
tx (np.ndarray): Feature matrix, shape (n_samples, n_features)
Returns:
w (np.ndarray): Optimal weights, shape (n_features,)
loss (float): Mean Squared Error loss
"""
tx_t = tx.T
w = np.linalg.solve(tx_t @ tx, tx_t @ y)
# Compute Mean Squared Error for the Loss
return w, loss_mse(y, tx, w)
def ridge_regression(y, tx, lambda_):
"""
Computes the least squares solution to the linear regression problem with Ridge regularization.
Parameters:
y (np.ndarray): Target values, shape (n_samples,)
tx (np.ndarray): Feature matrix, shape (n_samples, n_features)
lambda_ (float): Regularization parameter. Set to 0 for no regularization.
Returns:
w (np.ndarray): Optimal weights, shape (n_features,)
loss (float): Mean Squared Error loss
"""
n, d = tx.shape
w = np.linalg.solve(tx.T @ tx + lambda_ * 2*n * np.eye(d), tx.T @ y)
# Compute Mean Squared Error for the Loss
return w, loss_mse(y, tx, w)
def logistic_regression(y, tx, initial_w, max_iters, gamma):
""" Logistic regression using gradient descent
Parameters:
y : np.ndarray(N) : labels (0 or 1)
tx : np.ndarray(N, D) : features
initial_w : np.ndarray(D) : initial weights
max_iters : int : maximum number of iterations
gamma : float : step size
Returns:
w : np.ndarray(D) : final weights
loss : float : final loss
"""
w = initial_w
for _ in range(max_iters):
### compute grad and update w
grad = log_reg_grad(y, tx, w)
w = w - gamma * grad
final_loss = log_reg_loss(y, tx, w)
return w, final_loss
def reg_logistic_regression(y, tx, lambda_, initial_w, max_iters, gamma):
""" Regularized logistic regression using gradient descent
Parameters:
y : np.ndarray(N) : labels (0 or 1)
tx : np.ndarray(N, D) : features
lambda_ : float : regularization strength (L_r = lambda * ||w||^2)
initial_w : np.ndarray(D) : initial weights
max_iters : int : maximum number of iterations
gamma : float : step size
Returns:
w : np.ndarray(D) : final parameter vector
loss : float : final loss
"""
w = initial_w
for _ in range(max_iters):
### compute grad and update w
grad = log_reg_grad(y, tx, w) + 2 * lambda_ * w
w -= gamma * grad
final_loss = log_reg_loss(y, tx, w) # don't include the regularization term
return w, final_loss