I am trying to train RNN model to classify sentences into 4 classes, but it doesn’t seem to work. I tried to overfit 4 examples (blue line) which worked, but even as little as 8 examples (red line) is not working, let alone the whole dataset.enter image description here

我try 了不同的学习速度和大小的hidden_sizeembedding_size,但似乎没有帮助,我错过了什么?我知道,如果模型不能过度适应小批量,这意味着应该增加产能,但在这种情况下,增加产能没有效果.

class RNN(nn.Module):
    def __init__(self, embedding_size=256, hidden_size=128, num_classes=4):
        super().__init__()
        self.embedding = nn.Embedding(len(vocab), embedding_size, 0)
        self.rnn = nn.RNN(embedding_size, hidden_size, batch_first=True)
        self.fc = nn.Linear(hidden_size, num_classes)

    def forward(self, x):
        #x=[batch_size, sequence_length]
        x = self.embedding(x) #x=[batch_size, sequence_length, embedding_size]
        _, h_n = self.rnn(x)  #h_n=[1, batch_size, hidden_size]
        h_n = h_n.squeeze(0)
        out = self.fc(h_n)  #out=[batch_size, num_classes]
        return out

输入数据是标记化的句子,用0填充到该批中最长的句子,因此作为一个示例,一个样本是:[278495441321120,0,0].数据来自torchtext数据集的AG_新闻数据集.

培训代码:

model = RNN().to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=LR)
model.train()

for epoch in range(NUM_EPOCHS):
    epoch_losses = []
    correct_predictions = []
    for batch_idx, (labels, texts) in enumerate(train_loader):
        scores = model(texts)
        loss = criterion(scores, labels)
        
        loss.backward()
        optimizer.step()
        optimizer.zero_grad()
    
        epoch_losses.append(loss.item())
        correct = (scores.max(1).indices==labels).sum()
        correct_predictions.append(correct)
        
    epoch_avg_loss = sum(epoch_losses)/len(epoch_losses)
    epoch_avg_accuracy = float(sum(correct_predictions))/float(len(labels))

推荐答案

这个问题是由于消失梯度造成的,它通过批量归一化得到解决.

Python相关问答推荐

使用Python更新字典中的值

使用groupby方法移除公共子字符串

将scipy. sparse矩阵直接保存为常规txt文件

dask无groupby(ddf. agg([min,max])?''''

为什么if2/if3会提供两种不同的输出?

如何使用两个关键函数来排序一个多索引框架?

为什么常规操作不以其就地对应操作为基础?

剪切间隔以添加特定日期

为什么调用函数的值和次数不同,递归在代码中是如何工作的?

pysnmp—lextudio使用next()和getCmd()生成器导致TypeError:tuple对象不是迭代器''

如何按row_id/row_number过滤数据帧

如何防止html代码出现在quarto gfm报告中的pandas表之上

如何在Python中从html页面中提取html链接?

将字节序列解码为Unicode字符串

启动线程时,Python键盘模块冻结/不工作

Django更新视图未更新

大Pandas 中的群体交叉融合

更新包含整数范围的列表中的第一个元素

如何将ManyToManyfield用于Self类

使用pyopencl、ArrayFire或另一个Python OpenCL库制作基于欧几里得距离的掩模