《程序员的AI书_从代码开始》第二章 手工实现神经网络

2.1 感知器
2.1.1 从神经元到感知器
2.1.2 实现简单的感知器
class Perception(object):
    def __init__(self,eta=0.01,iterations=10):
        self.lr = eta
        self.iterations = iterations
        self.w = 0.0
        self.bias = 0.0
        self.a = 0

    def fit(self,X,Y):
        for _ in range(self.iterations):
            for i in range(len(X)-2):
                x = X[i]
                y = Y[i]
                updata = self.lr * (y-self.predict(x))
                self.w += updata * x
                self.bias += updata


    def net_input(self,x):
        # print(type(self.w))
        # print(type(x))
        # self.a +=1
        # print(self.a)
        return self.w * x +self.bias
    

    def predict(self,x):
         return 1.0 if self.net_input(x) > 0.0 else 0.0

    


x=[1,2,3,10,20,-2,-10,-100,-5,-20]
y=[1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0]

model = Perception(0.01,10)
model.fit(x,y)

test_x=[30,40,-20,-60]

for i in range(0,len(test_x)):
    print('input{}=>predict:{}'.format(test_x[i],model.predict(test_x[i])))

print(model.w,model.bias)

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/GQ_Sonofgod/article/details/131483395