一、感知器
1.神经网络和感知器
神经网络结构包含输入层、隐藏层(可以有多层)、输出层,如下图所示
其中每个神经元是一个感知器,感知器的结构组成部分:输入权值、激活函数、输出
ps:激活函数可以有很多种选择,而感知器的输出由 y=f(w*x+b)来计算
感知器结构如下图:
2.感知器的训练:(个人觉得是神经网络的重点,通过已有的数据,对权值W的相关计算)
感知器的迭代公式:
3.实战:通过感知器实现and函数
训练数据输入:[1,1]->1 [1,0]->0 [0,1]->0 [0,0]->0
激活函数:使用阶跃函数
输出:y=f(w*x+b)
代码如下(原文代码python2,简单修改代码后为python3,已实现):
from functools import reduce class Perception(object): def __init__(self,input_num,activator): self.activator=activator self.weight=[0.0 for _ in range(input_num)] print(self.weight) self.bias=0.0 def __str__(self): return "weights:{0},bias:{1}".format(list(self.weight),self.bias) def predict(self,input_X): return self.activator( reduce(lambda a,b:a+b, map(lambda x,w:x*w,input_X,self.weight),0.0)+self.bias ) def train(self,iteration,input_X,Label,rate): for i in range(iteration): self.one_interation(input_X,Label,rate) def one_interation(self,input_X,Label,rate): samples=zip(input_X,Label) for (a,b) in samples: y_temp=self.predict(a) self.update_weight(a,b,rate,y_temp) def update_weight(self,input_X,Label,rate,y_temp): delta=Label-y_temp self.weight=list(map(lambda x,w:w+rate*delta*x,input_X,self.weight)) self.bias+=rate*delta def f(x): return 1 if x>0 else 0 def get_train_dataset(): input_X=[[1,1],[0,0],[1,0],[0,1]] Label=[1,0,0,0] return input_X,Label def train_and_perception(): p=Perception(2,f) input_X,Label=get_train_dataset() p.train(10,input_X,Label,0.1) return p if __name__=='__main__': perception=train_and_perception() print(perception) print(perception.predict([1,1])) print(perception.predict([1,0])) print(perception.predict([0,1])) print(perception.predict([0,0]))