矩阵乘法维度令人困惑

时间:2020-05-02 09:29:21

标签: python pytorch torch torchtext

我正在关注本教程https://pytorch.org/tutorials/beginner/nlp/deep_learning_tutorial.html#example-logistic-regression-bag-of-words-classifier

nn.Linear(vocab_size, num_labels) 表示矩阵形状为num_labels x vocab_size

bow_vector尺寸为1 x vocab_size,而预期的nn.linear输入为batch_size x features

现在,我们将num_labels x vocab_size矩阵乘以1 x vocab_size。因此,尺寸与矩阵乘法不匹配。我在这里想念什么? :思考:

https://discuss.pytorch.org/t/matrix-multiplication-dimentions-confusing/79376?u=abhigenie92

1 个答案:

答案 0 :(得分:0)

您在nn.Linear中误解了。让我为您指出一点。

nn.Linear(vocab_size, num_labels)并不表示矩阵形状为num_labels x vacab_size

原始文件为nn.Linear(input_dim, output_dim, bias=True)。假设您在3D空间中有3个点,并且要将这些点投影到2D空间中。因此,您只需创建一个线性图层即可帮助您做到这一点=> nn.Linear(3, 2, bias=True)

示例:

linear_function = nn.Linear(3, 2, bias=True) # you have just created a function
a_3D_point = torch.Tensor([[1, 1, 1]])
a_2D_point = linear_function(a_3D_point)

基本上,nn.Linear()可以帮助您创建一个可以进行投影的函数。

因此您可能想知道nn.Linear如何帮助您进行投影。好吧,当投影只是y = Wx + by = Wx(如果bias = False)(其中W是权重而b是偏差,并且两者都它们将由nn.Linear随机创建。通过以下方式查看:

print(list(linear_function.parameters()))  # Unchecked since I use my iPad to write this answer

================

根据我的理解,根据您的情况,BowClassifier只是尝试将句子分类为有限类。最简单的方法之一是使用一个形状为n x vocab的热向量。

n表示您有n句子,但是第二维的vocab现在扮演代表每个句子的特征。

您现在想将n个句子分类为num_labels类,只需进行投影即可。

input = ...  # shape: [n x vocab]
classify_fn = nn.Linear(vocab, num_labels)
output = classify_fn(input)

# sigmoid or softmax to get the probability here
...