![]() |
#2
TysonKoothra2019-08-01 19:17
|
![](zzz/editor/img/code.gif)
#===================类====================
class Perceptron(object):
def init (self,input_num,activator): #初始化函数,设置输入参数的个数以及激活函数
self.activator = activator #设置激活函数
self.weights = [0.0 for _ in range(input_num)]#设置初始化函数为0
self.bias = 0.0 #设置偏置项为0
def predict(self,input_vec): #输入样本向量,输出预测结果
return self.activator(reduce(lambda a,b:a+b,map(lambda x,w:x*w,zip(input_vec,self.weights)),0.0)+self.bias)
……
#中间就不放了
……
#=========================================
#-----------------------------------------
#主程序中定义的函数,希望它能在类中调用
……
def judge(x): #激活函数
return 1 if x > 0 else 0
#-----------------------------------------
#=========================================
p = Perceptron(2,judge)
#自己尝试的方法,会报错:
#Traceback (most recent call last):
# p = Perceptron(2,judge)
#TypeError: Perceptron() takes no arguments
#=========================================