Perceptron Approach

Perceptron Approach

from tkinter import *
import numpy as np


# 样本空间1
def pattern_one(event):
    global w1
    x1, y1 = (event.x - 5), (event.y - 5)
    x2, y2 = (event.x + 5), (event.y + 5)
    w.create_oval(x1, y1, x2, y2, fill='red')  # 实时获取的坐标作为参数
    w1 = np.concatenate((w1, [[event.x, event.y, 1]]), axis=0)


# 样本空间2
def pattern_two(event):
    global w2
    x1, y1 = (event.x - 5), (event.y - 5)
    x2, y2 = (event.x + 5), (event.y + 5)
    w.create_oval(x1, y1, x2, y2, fill='green')  # 实时获取的坐标作为参数
    w2 = np.concatenate((w2, [[-event.x, -event.y, -1]]), axis=0)


# 感知器算法
def judge():
    global w1
    global w2
    W = np.random.random((1, 3))*10
    X = np.concatenate((w1, w2), axis=0)
    while True:
        nc = 0
        for x in X:
            if np.dot(np.array([x]), W.T) <= 0:
                W += np.array([x])
                continue
            nc += 1
        if nc == np.shape(X)[0]:
            x1 = 20
            y1 = -(W[0, 2] + W[0, 0]*20)/W[0, 1]
            x2 = 380
            y2 = -(W[0, 2] + W[0, 0]*380)/W[0, 1]
            print(y1, y2, W)
            w.create_line(x1, y1, x2, y2, fill='white')
            break


def change():
    w.bind('<Button-1>', pattern_two)


def restart_program():
    global w1
    global w2
    for item in w.find_all():
        w.delete(item)
    w.bind('<Button-1>', pattern_one)
    w1 = np.empty((0, 3))
    w2 = np.empty((0, 3))


if __name__ == '__main__':
    # 初始化样本空间
    w1 = np.empty((0, 3))
    w2 = np.empty((0, 3))

    root = Tk()
    # 建立画布
    w = Canvas(root, bg='blue', height=400, width=400)
    w.pack()
    # 绑定左键点击事件
    w.bind('<Button-1>', pattern_one)
    # 按钮部分
    button = Frame(root).pack(side=BOTTOM)
    Button(button, text='Change', command=change, width=18).pack(side=LEFT)
    Button(button, text='Run', command=judge, width=18).pack(side=LEFT)
    Button(button, text='Reset', command=restart_program, width=18).pack(side=RIGHT)
    mainloop()
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值