【发布时间】:2020-11-10 08:29:47
【问题描述】:
我正在学习神经网络。
当我转置特征时,我得到以下输出:
import torch
def activation(x):
return 1/(1+torch.exp(-x))
### Generate some data
torch.manual_seed(7) # Set the random seed so things are predictable
# Features are 5 random normal variables
features = torch.randn((1, 5))
# True weights for our data, random normal variables again
weights = torch.randn_like(features)
# and a true bias term
bias = torch.randn((1, 1))
product = features.t() * weights + bias
output = activation(product.sum())
张量(0.9897)
但是,如果我转置权重,我会得到不同的输出:
weights_prime = weights.view(5,1)
prod = torch.mm(features, weights_prime) + bias
y_hat = activation(prod.sum())
张量(0.1595)
为什么会这样?
更新
我看到了这个:
y = activation((features * weights).sum() + bias)
为什么一个矩阵特征(1,5)可以乘另一个矩阵权重(1,5)而不先转置权重?
更新 2
看了几篇文章后,我意识到
matrixA * matrixB 不同于 torch.mm(matrixA,matrixB) 和 torch.matmul(matrixA,matrixB)。
有人可以确认我之间的三个理解吗?
-
所以 * 表示逐元素乘法,而 torch.mm() 和 torch.matmul() 是逐矩阵乘法。
-
torch.mm() 和 torch.matmul() 的区别:mm() 专门用于二维矩阵,而 matmul() 可用于更复杂的情况。
-
在我上面链接中提到的这个 Udacity 编码练习的中性网络中,它需要逐元素乘法。
更新 3
只是为了给有同样困惑的人带来视频截图:
这里是视频链接:https://www.youtube.com/watch?time_continue=98&v=6Z7WntXays8&feature=emb_logo
【问题讨论】:
-
对于您的更新 2:是的,
*用于元素乘法。这会进行广播,这就是为什么行向量*列向量会产生外积的原因。torch.matmul比torch.mm支持场景,也做广播。对于 Udacity 示例,逐元素乘法有效,因为它后面跟着一个和,这会产生一个点积。
标签: python machine-learning neural-network pytorch