Numpy 행렬 연산

정현준·2023년 5월 24일
0

브로드캐스팅

  • 벡터 - 스칼라 = 벡터 - (앞 벡터와 크기가 같고 해당 스칼라 값으로 변환된 벡터)

내적(가중합)

x = np.array([[1], [2], [3]])
y = np.array([[4], [5], [6]])
x.T @ y  # 또는 np.dot(x.T, y)
array([[32]])
x = np.array([1, 2, 3])
y = np.array([4, 5, 6])
x @ y  # 또는 np.dot(x, y)
32

행렬 간의 곱셈

A = np.array([[1, 2, 3], [4, 5, 6]])
B = np.array([[1, 2], [3, 4], [5, 6]])
C = A @ B
C
array([[22, 28],
       [49, 64]])

가중평균

x = np.arange(10)
N = len(x)

np.ones(N) @ x / N
4.5
x.mean()
4.5

유사도

from sklearn.datasets import load_digits
import matplotlib.gridspec as gridspec

digits = load_digits()
d1 = digits.images[0]
d2 = digits.images[10]
d3 = digits.images[1]
d4 = digits.images[11]
v1 = d1.reshape(64, 1)
v2 = d2.reshape(64, 1)
v3 = d3.reshape(64, 1)
v4 = d4.reshape(64, 1)

plt.figure(figsize=(9, 9))
gs = gridspec.GridSpec(1, 8, height_ratios=[1],
                       width_ratios=[9, 1, 9, 1, 9, 1, 9, 1])
for i in range(4):
    plt.subplot(gs[2 * i])
    plt.imshow(eval("d" + str(i + 1)), aspect=1,
               interpolation='nearest', cmap=plt.cm.bone_r)
    plt.grid(False)
    plt.xticks([])
    plt.yticks([])
    plt.title("image {}".format(i + 1))
    plt.subplot(gs[2 * i + 1])
    plt.imshow(eval("v" + str(i + 1)), aspect=0.25,
               interpolation='nearest', cmap=plt.cm.bone_r)
    plt.grid(False)
    plt.xticks([])
    plt.yticks([])
    plt.title("vector {}".format(i + 1))
plt.tight_layout()
plt.show()

out

  • 같은 label인 이미지의 내적
(v1.T @ v2)[0][0], (v3.T @ v4)[0][0]
(3064.0, 3661.0)
  • 다른 label인 이미지의 내적
(v1.T @ v3)[0][0], (v1.T @ v4)[0][0], (v2.T @ v3)[0][0], (v2.T @ v4)[0][0]
(1866.0, 1883.0, 2421.0, 2479.0)

이차형식

x = np.array([1, 2, 3])
x
array([1, 2, 3])
A = np.arange(1, 10).reshape(3, 3)
A
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
x.T @ A @ x
228
profile
정리 블로그

0개의 댓글