pytorch实现感知机模型

发布时间 2023-11-12 10:32:34作者: Yuxi001

感知机是一种简单的二分类模型,通常用于线性分类任务。

以下是使用 PyTorch 和 Python 实现感知机模型的示例代码,并附有注释。

python
import torch
import torch.nn as nn
import torch.optim as optim
import matplotlib.pyplot as plt
import numpy as np

# 生成一些随机的线性可分数据
np.random.seed(42)
num_samples = 100
features = 2
x = 10 * np.random.rand(num_samples, features)  # 生成随机输入特征
w_true = np.array([2, -3.4])  # 真实的权重
b_true = 4.2  # 真实的偏置
y_true = np.dot(x, w_true) + b_true + 0.1 * np.random.randn(num_samples)  # 添加噪声
y_true = np.where(y_true > 0, 1, -1)  # 将输出标签转换为二分类问题

# 将数据转换为 PyTorch 的 Tensor
x = torch.tensor(x, dtype=torch.float32)
y_true = torch.tensor(y_true, dtype=torch.float32)

# 定义感知机模型
class Perceptron(nn.Module):
    def __init__(self, input_size):
        super(Perceptron, self).__init__()
        self.linear = nn.Linear(input_size, 1)

    def forward(self, x):
        return torch.sign(self.linear(x))

# 初始化感知机模型
perceptron = Perceptron(input_size=features)

# 定义损失函数和优化器
criterion = nn.MSELoss()
optimizer = optim.SGD(perceptron.parameters(), lr=0.01)

# 训练感知机模型
num_epochs = 100
for epoch in range(num_epochs):
    # 前向传播
    y_pred = perceptron(x)

    # 计算损失
    loss = criterion(y_pred.view(-1), y_true)

    # 反向传播和优化
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

    # 打印损失
    if (epoch + 1) % 10 == 0:
        print(f'Epoch [{epoch + 1}/{num_epochs}], Loss: {loss.item():.4f}')

# 在训练数据上进行预测
with torch.no_grad():
    predictions = perceptron(x).numpy()

# 可视化结果
plt.scatter(x[:, 0], x[:, 1], c=predictions.flatten(), cmap='coolwarm', marker='o')
plt.title('Perceptron Model')
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
plt.show()

这个示例包括以下步骤:

1. 生成一个简单的线性可分数据集。
2. 定义了一个简单的感知机模型。
3. 使用均方误差(MSE)作为损失函数,随机梯度下降(SGD)作为优化器。
4. 训练感知机模型。
5. 使用训练后的模型在训练数据上进行预测。
6. 可视化模型的决策边界。