假設某公司有4個工廠,每個工廠都有3種產品,銷量數據如下:
工廠 | P1 | P2 | P3 |
---|---|---|---|
甲 | 5 | 2 | 4 |
乙 | 3 | 8 | 2 |
丙 | 6 | 0 | 4 |
丁 | 0 | 1 | 6 |
每種產品的成本利潤如下:
產品 | 成本 | 利潤 |
---|---|---|
P1 | 2 | 4 |
P2 | 1 | 3 |
P3 | 3 | 2 |
則這個公司各個工廠的總成本和總利潤爲:
甲:成本=5x2+2x1+4x3=24 利潤=5x4+2x3+4x2=34
乙:成本=3x2+8x1+2x3=20 利潤=3x4+8x3+2x2=40
丙:成本=6x2+0x1+4x3=24 利潤=6x4+0x3+4x2=32
丁:成本=0x2+1x1+6x3=19 利潤=0x4+1x3+6x2=15
工廠產品銷量、產品成本利潤,分別可以用兩個矩陣表示,矩陣相乘即爲工廠的總成本和總利潤
Numpy 中的矩陣相乘函數
import numpy as np
A = np.array([[5,2,4], [3,8,2], [6,0,4], [0,1,6]])
array([[5, 2, 4],
[3, 8, 2],
[6, 0, 4],
[0, 1, 6]])
B = np.array([[2,4], [1,3], [3,2]])
array([[2, 4],
[1, 3],
[3, 2]])
C = np.matmul(A, B)
array([[24, 34],
[20, 40],
[24, 32],
[19, 15]])
深度學習框架 TensorFlow 和 PyTorch 中的矩陣相乘函數如下
import tensorflow as tf
C = tf.matmul(A, B)
[[24 34]
[20 40]
[24 32]
[19 15]]
import torch
A = torch.from_numpy(A)
B = torch.from_numpy(B)
C = torch.matmul(A, B) # 或者 torch.mm(A, B)
tensor([[24, 34],
[20, 40],
[24, 32],
[19, 15]])
矩陣A的形狀是 [4, 3]
矩陣B的形狀是 [3, 2]
矩陣C的形狀是 [4, 2]
發現什麼了嗎?
在進行深度學習計算時,有時候需要注意下矩陣維度是否正確,否則就報錯了
a = np.array([1,2,3])
array([1, 2, 3])
b = a.reshape(-1,1)
array([[1],
[2],
[3]])
# numpy
np.matmul(a, b)
array([14])
# tensorflow
sess.run(tf.matmul(a, b))
ValueError: Shape must be rank 2 but is rank 1 for 'MatMul_14' (op: 'MatMul') with input shapes: [3], [3,1].
# 報錯: 張量應該是2階,但是其中一個爲1階
# pytorch
torch.matmul(torch.from_numpy(a), torch.from_numpy(b))
tensor([14]) # 正常輸出
torch.mm(torch.from_numpy(a), torch.from_numpy(b))
RuntimeError: matrices expected, got 1D, 2D tensors at /Users/administrator/nightlies/pytorch-1.0.0/wheel_build_dirs/wheel_3.5/pytorch/aten/src/TH/generic/THTensorMath.cpp:935
# 報錯: a張量是1D(1維),b張量是2D(2維),無法進行計算
# 修正
a = a.reshape(-1, 3)