#两个feature, 一个n*d, 一个m*d,求他们的l2损失
import numpy as np
N = np.random.randint(1, 10, size=(3, 5))
print(N)
M = np.random.randint(1, 10, size=(6, 5))
print(M)
for循环实现
最初版本
# N[n, d]
# M[m, d]
L0 = np.zeros((N.shape[0], M.shape[0]))
for i in range(N.shape[0]):
for j in range(M.shape[0]):
for k in range(N.shape[1]):
L0[i, j] += np.sum((N[i, k] - M[j, k])**2)
print(L0)
优化后
# N[n, d]
# M[m, d]
L01 = np.zeros((N.shape[0], M.shape[0]))
for i in range(N.shape[0]):
for j in range(M.shape[0]):
L01[i, j] += np.sum((N[i] - M[j])**2)
print(L01)
进一步优化
# N[n, d]
# M[m, d]
L = np.zeros((N.shape[0], M.shape[0]))
for i in range(N.shape[0]):
L[i] = np.sum((N[i] - M)**2, 1)
print(L)
终极优化
对数据扩充维度
M_1 = np.tile(np.expand_dims(M, 0), (N.shape[0], 1, 1))
print(M_1)
N_1 = np.tile(np.expand_dims(N, 1), (1, M.shape[0], 1))
print(N_1)
L_1 = np.sum((N_1 - M_1)**2, 2)
print(L_1)