感知机模型

一、概述

  感知机模型(Perceptron Model)也叫做神经元模型,设计灵感即来自于生物神经元的运行机制,依次完成信息接收、处理、输出的过程。当前大放异彩的各种人工神经网络模型即由一个个人工神经元构成,因此,本文介绍的感知机模型(神经元模型)就是各种神经网络模型的基本单元。

二、模型原理

模型原理

  模型的核心概况起来即是线性回归+符号函数映射。对未知数据,先做线性拟合,输出值再经符号函数映射,完成类别判定。因此,感知机模型也是直接用于二分类任务的模型。模型示意图可表示为

模型原理直接地表示也就是

\[y=\left\{ \begin{aligned} &-1, \ w\cdot x+b<0\\ &1, \ w\cdot x+b\geq 0 \end{aligned} \right. \]

对任意待测样本,将其特征向量直接代入计算即可。

模型的训练

  模型的参数就是指线性回归中的权重和偏置,确定了它们也就确定了整个模型。对参数的确定往往通过训练数据集实施,也就是由训练集和标签之间的对应构造一个关于待求参数的损失函数,通过不断迭代优化,在过程中确定出最佳的参数值。损失函数的构造通常采用这样一种方式,就是计算所有误分类样本到决策函数的距离和。表达式为

\[d=\frac{1}{\left| \left| w \right| \right|}\sum_{x_i\in M}{\left| w\cdot x_i+b \right|} \]

其中,\(\left| \left| w \right| \right|=\sqrt{w_{1}^{2}+w_{2}^{2}+...+w_{n}^{2}}\),M为误分类样本集。
  为进一步简化,可以将绝对值计算以‘-y’等价替换。y是样本的标签,取值要么为1,要么为-1,若y为1,表明样本为正,错误判定时计算得到的回归值为负,此时‘-y负值’为正;若y为-1,表明样本为负,错误判定时计算得到的回归值为正,此时‘-y正值’仍为正,与绝对值运算等价,此时损失函数表达式为

\[d=-\frac{1}{\left| \left| w \right| \right|}\sum_{x_i\in M}{y_i(w\cdot x_i+b)} \]

  式中的\(\frac{1}{\left| \left| w \right| \right|}\)实质地表征了决策函数的方向性,而模型关注的是对两类样本的类别结果判定,并不实际关注决策函数的具体方向以及样本到函数距离的具体差异,因而该部分可以省去,损失函数也就简化为

\[d=-\sum_{x_i\in M}{y_i(w\cdot x_i+b)} \]

三、Python实现

手工实现:

import numpy as np
from sklearn import datasets

def model(X, theta):
    return X @ theta

def predict(x, theta):
    flags = model(x, theta)
    y = np.ones_like(flags)
    y[np.where(flags < 0)[0]] = -1
    return y

def computerCost(X, y, theta):
    y_pred = predict(X, theta)
    error_index = np.where(y_pred != y)[0]
    return np.squeeze(-y_pred[error_index].T @ y[error_index])

def gradientDescent(X, y, alpha, num_iters=1000):
    n = X.shape[1]
    theta = np.zeros((n, 1))
    J_history = []
    for i in range(num_iters):
        y_pred = predict(X, theta)
        error_index = np.where(y_pred != y)[0]
        theta = theta + alpha * X[error_index, :].T @ y[error_index]
        cur_cost = computerCost(X, y, theta)
        J_history.append(cur_cost)
        print('.', end='')
        if cur_cost == 0:
            print(f'Finished in advance in iteration {i + 1}!')
            break

    return theta, J_history

iris = datasets.load_iris()
X = iris.data
m = X.shape[0]
X = np.hstack((np.ones((m, 1)), X))
y = iris.target
y[np.where(y != 0)[0]] = -1
y[np.where(y == 0)[0]] = 1
y = y.reshape((len(y), 1))
theta, J_history = gradientDescent(X, y, 0.01, 1000)
y_pred = predict(X, theta)
acc = np.sum(y_pred == y) / len(y)

print('acc:\n', acc)


基于PyTorch实现:

import torch
import torch.nn as nn
import torch.optim as optim
import matplotlib
matplotlib.use('TkAgg')
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()


End.


pdf下载

posted @ 2024-09-06 11:54  归去_来兮  阅读(131)  评论(0编辑  收藏  举报