Python3.6.4 实现感知机代码(与算法)

利用python实现感知机功能,简单的与运算即[1,1]->1,[1,0]->0,[0,1]->0,[0,0]->0。代码实现环境,windows下,python3.6
代码如下:


import numpy as np

class Perceptron(object):
    
    def __init__(self,input_num,activator):
        self.activator = activator
        self.weights = [0.0 for _ in range(input_num)]
        self.bias = 0.0
        
        
    def predict(self,input_vec):
        return self.activator(np.dot(input_vec,self.weights)+self.bias)
        
    def train(self,input_vecs,labels,iteration,rate):
        for i in range(iteration):
            self._one_iteration(input_vecs,labels,rate)
            
    def _one_iteration(self, input_vecs, labels, rate):
        #每一次训练都是一次预测,并不断修正weight和bias
        for i in range(len(labels)):
            output = self.predict(input_vecs[i])
            self._update_weights(input_vecs[i],output,labels[i],rate)
        
    def _update_weights(self, input_vecs, output, labels, rate):
        delta = labels - output
        self.weights = self.weights + np.dot(rate*delta,input_vecs)
        self.bias += rate*delta

def f(x):
    return 1 if x > 0 else 0
    
def get_train_dataset():
    # 设置训练数据
    #输入数据为[[1,1],[0,0],[1,0],[0,1]]
    input_vecs = np.array([[1,1],[0,0],[1,0],[0,1]])
    #对应标准输出数据为[1,0,0,0]
    labels = np.array([1,0,0,0])
    return input_vecs,labels
    
def train_and_preceptron():
    #感知机类的实体化为p
    p = Perceptron(2,f)
    #获取设置的训练数据
    input_vecs,labels = get_train_dataset()
    #对训练数据进行十次训练,设置每次调整比例为0.1
    p.train(input_vecs,labels,10,0.1)
    return p


#程序入口    
if __name__ == '__main__':
    #获得程序的实体化操作后的对象
    perception =train_and_preceptron()
    print(perception.weights)
    print(perception.bias)
    print(perception.predict([1, 1]))
    print(perception.predict([0, 0]))
    print(perception.predict([1, 0]))
    print(perception.predict([0, 1]))

结果如下:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值