使用pytorch实现前馈神经网络近似连续函数
时间: 2023-11-03 22:06:04 浏览: 88
以下是使用PyTorch实现前馈神经网络近似连续函数的示例代码:
```python
import torch
import torch.nn as nn
import numpy as np
import matplotlib.pyplot as plt
# 定义连续函数
def func(x):
return np.sin(x)
# 生成训练数据
x_train = np.linspace(0, 2*np.pi, 1000)
y_train = func(x_train)
# 将数据转换为张量
x_train = torch.Tensor(x_train).unsqueeze(1)
y_train = torch.Tensor(y_train).unsqueeze(1)
# 定义前馈神经网络模型
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(1, 10)
self.fc2 = nn.Linear(10, 10)
self.fc3 = nn.Linear(10, 1)
self.relu = nn.ReLU()
def forward(self, x):
x = self.relu(self.fc1(x))
x = self.relu(self.fc2(x))
x = self.fc3(x)
return x
# 定义训练函数
def train(model, optimizer, criterion, x_train, y_train, epochs):
for epoch in range(epochs):
optimizer.zero_grad()
y_pred = model(x_train)
loss = criterion(y_pred, y_train)
loss.backward()
optimizer.step()
if epoch % 100 == 0:
print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, epochs, loss.item()))
# 初始化模型和优化器
model = Net()
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
# 开始训练
train(model, optimizer, criterion, x_train, y_train, 1000)
# 绘制预测结果和原始函数图像
x_test = torch.Tensor(np.linspace(0, 2*np.pi, 1000)).unsqueeze(1)
y_pred = model(x_test).detach().numpy()
plt.plot(x_train.numpy(), y_train.numpy(), 'o')
plt.plot(x_test.numpy(), y_pred, '-')
plt.show()
```
在这个示例中,我们首先定义了一个连续函数,然后使用它生成训练数据。接下来,我们将训练数据转换为PyTorch张量,并定义了一个包含3个全连接层的前馈神经网络模型。我们使用MSELoss作为损失函数,并使用Adam优化器进行优化。最后,我们训练模型,并使用matplotlib绘制了预测结果和原始函数图像。
阅读全文
相关推荐
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)