mlp神经网络画sinx
时间: 2023-06-30 22:09:06 浏览: 83
MLP神经网络可以用来拟合函数,包括正弦函数。下面是Python代码示例,使用PyTorch实现MLP神经网络拟合sinx函数:
```python
import torch
import torch.nn as nn
import numpy as np
import matplotlib.pyplot as plt
# Generate sin(x) data
x = np.linspace(-np.pi, np.pi, 2000)
y = np.sin(x)
# Convert data to tensors
x_tensor = torch.tensor(x, dtype=torch.float).unsqueeze(1)
y_tensor = torch.tensor(y, dtype=torch.float).unsqueeze(1)
# Define neural network model
class MLP(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super().__init__()
self.hidden = nn.Linear(input_size, hidden_size)
self.out = nn.Linear(hidden_size, output_size)
def forward(self, x):
x = torch.relu(self.hidden(x))
x = self.out(x)
return x
# Instantiate model
model = MLP(1, 10, 1)
# Define loss function and optimizer
criterion = nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
# Train model
for epoch in range(10000):
# Forward pass
y_pred = model(x_tensor)
loss = criterion(y_pred, y_tensor)
# Backward pass
optimizer.zero_grad()
loss.backward()
optimizer.step()
if epoch % 1000 == 0:
print(f'Epoch {epoch}, loss: {loss.item()}')
# Plot results
y_pred = model(x_tensor).detach().numpy()
plt.plot(x, y, label='sin(x)')
plt.plot(x, y_pred, label='predicted sin(x)')
plt.legend()
plt.show()
```
运行以上代码后,将生成一个图表,其中包含原始sinx函数及MLP神经网络的预测结果。可以看到,MLP神经网络可以很好地拟合sinx函数。
阅读全文