欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

我的第一个感知机!!!(哭了

程序员文章站 2022-07-12 12:02:33
...
import numpy as np
import io

class Perceptron(object):
    # 输入节点初始化权重和偏置常数b(假设与偏置常数相乘的输入值一直为0)
    def __init__(self, inode_num, learning_rate):
     #   self.inode_vec = inode_vec                     # 初始化输入节点个数
        self.weight = np.zeros(inode_num)         # 初始化权重
        self.learning_rate = learning_rate
        self.bias = 0.0
        
    #定义**函数
    def activator(self, Sum):                 # 返回0/1
        if Sum > 0:
            outcome = 1
        else:
            outcome = 0
        return outcome
    
    #权重更新
    def train(self, inode_vec, label):
        ixw = np.hstack((inode_vec * self.weight, np.array([self.bias])))          # 计算输入与权重乘积后与偏置常数合并为一个向量
        ixw_sum = ixw.sum()                   # 返回计算后的元素总和
        output = self.activator(ixw_sum)           # 总和输入**函数
        delta = label - output                     # 计算误差
        delta_weight = self.learning_rate * delta * inode_vec         # 计算权重误差
        delta_bias = self.learning_rate * delta          # 计算偏置常数误差
        self.weight += delta_weight           # 权重更新
        self.bias += delta_bias           #偏置常数更新
    
    def printout(self):
        print('weight:', self.weight, 'bias:', self.bias,) 
samples = io.open(r'C:\Users\john\PerceptronTest.csv','r')    # 打开训练样本
list_samples = samples.readlines()
samples.close()
inode_num = 2
learning_rate = 0.1
n = Perceptron(inode_num, learning_rate)
iterate_num = 5               #设置迭代次数

for i in range(0,iterate_num):
    for item in list_samples:   
        inode_vec = np.asfarray( item[:-1].split(',') )      
        label = inode_vec[2]
        inode_vec = inode_vec[:2]
        n.train(inode_vec, label)
        n.printout()
相关标签: 感知机