Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
yiming-wange
GitHub Repository: yiming-wange/cs224n-2023-solution
Path: blob/main/a2/utils/utils.py
1003 views
1
#!/usr/bin/env python
2
3
import numpy as np
4
5
def normalizeRows(x):
6
""" Row normalization function
7
8
Implement a function that normalizes each row of a matrix to have
9
unit length.
10
"""
11
N = x.shape[0]
12
x /= np.sqrt(np.sum(x**2, axis=1)).reshape((N,1)) + 1e-30
13
return x
14
15
def softmax(x):
16
"""Compute the softmax function for each row of the input x.
17
It is crucial that this function is optimized for speed because
18
it will be used frequently in later code.
19
20
Arguments:
21
x -- A D dimensional vector or N x D dimensional numpy matrix.
22
Return:
23
x -- You are allowed to modify x in-place
24
"""
25
orig_shape = x.shape
26
27
if len(x.shape) > 1:
28
# Matrix
29
tmp = np.max(x, axis=1)
30
x -= tmp.reshape((x.shape[0], 1))
31
x = np.exp(x)
32
tmp = np.sum(x, axis=1)
33
x /= tmp.reshape((x.shape[0], 1))
34
else:
35
# Vector
36
tmp = np.max(x)
37
x -= tmp
38
x = np.exp(x)
39
tmp = np.sum(x)
40
x /= tmp
41
42
assert x.shape == orig_shape
43
return x
44