I am looking for a better way of calculating the following
JavaScript
x
21
21
1
import numpy as np
2
np.random.seed(123)
3
4
# test code
5
t = np.random.randint(3, size = 100)
6
X = np.random.random((100, 3))
7
m = np.random.random((3, 3))
8
9
# current method
10
res = 0
11
for k in np.unique(t):
12
for row in X[t == k] - m[k]:
13
res += np.outer(row, row)
14
res
15
"""
16
Output:
17
array([[12.45661335, -3.51124346, 3.75900294],
18
[-3.51124346, 14.85327689, -3.02281263],
19
[ 3.75900294, -3.02281263, 18.30868772]])
20
"""
21
I would prefer getting rid of the for loops using numpy.
This is the within-class scatter matrix for fischers linear discriminant.
Advertisement
Answer
You can write as follows:
JavaScript
1
3
1
Y = X - m[t]
2
np.matmul(Y.T, Y)
3
This is because sum_i x_i x'_i = X' X
, where X
is (N, 3)
matrix and x_i = X[i,:]
, i.e. i
-th row of X
. '
indicates the transpose.