-
Notifications
You must be signed in to change notification settings - Fork 1
/
functional.py
293 lines (243 loc) · 8.15 KB
/
functional.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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
from typing import Tuple, Union
import numpy as np
from utils import matrix_to_diagonals
def relu(x: np.ndarray) -> np.ndarray:
"""
Calculate the ReLU function for a given input x.
Parameters
----------
x : ndarray
The input to the ReLU function.
Returns
-------
ndarray
The output of the ReLU function applied element-wise to the input array.
"""
return np.clip(x, 0, np.finfo(x.dtype).max)
def softmax(x: np.ndarray) -> np.ndarray:
"""
Calculate the softmax function for a given input x.
Parameters
----------
x : ndarray
The input to the softmax function.
Returns
-------
ndarray
The output of the softmax function applied element-wise to the input array.
"""
e_x = np.exp(x - np.max(x, axis=-1, keepdims=True))
return e_x / np.sum(e_x, axis=-1, keepdims=True)
def tanh(x: np.ndarray) -> np.ndarray:
"""
Calculate the tanh function for a given input x.
Parameters
----------
x : ndarray
The input to the tanh function.
Returns
-------
ndarray
The output of the tanh function applied element-wise to the input array.
"""
return np.tanh(x)
def tanh_derivative(x: np.ndarray) -> np.ndarray:
"""
Calculate the derivative of the tanh function for a given input x.
Parameters
----------
x : ndarray
The input to the tanh function.
Returns
-------
ndarray
The output of the derivative of the tanh function applied element-wise to the input array.
"""
return 1 - np.tanh(x) ** 2
def log_softmax(x: np.ndarray, with_softmax: bool = False) -> Tuple[np.ndarray, Union[np.ndarray, None]]:
"""
Calculate the log softmax function for a given input x.
Parameters
----------
x : ndarray
The input to the softmax function.
with_softmax : bool, optional, default=False
Whether to return the softmax function as well.
Returns
-------
tuple
The output of the log softmax function applied element-wise to the input array.
If `with_softmax` is True, the softmax function is also returned.
"""
t = x - np.max(x, axis=-1, keepdims=True)
e = np.exp(t)
s = np.sum(e, axis=-1, keepdims=True)
if with_softmax:
return t - np.log(s), e / s
return t - np.log(s), None
def softmax_derivative(x: np.ndarray) -> np.ndarray:
"""
Calculate the derivative of the softmax function for a given input x.
Parameters
----------
x : ndarray, shape (n_samples, n_features)
The input to the softmax function.
Returns
-------
ndarray, shape (n_samples, n_features, n_features)
The matrix of derivatives of the softmax function.
"""
"""
diag: (n_classes, n_classes)
| x_i[0] 0 0 |
| 0 x_i[1] 0 |
| 0 0 x_i[2] |
outer: (n_classes, n_classes)
| x_i[0] * x_j[0] x_i[0] * x_j[1] x_i[0] * x_j[2] |
| x_i[1] * x_j[0] x_i[1] * x_j[1] x_i[1] * x_j[2] |
| x_i[2] * x_j[0] x_i[2] * x_j[1] x_i[2] * x_j[2] |
diag - outer: (n_classes, n_classes)
| x_i[0] - x_i[0] * x_j[0] -x_i[0] * x_j[1] -x_i[0] * x_j[2] |
| -x_i[1] * x_j[0] x_i[1] - x_i[1] * x_j[1] -x_i[1] * x_j[2] |
| -x_i[2] * x_j[0] -x_i[2] * x_j[1] x_i[2] - x_i[2] * x_j[2] |
"""
return matrix_to_diagonals(x) - np.einsum("bi,bj->bij", x, x)
def log_softmax_derivative(x: np.ndarray) -> np.ndarray:
"""
Calculate the derivative of the log softmax function for a given input x.
Parameters
----------
x : ndarray, shape (n_samples, n_features)
The input to the softmax function.
Returns
-------
ndarray, shape (n_samples, n_features, n_features)
The matrix of derivatives of the softmax function.
"""
n, c = x.shape
return np.repeat(np.eye(c)[None, :, :], n, axis=0) - np.repeat(x[:, None, :], c, axis=1)
def nll_loss(x: np.ndarray, y: np.ndarray, reduction: str = "mean") -> np.ndarray:
"""
Calculate the negative log-likelihood loss for a given input x and target y.
Parameters
----------
x : ndarray, shape (n_samples, n_features)
The input to the softmax function.
y : ndarray, shape (n_samples,)
The target values.
reduction : str, optional, default="mean"
The reduction method to use.
Returns
-------
ndarray
The negative log-likelihood loss.
"""
assert reduction in ["mean", "sum", "none"], "Invalid reduction method."
loss = -x[np.arange(x.shape[0]), y]
if reduction == "mean":
return np.mean(loss)
elif reduction == "sum":
return np.sum(loss)
return loss
def nll_loss_derivative(x: np.ndarray, y: np.ndarray, reduction: str = "mean") -> np.ndarray:
"""
Calculate the derivative of the negative log-likelihood loss for a given input x and target y.
Parameters
----------
x : ndarray, shape (n_samples, n_features)
The input to the softmax function.
y : ndarray, shape (n_samples,)
The target values.
reduction : str, optional, default="mean"
The reduction method to use.
Returns
-------
ndarray
The derivative of the negative log-likelihood loss.
"""
assert reduction in ["mean", "sum", "none"], "Invalid reduction method."
n, c = x.shape
d = np.zeros((n, c))
d[np.arange(n), y] = -1
if reduction == "mean":
return d / n
elif reduction == "sum":
return d
return d
def cross_entropy(x: np.ndarray, y: np.ndarray, reduction: str = "mean", with_softmax=True) -> np.ndarray:
"""
Calculate the cross-entropy loss for a given input x and target y.
Parameters
----------
x : ndarray, shape (n_samples, n_features)
The input to the softmax function.
y : ndarray, shape (n_samples,)
The target values.
reduction : str, optional, default="mean"
The reduction method to use.
with_softmax : bool, optional, default=True
Whether to apply the softmax function to the input.
Returns
-------
ndarray
The cross-entropy loss.
"""
assert reduction in ["mean", "sum", "none"], "Invalid reduction method."
if with_softmax:
log_soft, _ = log_softmax(x, with_softmax=False)
loss = -log_soft[range(len(y)), y]
else:
loss = -np.log(x[range(len(y)), y])
if reduction == "mean":
return np.mean(loss)
elif reduction == "sum":
return np.sum(loss)
return loss
def cross_entropy_derivative(x: np.ndarray, y: np.ndarray, reduction: str = "mean", with_softmax=True) -> np.ndarray:
"""
Calculate the derivative of the cross-entropy loss for a given input x and target y.
Parameters
----------
x : ndarray, shape (n_samples, n_features)
The input to the softmax function.
y : ndarray, shape (n_samples,)
The target values.
reduction : str, optional, default="mean"
The reduction method to use.
with_softmax : bool, optional, default=True
Whether to apply the softmax function to the input.
Returns
-------
ndarray
The derivative of the cross-entropy loss.
"""
assert reduction in ["mean", "sum", "none"], "Invalid reduction method."
n, c = x.shape
d = np.zeros((n, c))
if with_softmax:
d = softmax(x)
d[np.arange(n), y] -= 1
else:
d[np.arange(n), y] = -1 / x[np.arange(n), y]
if reduction == "mean":
return d / n
elif reduction == "sum":
return d
return d
def linear(x: np.ndarray, w: np.ndarray, b: np.ndarray) -> np.ndarray:
"""
Calculate the linear function for a given input x.
Parameters
----------
x : ndarray, shape (n_samples, n_features)
The input to the linear function.
w : ndarray, shape (n_features, n_classes)
The weight matrix.
b : ndarray, shape (n_classes,)
The bias vector.
Returns
-------
ndarray, shape (n_samples, n_classes)
The output of the linear function.
"""
return x @ w + b