当前位置: 首页 > article >正文

感知机模型

一、概述

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

二、模型原理

模型原理

  模型的核心概况起来即是线性回归+符号函数映射。对未知数据,先做线性拟合,输出值再经符号函数映射,完成类别判定。因此,感知机模型也是直接用于二分类任务的模型。模型示意图可表示为
在这里插入图片描述
模型原理直接地表示也就是
y = { − 1 ,   w ⋅ x + b < 0 1 ,   w ⋅ x + b ≥ 0 y=\left\{ \begin{aligned} &-1, \ w\cdot x+b<0\\ &1, \ w\cdot x+b\geq 0 \end{aligned} \right. y={1, wx+b<01, wx+b0
对任意待测样本,将其特征向量直接代入计算即可。

模型的训练

  模型的参数就是指线性回归中的权重和偏置,确定了它们也就确定了整个模型。对参数的确定往往通过训练数据集实施,也就是由训练集和标签之间的对应构造一个关于待求参数的损失函数,通过不断迭代优化,在过程中确定出最佳的参数值。损失函数的构造通常采用这样一种方式,就是计算所有误分类样本到决策函数的距离和。表达式为
d = 1 ∣ ∣ w ∣ ∣ ∑ x i ∈ M ∣ w ⋅ x i + b ∣ d=\frac{1}{\left| \left| w \right| \right|}\sum_{x_i\in M}{\left| w\cdot x_i+b \right|} d=w1xiMwxi+b
其中, ∣ ∣ w ∣ ∣ = w 1 2 + w 2 2 + . . . + w n 2 \left| \left| w \right| \right|=\sqrt{w_{1}^{2}+w_{2}^{2}+...+w_{n}^{2}} w=w12+w22+...+wn2 ,M为误分类样本集。
  为进一步简化,可以将绝对值计算以‘-y’等价替换。y是样本的标签,取值要么为1,要么为-1,若y为1,表明样本为正,错误判定时计算得到的回归值为负,此时‘-y负值’为正;若y为-1,表明样本为负,错误判定时计算得到的回归值为正,此时‘-y正值’仍为正,与绝对值运算等价,此时损失函数表达式为
d = − 1 ∣ ∣ w ∣ ∣ ∑ x i ∈ M y i ( w ⋅ x i + b ) d=-\frac{1}{\left| \left| w \right| \right|}\sum_{x_i\in M}{y_i(w\cdot x_i+b)} d=w1xiMyi(wxi+b)

  式中的 1 ∣ ∣ w ∣ ∣ \frac{1}{\left| \left| w \right| \right|} w1实质地表征了决策函数的方向性,而模型关注的是对两类样本的类别结果判定,并不实际关注决策函数的具体方向以及样本到函数距离的具体差异,因而该部分可以省去,损失函数也就简化为
d = − ∑ x i ∈ M y i ( w ⋅ x i + b ) d=-\sum_{x_i\in M}{y_i(w\cdot x_i+b)} d=xiMyi(wxi+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下载


http://www.kler.cn/news/292565.html

相关文章:

  • springboot小儿推拿培训系统
  • 蓝牙--关于bta_av_api.cc 文件的讲解
  • java使用jedis连接redis
  • Mac剪贴板管理器:扩展你的复制粘贴能力
  • 卷积公式的几何学理解
  • 硬件工程师笔试面试——继电器
  • windows清理图标缓存
  • 如何实现对窗口window的viewtree进行dump Hierarchy-安卓framework实战开发
  • HarmonyOS开发实战( Beta5版)状态管理优秀实践
  • 二、搭建网站服务器超详细步骤——部署轻量应用服务器(Centos)
  • ceph中pg与pool关系
  • SQL常见100面试题解析
  • vs2019编译opencv+contribute+gpu
  • 【华为OD】2024D卷——查找众数与中位数
  • MacBook真的不能打游戏吗?Mac打游戏会损坏电脑吗?苹果电脑怎么玩游戏
  • 如何在 Java 中实现线程安全的单例模式?
  • 前端宝典二十七:React Native最佳实践实例推荐
  • 强化网络安全:通过802.1X协议保障远程接入设备安全认证
  • 迭代器 Iterator 是什么?
  • Linux修改docker默认存储目录(/var/lib)
  • Twitter上品牌安全指标的关键显示错误已修正
  • 2024跨境旺季营销:哪个平台是流量之王?
  • Ribbon负载均衡底层原理
  • 配置阿里云千问大模型--环境变量dashscope
  • 基于Openface在ubuntu上抽取人脸图像
  • 02【SQL sever 2005数据库安装教程】
  • python学习第三节:创建第一个python项目
  • Python 数据分析— Numpy 基本操作(下)
  • 【大模型实战篇】大模型周边NLP技术回顾及预训练模型数据预处理过程解析(预告)
  • tkcalendar中的DateEntry