在训练数据时经常涉及到矩阵运算,有段时间没有练习过了,手便生疏了,今天重新测了一把,python中各类矩阵运算举例如下,可以清楚的看到tf.matmul(A,C)=np.dot(A,C)= A@C都属于叉乘,而tf.multiply(A,C)= A*C=A∙C属于点乘。
Python测试编码如下:
import tensorflow as tf
import numpy as np
a = np.array([[1,2],[3,4]])
b = np.array([5,6])
c = np.array([[5,6],[7,8]])
print(‘a:’+’\n’,a)
print(‘b:’+’\n’,b)
print(‘c:’+’\n’,c)
#叉乘
d1=a@c
d2=tf.matmul(a,c)
d3=np.dot(a,c)
#点乘
f1=a*c
f2=tf.multiply(a,c)with tf.compat.v1.Session() as sess:
print(‘d1:叉乘a@c’ + ‘\n’, d1)
print(‘d2:叉乘matmul(a,c)’ + ‘\n’, sess.run(d2))
print(‘d3:叉乘dot(a,c)’ + ‘\n’, d3)
print(‘f1:点乘a*c’ + ‘\n’, f1)
print(‘f2:点乘multiply(a,c)’ + ‘\n’, sess.run(f2))
测试结果如下:
import torch
from torch import nn
class MyLinear(nn.Module):
def __init__(self, in_features, out_features):
super().__init__()
self.weight = nn.Parameter(torch.randn(in_features, out_features))
self.bias = nn.Parameter(torch.randn(out_features))
def forward(self, input):
return (input @ self.weight) + 2*self.bias
# 其中的@,torch.matmul, torch.dot,numpy.dot.
# torch.mul(), torch.multipy(), *, 是点乘积。
m = MyLinear(4, 3)
sample_input = torch.randn(4)
k = m(sample_input)
print(k)