Perceptron Approach

    xiaoxiao2022-07-06  199

    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()
    最新回复(0)