pytorch mlp实现二分类
时间: 2024-02-23 07:54:42 浏览: 151
PyTorch是一个流行的深度学习框架,可以用于实现各种机器学习模型,包括多层感知机(MLP)。下面是一个简单的PyTorch MLP实现二分类的示例:
```python
import torch
import tor.nn as nn
import torch.optim as optim
# 定义MLP模型
class MLP(nn.Module):
def ____(self, input_size, hidden_size, output_size):
super(MLP, self).__init__()
self.fc1 = nn.Linear(input_size, hidden_size)
self = nn.ReLU()
self.fc2 = nn.Linear(hidden_size, output_size)
self.sigmoid = nn.Sigmoid()
forward(self, x):
out = self.fc(x)
out = self.relu(out)
out = self.fc2(out)
out = self.sigmoid(out)
return out
# 定义训练数据和标签
x_train = torch.tensor([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=torch.float32)
y_train = torch.tensor([[0], [1], [1], [0]], dtype=torch.float32)
# 定义模型参数
input_size = 2
hidden_size = 4
output_size = 1
# 创建模型实例
model = MLP(input_size, hidden_size, output_size)
# 定义损失函数和优化器
criterion = nn.BCELoss()
optimizer = optim.SGD(model.parameters(), lr=0.1)
# 训练模型
num_epochs = 1000
for epoch in range(num_epochs):
# 前向传播
outputs = model(x_train)
loss = criterion(outputs, y_train)
# 反向传播和优化
optimizer.zero_grad()
loss.backward()
optimizer.step()
# 每100个epoch打印一次损失值
if (epoch+1) % 100 == 0:
print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, num_epochs, loss.item()))
# 测试模型
x_test = torch.tensor([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=torch.float32)
with torch.no_grad():
predictions = model(x_test)
predicted_labels = (predictions >= 0.5).float()
print('Predictions:')
for i in range(len(x_test)):
print('Input: {}, Predicted Label: {}'.format(x_test[i].tolist(), predicted_labels[i].item()))
```
这个示例中,我们定义了一个包含两个隐藏层的MLP模型,输入大小为2,输出大小为1。使用二进制交叉熵损失函数和随机梯度下降优化器进行训练。训练完成后,我们使用训练好的模型进行预测。
阅读全文