【问题标题】:loading pretrained model in pytorch在 pytorch 中加载预训练模型
【发布时间】:2020-02-07 02:19:05
【问题描述】:

首先,我想道歉这个问题可能听起来很愚蠢,但我是深度学习的新手。谁能向我解释一下用于在 PyTorch 中加载预训练模型的以下代码行?

# Retrieving model parameters from checkpoint.
vocab_size = checkpoint["model"]["_word_embedding.weight"].size(0)
embedding_dim = checkpoint["model"]['_word_embedding.weight'].size(1)
hidden_size = checkpoint["model"]["_projection.0.weight"].size(0)
num_classes = checkpoint["model"]["_classification.4.weight"].size(0)

看不懂上面文字中的投影、权重、分类、size(0)、size(1)。

【问题讨论】:

  • 最好还是看看 pytorch 上的一些教程来弄清楚代码的作用,而不是在这里问。
  • 为什么torch.load 不足以满足您的情况?你做了什么研究?

标签: deep-learning nlp pytorch


【解决方案1】:
import torch
import torch.nn as nn


class Model(nn.Module):

    def __init__(self):
        super(Model, self).__init__()

        vocab_size = 10000
        embed_size = 100
        # word embedding layer
        self._word_embedding = nn.Embedding(vocab_size, embed_size)
        # linear transformation layers (no bias)
        self._projection = nn.ModuleList([nn.Linear(100, 50, bias=False)
                                          for i in range(2)])
        # linear transformation layers (no bias)
        self._classification = nn.ModuleList([nn.Linear(50, 50, bias=False)
                                              for i in range(4)])

    def forward(self):
        return


model = Model()
checkpoint = {
    'model': model.state_dict()  # OrderedDict
}

# _word_embedding.weight --> torch.Size([10000, 100])
# _projection.0.weight --> torch.Size([50, 100])
# _projection.1.weight --> torch.Size([50, 100])
# _classification.0.weight --> torch.Size([50, 50])
# _classification.1.weight --> torch.Size([50, 50])
# _classification.2.weight --> torch.Size([50, 50])
# _classification.3.weight --> torch.Size([50, 50])

for name, param in checkpoint['model'].items():
    print(name, '-->', param.size()) # see above

# similarly, we can print as follows
print(checkpoint["model"]["_word_embedding.weight"].size(0)) # 10000
print(checkpoint["model"]["_word_embedding.weight"].size(1)) # 100
print(checkpoint["model"]["_projection.0.weight"].size(0)) # 50
print(checkpoint["model"]["_classification.0.weight"].size(0)) # 50

准备了一个例子来帮助你理解这四行的含义。

看不懂上面文字中的投影、权重、分类、size(0)、size(1)。

  • 投影:神经网络层
  • 分类:神经网络层
  • 权重:各NN层的权重矩阵
  • size(0):权重矩阵第一维的大小
  • size(1):权重矩阵第二维的大小

【讨论】:

    猜你喜欢
    • 2019-07-17
    • 2021-04-05
    • 2021-07-16
    • 2019-09-09
    • 2019-09-11
    • 2020-07-27
    • 2018-02-20
    • 2017-06-11
    • 2021-02-19
    相关资源
    最近更新 更多