多层感知机实现异或代码
时间: 2023-06-29 19:13:43 浏览: 80
以下是使用PyTorch实现的多层感知机解决异或问题的代码:
```python
import torch
import torch.nn as nn
import torch.optim as optim
# 定义模型结构
class MLP(nn.Module):
def __init__(self):
super(MLP, self).__init__()
self.fc1 = nn.Linear(2, 4) # 输入层到隐藏层
self.fc2 = nn.Linear(4, 1) # 隐藏层到输出层
self.act = nn.Sigmoid() # 激活函数
def forward(self, x):
x = self.fc1(x)
x = self.act(x)
x = self.fc2(x)
x = self.act(x)
return x
# 数据集
x = torch.Tensor([[0, 0], [0, 1], [1, 0], [1, 1]])
y = torch.Tensor([[0], [1], [1], [0]])
# 模型、损失函数、优化器
model = MLP()
criterion = nn.MSELoss()
optimizer = optim.SGD(model.parameters(), lr=0.1)
# 训练
for epoch in range(10000):
optimizer.zero_grad()
output = model(x)
loss = criterion(output, y)
loss.backward()
optimizer.step()
if epoch % 1000 == 0:
print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, 10000, loss.item()))
# 测试
with torch.no_grad():
output = model(x)
print('Output: {}'.format(output))
```
在此代码中,我们定义了一个包含一个隐藏层的MLP,使用Sigmoid函数作为激活函数,使用均方误差作为损失函数,使用随机梯度下降算法作为优化器。然后,我们使用数据集进行训练,最终输出模型的预测结果。