栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

从零手写感知器 python 篇

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

从零手写感知器 python 篇

从零手写感知器 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 'weightst:%snbiast:%fn' % (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]))
    
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/958243.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号