单层神经网络简单实例

#!/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)}")

 

你可能感兴趣的:(人工智能,机器学习,神经网络)