从零手写感知器 python 篇

这篇博客介绍了如何从零开始用Python实现感知器,这是神经网络的基础。感知器通过两个公式进行运算,文章提供了详细的代码实现,包括权重和偏置的更新。并给出了基于AND真值表的训练数据集,演示了感知器的训练过程和预测功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

从零手写感知器 python 篇
感知器是入门神经网络的基础
主要用到了两个公式
1、在这里插入图片描述

2、在这里插入图片描述
参考文章:点击前往

# -*- coding: utf-8 -*-
import numpy as np 
class Perceptron(object):
    
    def __init__(self, input_num):
        
        self.activator = self.f
        self.weights = [0.0] * input_num
        self.bias = 0.0
        
    def __str__(self):
        """
        打印学习到的权重、偏置项
        """
        return 'weights\t:%s\nbias\t:%f\n' % (self.weights, self.bias)
    
    def predict(self, input_vec):
        return np.dot(input_vec, self.weights) + self.bias
    
    def train(self, input_vecs, labels, counts, rate):
        # 训练的数据, 标签 ,轮数 , 下降率
        for i in range(counts):
            self.one_iteration(input_vecs, labels, rate)
            
    def one_iteration(self, input_vecs, labels, rate):
        
        samples = zip(input_vecs, labels)
        
        for (input_vec, label) in samples:
            out_put = self.predict(input_vec)
            
            self.update_weight(input_vec,
                               out_put,
                               label,
                               rate
                               )
            
    def update_weight(self, input_vec, out_put, label, rate):
        # 训练等于 w = w + fw
        # fw = rate * (label - out_put) * xi
        delta = label - out_put
        updateW = np.dot(delta * rate, input_vec)
        self.weight = np.add(self.weights, updateW)
        self.bias = rate * delta
    def f(self, x):
        return 1 if x > 0 else 0
            
def get_training_dataset():
        """
        基于and真值表构建训练数据
        """
        # 构建训练数据
        # 输入向量列表
        input_vecs = [[1, 1], [0, 0], [1, 0], [0, 1]]
        # 期望的输出列表,注意要与输入一一对应
        # [1,1] -> 1, [0,0] -> 0, [1,0] -> 0, [0,1] -> 0
        labels = [1, 0, 0, 0]
        return input_vecs, labels
def train_and_perceptron():
        p = Perceptron(2)
        input_vecs, labels = get_training_dataset()
        p.train(input_vecs, labels, 10, 0.1)
        return p
if __name__  == "__main__":
    and_perceptron = train_and_perceptron()
    print("my")
    print(and_perceptron)
    print('1 and 1 = %d' % and_perceptron.predict([1, 1]))
    print('0 and 0 = %d' % and_perceptron.predict([0, 0]))
    print('1 and 0 = %d' % and_perceptron.predict([1, 0]))
    print('0 and 1 = %d' % and_perceptron.predict([0, 1]))
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

东哥aigc

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值