【问题标题】:Multi-class for sentence classification with pytorch (Using nn.LSTM)使用 pytorch 进行句子分类的多类(使用 nn.LSTM)
【发布时间】:2020-03-29 08:08:21
【问题描述】:

我有这个网络,是从 this 教程中获取的,我希望将句子作为输入(已经完成),结果只是一个单行张量。

从教程中,这句话“约翰的狗喜欢食物”,得到一个 1 列张量返回:

tensor([[-3.0462, -4.0106, -0.6096],
[-4.8205, -0.0286, -3.9045],
[-3.7876, -4.1355, -0.0394],
[-0.0185, -4.7874, -4.6013]])

...和班级列表:

tag_list[ “name”, “verb”, “noun”]

每一行都有一个标签与单词相关联的概率。 (第一个词有 [-3.0462, -4.0106, -0.6096] 向量,其中最后一个元素对应于最高得分标签,“名词”)

教程的数据集如下所示:

training_data = [
    ("The dog ate the apple".split(), ["DET", "NN", "V", "DET", "NN"]),
    ("Everybody read that book".split(), ["NN", "V", "DET", "NN"])
]

我希望我的格式是这样的:

training_data = [
    ("Hello world".split(), ["ONE"]),
    ("I am dog".split(), ["TWO"]),
    ("It's Britney glitch".split(), ["THREE"])
]

参数定义为:

class LSTMTagger(nn.Module):
    def __init__(self, embedding_dim, hidden_dim, vocab_size, tagset_size):
        super(LSTMTagger, self).__init__()
        self.hidden_dim = hidden_dim
        self.word_embeddings = nn.Embedding(vocab_size, embedding_dim)
        self.lstm = nn.LSTM(embedding_dim, hidden_dim)
        self.hidden2tag = nn.Linear(hidden_dim, tagset_size)

    def forward(self, sentence):
        embeds      = self.word_embeddings(sentence)
        lstm_out, _ = self.lstm(embeds.view(len(sentence), 1, -1))
        tag_space   = self.hidden2tag(lstm_out.view(len(sentence), -1))
        tag_scores  = F.log_softmax(tag_space, dim=1)
        return tag_scores

截至目前,输入和输出的大小不匹配,我得到: ValueError: Expected input batch_size (2) to match target batch_size (1).

由于尺寸不匹配,标准函数不接受输入:

loss        = criterion(tag_scores, targets)

我读过最后一层可以定义为 nn.Linear 以压缩输出,但我似乎无法得到任何结果。尝试了其他损失函数

如何更改它以便模型对句子进行分类,而不是像原始教程中那样对每个单词进行分类?

【问题讨论】:

    标签: python machine-learning neural-network pytorch torch


    【解决方案1】:

    我解决了这个问题,通过简单地获取最后的隐藏状态

    tag_space   = self.hidden2tag(lstm_out[-1])
    

    【讨论】:

      猜你喜欢
      • 2020-07-11
      • 2012-08-31
      • 2021-05-09
      • 1970-01-01
      • 2017-09-30
      • 2021-11-13
      • 2021-01-31
      • 2018-05-02
      • 2017-09-27
      相关资源
      最近更新 更多