pytorch用rnn模型拟合sin函数
时间: 2024-01-05 08:04:38 浏览: 127
使用Pytorch来拟合函数方式
可以使用PyTorch中的RNN模型来拟合sin函数。以下是一个简单的例子:
```python
import torch
import torch.nn as nn
import matplotlib.pyplot as plt
import numpy as np
# 定义模型
class RNN(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(RNN, self).__init__()
self.hidden_size = hidden_size
self.rnn = nn.RNN(input_size, hidden_size, batch_first=True)
self.fc = nn.Linear(hidden_size, output_size)
def forward(self, x, hidden):
out, hidden = self.rnn(x, hidden)
out = self.fc(out)
return out, hidden
# 训练模型
input_size = 1
hidden_size = 32
output_size = 1
sequence_length = 20
num_epochs = 1000
learning_rate = 0.01
rnn = RNN(input_size, hidden_size, output_size)
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(rnn.parameters(), lr=learning_rate)
hidden = None
for epoch in range(num_epochs):
# 生成随机序列
inputs = torch.from_numpy(np.random.uniform(-np.pi, np.pi, size=(1, sequence_length, input_size))).float()
outputs = torch.sin(inputs)
# 前向传播
rnn.zero_grad()
hidden = hidden.detach() if hidden is not None else None
outputs, hidden = rnn(inputs, hidden)
loss = criterion(outputs, outputs)
# 反向传播
optimizer.zero_grad()
loss.backward()
optimizer.step()
if (epoch+1) % 100 == 0:
print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, num_epochs, loss.item()))
# 测试模型
with torch.no_grad():
inputs = torch.from_numpy(np.linspace(-np.pi, np.pi, num=100).reshape(1, -1, 1)).float()
outputs = torch.sin(inputs)
hidden = None
preds, hidden = rnn(inputs, hidden)
plt.plot(inputs.squeeze().numpy(), outputs.squeeze().numpy(), label='target')
plt.plot(inputs.squeeze().numpy(), preds.squeeze().numpy(), label='prediction')
plt.legend()
plt.show()
```
这个例子中,我们使用一个有一个隐藏层的RNN模型来拟合sin函数。我们生成随机序列作为输入,并将其作为sin函数的输出进行训练。在1000个epoch之后,我们使用训练好的模型来预测sin函数,并将其可视化。
阅读全文