import torch import torch.nn as nn from torchtext.datasets import AG_NEWS from torchtext.data.utils import get_tokenizer from torchtext.vocab import build_vocab_from_iterator # 数据预处理 tokenizer = get_tokenizer('basic_english') train_iter = AG_NEWS(split='train') counter = Counter() for (label, line) in train_iter: counter.update(tokenizer(line)) vocab = build_vocab_from_iterator([counter], specials=["<unk>"]) word2idx = dict(vocab.stoi) # 设定超参数 embedding_dim = 64 hidden_dim = 128 num_epochs = 10 batch_size = 64 # 定义模型 class RNN(nn.Module): def __init__(self, vocab_size, embedding_dim, hidden_dim): super(RNN, self).__init__() self.embedding = nn.Embedding(vocab_size, embedding_dim) self.rnn = nn.RNN(embedding_dim, hidden_dim, batch_first=True) self.fc = nn.Linear(hidden_dim, 4) def forward(self, x): x = self.embedding(x) out, _ = self.rnn(x) out = self.fc(out[:, -1, :]) return out # 初始化模型、优化器和损失函数 model = RNN(len(vocab), embedding_dim, hidden_dim) optimizer = torch.optim.Adam(model.parameters()) criterion = nn.CrossEntropyLoss() # 定义数据加载器 train_iter = AG_NEWS(split='train') train_data = [] for (label, line) in train_iter: label = torch.tensor([int(label)-1]) line = torch.tensor([word2idx[word] for word in tokenizer(line)]) train_data.append((line, label)) train_loader = torch.utils.data.DataLoader(train_data, batch_size=batch_size, shuffle=True) # 开始训练 for epoch in range(num_epochs): total_loss = 0.0 for input, target in train_loader: model.zero_grad() output = model(input) loss = criterion(output, target.squeeze()) loss.backward() optimizer.step() total_loss += loss.item() * input.size(0) print("Epoch: {}, Loss: {:.4f}".format(epoch+1, total_loss/len(train_data)))改错
时间: 2023-12-08 08:03:24 浏览: 249
python torch.utils.data.DataLoader使用方法
5星 · 资源好评率100%
在代码中出现了一个错误:缺少 `Counter` 的导入语句。需要在开头添加 `from collections import Counter`。
另外,在模型训练时,需要将模型设置为训练模式(`model.train()`),以启用 dropout 和 batch normalization 等功能。同时,还需要将输入和目标数据转移到 GPU 上进行计算,以加速训练过程。具体修改如下:
```
import torch
import torch.nn as nn
from torchtext.datasets import AG_NEWS
from torchtext.data.utils import get_tokenizer
from torchtext.vocab import build_vocab_from_iterator
from collections import Counter
# 数据预处理
tokenizer = get_tokenizer('basic_english')
train_iter = AG_NEWS(split='train')
counter = Counter()
for (label, line) in train_iter:
counter.update(tokenizer(line))
vocab = build_vocab_from_iterator([counter], specials=["<unk>"])
word2idx = dict(vocab.stoi)
# 设定超参数
embedding_dim = 64
hidden_dim = 128
num_epochs = 10
batch_size = 64
# 定义模型
class RNN(nn.Module):
def __init__(self, vocab_size, embedding_dim, hidden_dim):
super(RNN, self).__init__()
self.embedding = nn.Embedding(vocab_size, embedding_dim)
self.rnn = nn.RNN(embedding_dim, hidden_dim, batch_first=True)
self.fc = nn.Linear(hidden_dim, 4)
def forward(self, x):
x = self.embedding(x)
out, _ = self.rnn(x)
out = self.fc(out[:, -1, :])
return out
# 初始化模型、优化器和损失函数
model = RNN(len(vocab), embedding_dim, hidden_dim)
optimizer = torch.optim.Adam(model.parameters())
criterion = nn.CrossEntropyLoss()
# 将模型设置为训练模式
model.train()
# 将数据转移到 GPU 上
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)
train_iter = AG_NEWS(split='train')
train_data = []
for (label, line) in train_iter:
label = torch.tensor([int(label)-1]).to(device)
line = torch.tensor([word2idx[word] for word in tokenizer(line)]).to(device)
train_data.append((line, label))
train_loader = torch.utils.data.DataLoader(train_data, batch_size=batch_size, shuffle=True)
# 开始训练
for epoch in range(num_epochs):
total_loss = 0.0
for input, target in train_loader:
optimizer.zero_grad()
output = model(input)
loss = criterion(output, target.squeeze())
loss.backward()
optimizer.step()
total_loss += loss.item() * input.size(0)
print("Epoch: {}, Loss: {:.4f}".format(epoch+1, total_loss/len(train_data)))
```
阅读全文