感知机及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))
相关推荐
机器学习之心15 小时前
PINN物理信息神经网络股票价格预测模型Matlab实现
人工智能·pinn·物理信息神经网络
咕咚-萌西15 小时前
MLLM-LLaVA-FL: Multimodal Large Language Model Assisted FederatedLearning
人工智能·语言模型·自然语言处理
人工智能研究所15 小时前
视频与音频碰撞,谷歌 Veo 3.1,生成“有声电影”,人物对话超震撼
人工智能·文生图·谷歌·文生视频·veo3.1
DisonTangor15 小时前
PaddleOCR-VL: 通过0.9B超紧凑视觉语言模型增强多语言文档解析
人工智能·计算机视觉·语言模型·自然语言处理·开源·aigc
skywalk816315 小时前
在Ubuntu Linux安装brew 使用brew安装llama.cpp 运行文心Ernie大模型
人工智能·ubuntu·llama·ernie·brew·1024程序员节
golang学习记15 小时前
Vibe Coding不香了,试试深信服的CoStrict 严肃编程模式
人工智能
蒙奇·D·路飞-15 小时前
Grok、Claude、ChatGPT、Gemini模型适用场景比较
人工智能·chatgpt
腾视科技15 小时前
安全驾驶 智在掌控|腾视科技ES06终端,为车辆运营赋能
大数据·人工智能·科技·安全·大模型
飞哥数智坊15 小时前
Cursor + CloudBase,两周闲暇时间做出我的“AI 碎片助理”
人工智能·ai编程
库库83916 小时前
Spring AI 知识点总结
java·人工智能·spring