单层神经网络简单实例

#!/bin/env python3

# -*-coding:utf-8-*-

from decimal import Decimal


class Neuron:
    w1 = Decimal(0)
    w2 = Decimal(0)
    thet = Decimal(0)
    alpha = Decimal(0)

    def __init__(self, w1, w2, thet=Decimal(0.2), alpha=Decimal(0.1)):
        self.w1 = w1
        self.w2 = w2
        self.thet = thet
        self.alpha = alpha

    def train_single(self, x1, x2, ev):

        total = Decimal(self.w1 * x1 + self.w2 * x2)

        ret = total - Decimal(self.thet)

        if self.step(round(ret, 2)) == ev:
            return True

        Yp = Decimal(ev - self.step(round(ret, 2)))

        self.w1 = Decimal(Decimal(self.w1) + Decimal(self.alpha) * Decimal(x1) * Yp)
        self.w2 = Decimal(Decimal(self.w2) + Decimal(self.alpha) * Decimal(x2) * Yp)
        return False

    @staticmethod
    def step(val):
        """activation function"""
        if val >= 0:
            return 1

        return 0

    def predict(self, x1, x2):

        total = Decimal(self.w1 * x1 + self.w2 * x2)

        ret = total - Decimal(self.thet)

        if self.step(round(ret, 2)) > 0:
            return 1

        return 0

    def __str__(self):
        return f"[w1:{round(self.w1,2)},w2:{round(self.w2,2)},thet:{self.thet}, alpha:{self.alpha}]"


if __name__ == '__main__':

    neuron = Neuron(w1=0.3, w2=-0.1, thet=0.2, alpha=0.1)
    print('do train')
    print()

    for i in range(0, 10):
        print(f"do training #{i}")
        cnt = 0
        if neuron.train_single(0, 0, 0):
            cnt += 1

        if neuron.train_single(0, 1, 0):
            cnt += 1

        if neuron.train_single(1, 0, 0):
            cnt += 1

        if neuron.train_single(1, 1, 1):
            cnt += 1

        if cnt == 4:
            print("train success")
            print(neuron)
            break

    print()

    print('do predict')
    print(f"0 & 0 = {neuron.predict(0, 0)}")
    print(f"0 & 1 = {neuron.predict(0, 1)}")
    print(f"1 & 0 = {neuron.predict(1, 0)}")
    print(f"1 & 1 = {neuron.predict(1, 1)}")

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值