你对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 + b 或y = Wx(如果偏差=False)时,数学上很容易,其中W 是重量,b 是偏差,它们都将由@987654333 随机创建@。通过以下方式查看:
print(list(linear_function.parameters())) # Unchecked since I use my iPad to write this answer
=================
映射到您的情况,我理解的 BowClassifier 只是尝试将句子分类为有限类。最简单的方法之一是使用一个形状为n x vocab 的热向量。
n 表示你有n 句子,但是第二维中的词汇现在扮演了代表每个句子的特征的角色。
你现在想把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
...