python3實現並且(and)感知機神經網路

2021-08-19 23:08:48 字數 2252 閱讀 9634

理論知識見

直接上python3**

#coding utf-8

from functools import reduce

class perceptron(object):

#初始化,輸入訓練數目,啟用函式

def __init__(self,input_num,activator):#activator為啟用函式

self.activator=activator

self.weights=[0.0 for _ in range(input_num)]#權重初始化為0

self.bias=0.0#偏置初始化為0.0

#運算def operation(self,input_vec):

#對啟用函式中的引數做運算,x[0]代表input_vec,x[1]代表weights

return self.activator(reduce(lambda a,b:a+b,map(lambda x:x[0]*x[1],zip(input_vec,self.weights)),0.0)+self.bias)#0.0為reduce的初始計算值

#權值更新

def updata(self,input_vec,output,label,rate):

delta=label-output

self.weights=list(map(lambda x:x[1]+rate*delta*x[0],zip(input_vec,self.weights)))#加上list跟python2有區別

self.bias+=rate*delta

#訓練,輸入資料及對應標籤,迭代次數,學習率

def train(self,input_vecs,labels,iteration_num,rate):

for i in range(iteration_num):#iteration_num次迭代

samples=zip(input_vecs,labels)#打包

for (input_vec,label) in samples:

output=self.operation(input_vec)#計算輸出值

self.updata(input_vec,output,label,rate)#更新

#**def predict(self,input_vec):

return self.operation(input_vec)

#列印權值,偏置

def __str__(self):#內部函式

return "weight: %s, bias: %f"%(self.weights,self.bias)#權值返回用%s

'''實現與(and)函式功能'''

#啟用函式為階躍函式

def andactivator(x):

if x>0:

return 1

else:

return 0

#得到訓練資料

def gettraindata():

input_vecs=[[1,1],[1,0],[0,1],[0,0]]#可重用多次迴圈迭代

labels=[1,0,0,0]

return input_vecs,labels

#訓練感知機

def trainperceptron():

p=perceptron(2,andactivator)

input_vecs,labels=gettraindata()

p.train(input_vecs,labels,100,0.1)#100為迭代次數,0.1為學習率

return p

#主函式

if __name__=='__main__':

train_perceptron=trainperceptron()

print(train_perceptron)

#測試 print(train_perceptron.predict([1,1]))

python3實現CryptoJS AES加密演算法

from crypto.cipher import aes from binascii import b2a hex,a2b hex import base64 class aescrypt def init self,key self.key key.encode utf8 self.mode a...

Python3 實現選擇排序

選擇排序 selection sort 原理很簡單,就是依次在未排序資料段中選擇出乙個最小的數,然後將其排列在已排序資料段末端,直到整個資料段排序完成演算法結束。程式如下,第乙個迴圈依次縮小未排序資料段的長度,並且每次將最小值暫定為未排序中第一位索引。第二個迴圈依次將該最小值與未排序資料段作比較,選...

python3實現線性單元

理論知識見 直接上python3的 coding utf 8 import matplotlib.pyplot as plt from functools import reduce class perceptron object 初始化,輸入訓練數目,啟用函式 def init self,inpu...