帮我构建一个最简单的神经网络来训练两个离散的变量,结构随意,使用relu和adam就可以
时间: 2023-05-20 10:07:13 浏览: 144
好的,让我来帮您构建一个简单的神经网络:
```
import torch
import torch.nn as nn
import torch.optim as optim
# 定义训练数据
X = torch.tensor([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=torch.float32)
y = torch.tensor([[0], [1], [1], [0]], dtype=torch.float32)
# 定义神经网络模型
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(2, 4)
self.fc2 = nn.Linear(4, 1)
self.relu = nn.ReLU()
def forward(self, x):
x = self.relu(self.fc1(x))
x = self.relu(self.fc2(x))
return x
net = Net()
# 定义损失函数和优化器
criterion = nn.MSELoss()
optimizer = optim.Adam(net.parameters(), lr=0.001)
# 训练模型
for epoch in range(10000):
optimizer.zero_grad()
predict = net(X)
loss = criterion(predict, y)
loss.backward()
optimizer.step()
# 进行预测
test_tensor = torch.tensor([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=torch.float32)
prediction = net(test_tensor).detach().numpy()
print(prediction)
```
这段代码会构建一个简单的两层神经网络,使用ReLU作为激活函数,Adam作为优化器,训练数据是两个离散变量,其输出的预测值也是离散的。
阅读全文
相关推荐


















