import torch import torch.nn as nn import torch.optim as optim import numpy as np 定义基本循环神经网络模型 class RNNModel(nn.Module): def init(self, rnn_type, input_size, hidden_size, output_size, num_layers=1): super(RNNModel, self).init() self.rnn_type = rnn_type self.input_size = input_size self.hidden_size = hidden_size self.output_size = output_size self.num_layers = num_layers self.encoder = nn.Embedding(input_size, hidden_size) if rnn_type == 'RNN': self.rnn = nn.RNN(hidden_size, hidden_size, num_layers) elif rnn_type == 'GRU': self.rnn = nn.GRU(hidden_size, hidden_size, num_layers) self.decoder = nn.Linear(hidden_size, output_size) def forward(self, input, hidden): input = self.encoder(input) output, hidden = self.rnn(input, hidden) output = output.view(-1, self.hidden_size) output = self.decoder(output) return output, hidden def init_hidden(self, batch_size): if self.rnn_type == 'RNN': return torch.zeros(self.num_layers, batch_size, self.hidden_size) elif self.rnn_type == 'GRU': return torch.zeros(self.num_layers, batch_size, self.hidden_size) 定义数据集 with open('汉语音节表.txt', encoding='utf-8') as f: chars = f.readline() chars = list(chars) idx_to_char = list(set(chars)) char_to_idx = dict([(char, i) for i, char in enumerate(idx_to_char)]) corpus_indices = [char_to_idx[char] for char in chars] 定义超参数 input_size = len(idx_to_char) hidden_size = 256 output_size = len(idx_to_char) num_layers = 1 batch_size = 32 num_steps = 5 learning_rate = 0.01 num_epochs = 100 定义模型、损失函数和优化器 model = RNNModel('RNN', input_size, hidden_size, output_size, num_layers) criterion = nn.CrossEntropyLoss() optimizer = optim.Adam(model.parameters(), lr=learning_rate) 训练模型 for epoch in range(num_epochs): model.train() hidden = model.init_hidden(batch_size) loss = 0 for X, Y in data_iter_consecutive(corpus_indices, batch_size, num_steps): optimizer.zero_grad() hidden = hidden.detach() output, hidden = model(X, hidden) loss = criterion(output, Y.view(-1)) loss.backward() torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0) optimizer.step() if epoch % 10 == 0: print(f"Epoch {epoch}, Loss: {loss.item()}")请正确缩进代码
时间: 2024-03-16 07:43:02 浏览: 207
Task03 循环神经网络进阶(pytorch代码实现)
下面是正确缩进的代码:
```python
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
# 定义基本循环神经网络模型
class RNNModel(nn.Module):
def __init__(self, rnn_type, input_size, hidden_size, output_size, num_layers=1):
super(RNNModel, self).__init__()
self.rnn_type = rnn_type
self.input_size = input_size
self.hidden_size = hidden_size
self.output_size = output_size
self.num_layers = num_layers
self.encoder = nn.Embedding(input_size, hidden_size)
if rnn_type == 'RNN':
self.rnn = nn.RNN(hidden_size, hidden_size, num_layers)
elif rnn_type == 'GRU':
self.rnn = nn.GRU(hidden_size, hidden_size, num_layers)
self.decoder = nn.Linear(hidden_size, output_size)
def forward(self, input, hidden):
input = self.encoder(input)
output, hidden = self.rnn(input, hidden)
output = output.view(-1, self.hidden_size)
output = self.decoder(output)
return output, hidden
def init_hidden(self, batch_size):
if self.rnn_type == 'RNN':
return torch.zeros(self.num_layers, batch_size, self.hidden_size)
elif self.rnn_type == 'GRU':
return torch.zeros(self.num_layers, batch_size, self.hidden_size)
# 定义数据集
with open('汉语音节表.txt', encoding='utf-8') as f:
chars = f.readline()
chars = list(chars)
idx_to_char = list(set(chars))
char_to_idx = dict([(char, i) for i, char in enumerate(idx_to_char)])
corpus_indices = [char_to_idx[char] for char in chars]
# 定义超参数
input_size = len(idx_to_char)
hidden_size = 256
output_size = len(idx_to_char)
num_layers = 1
batch_size = 32
num_steps = 5
learning_rate = 0.01
num_epochs = 100
# 定义模型、损失函数和优化器
model = RNNModel('RNN', input_size, hidden_size, output_size, num_layers)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
# 训练模型
for epoch in range(num_epochs):
model.train()
hidden = model.init_hidden(batch_size)
loss = 0
for X, Y in data_iter_consecutive(corpus_indices, batch_size, num_steps):
optimizer.zero_grad()
hidden = hidden.detach()
output, hidden = model(X, hidden)
loss = criterion(output, Y.view(-1))
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
optimizer.step()
if epoch % 10 == 0:
print(f"Epoch {epoch}, Loss: {loss.item()}")
```
阅读全文