【问题标题】:Matrix multiplication dimensions confusing矩阵乘法维度令人困惑
【发布时间】:2020-08-16 19:24:38
【问题描述】:

我正在关注这个教程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

【问题讨论】:

    标签: python pytorch torch torchtext


    【解决方案1】:

    你对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(如果偏差=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
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-15
      • 1970-01-01
      • 2017-03-20
      • 2014-05-05
      相关资源
      最近更新 更多