感知机及python实现

感知机(Perceptron)是神经网络的基本构件之一,最初由Frank Rosenblatt在1957年提出。感知机是一种二分类的线性分类器,通过一个简单的线性函数将输入数据分类到两种类别之一。

基本原理

感知机的工作原理如下:

  1. 输入:接受多个输入特征,每个特征有一个权重。

  2. 加权和:计算输入特征与对应权重的加权和。

  3. 激活函数:将加权和通过一个激活函数(通常是阶跃函数或符号函数)转换为输出。

  4. 更新权重:根据预测结果与实际结果之间的差异,调整权重,直到模型能够正确分类。

感知机的输出公式如下:如果 w⋅x+b≥0,y=1,如果 w⋅x+b<0,y=0

其中,w是权重向量,x是输入向量,b 是偏置项。

如何设计感知机

设计一个感知机模型包括以下步骤:

  1. 初始化权重和偏置

    • 将权重向量 w初始化为零或小的随机值。

    • 偏置项 b 初始化为1。

  2. 定义激活函数

    • 使用阶跃函数或符号函数作为激活函数。
  3. 训练模型

    • 输入训练数据集,包含输入特征和对应的标签。

    • 迭代更新权重和偏置,直到收敛或达到预设的迭代次数。

    • 使用如下公式更新权重和偏置:

其中,η为学习率。

示例

python 复制代码
import numpy as np

# 感知机类
class Perceptron:
    def __init__(self, learning_rate, n_iterations):
        self.lr = learning_rate
        self.n_iterations = n_iterations
        self.weights = None
        self.bias = None

    # 训练模型
    def fit(self, X, y):
        n_samples, n_features = X.shape
        
        # 初始化权重和偏置
        self.weights = np.zeros(n_features)
        self.weights_bias = 0
        self.bias = 1
        
        y_ = np.array([1 if i > 0 else 0 for i in y])
        
        # 迭代
        for _ in range(self.n_iterations):
            for idx, x_i in enumerate(X):
                linear_output = np.dot(x_i, self.weights) + self.bias * self.weights_bias
                y_pred = 1 if linear_output >= 0 else 0
                
                # 如果预测错误,则更新权重和偏置
                if y_pred != y_[idx]:
                    self.weights +=  self.lr * (y_[idx] - y_pred) * x_i
                    self.weights_bias +=  self.lr * (y_[idx] - y_pred)
                    
                # 打印权重更新结果
                print(self.weights, self.weights_bias)    
                    
    # 预测
    def predict(self, X):
        linear_output = np.dot(X, self.weights) + self.bias
        y_pred = [1 if i >= 0 else 0 for i in linear_output]
        return np.array(y_pred)

# 示例数据,X为数据点集,y为其分类集
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y = np.array([-1, -1, -1, 1])

# 创建感知机实例
p = Perceptron(learning_rate = 1, n_iterations=10)

# 训练模型
p.fit(X, y)

# 待预测数据
z = np.array([[3,9], [9,3], [3,-9], [-3,9]])

# 预测
print(p.predict(z))
相关推荐
NAGNIP5 小时前
轻松搞懂全连接神经网络结构!
人工智能·算法·面试
moshuying6 小时前
别让AI焦虑,偷走你本该有的底气
前端·人工智能
董董灿是个攻城狮7 小时前
零基础带你用 AI 搞定命令行
人工智能
喝拿铁写前端9 小时前
Dify 构建 FE 工作流:前端团队可复用 AI 工作流实战
前端·人工智能
阿里云大数据AI技术10 小时前
阿里云 EMR Serverless Spark + DataWorks 技术实践:引领企业 Data+AI 一体化转型
人工智能
billhan201610 小时前
MCP 深入理解:协议原理与自定义开发
人工智能
Jahzo10 小时前
openclaw桌面端体验--ClawX
人工智能·github
billhan201610 小时前
Agent 开发全流程:从概念到生产
人工智能
threerocks10 小时前
过了个年,AI 圈变天了?但没人告诉你为什么
人工智能