Last active
August 29, 2015 14:06
-
-
Save Linusp/d52197934febe5c3c638 to your computer and use it in GitHub Desktop.
perceptron_dual_form
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python | |
| # -*- coding: utf-8 -*- | |
| """ | |
| Author : Linusp | |
| Date : 2014/08/30 | |
| Description: Simple Perceptron Training | |
| """ | |
| import numpy as np | |
| import matplotlib.pyplot as plt | |
| import matplotlib.animation as animation | |
| import time | |
| fig = plt.figure() | |
| ax1 = fig.add_subplot(1, 1, 1) | |
| x = np.loadtxt('a.txt') | |
| alpha = np.zeros(len(x)) | |
| bias = 0.0 | |
| fai = 0.8 | |
| def is_error_classify(arr): | |
| weight = np.dot(np.multiply(alpha, x[:, 2].T), x[:, 0:2]) | |
| result = (np.dot(arr[0:2], weight) + bias) * arr[2] | |
| return result <= 0 | |
| def first_error(): | |
| global x, last | |
| for i in range(0, len(x)): | |
| if is_error_classify(x[i]): | |
| return i | |
| return -1 | |
| def update(i): | |
| global alpha, bias, x, fai | |
| alpha[i] = alpha[i] + fai | |
| bias = bias + fai * x[i, 2] | |
| weight = np.dot(np.multiply(alpha, x[:, 2].T), x[:, 0:2]) | |
| print "Error points(%d): (%f %f - %d);Weight: (%f %f); bias: %f" %(i, | |
| x[i][0], x[i][1], x[i][2], weight[0], weight[1], bias) | |
| def plot_all_points(): | |
| global x, ax1 | |
| for point in x: | |
| if point[2] == 1: | |
| ax1.plot(point[0], point[1], 'ro') | |
| else: | |
| ax1.plot(point[0], point[1], 'bo') | |
| def animate(i): | |
| global alpha, bias, x | |
| err_index = first_error() | |
| if err_index >= 0: | |
| update(err_index) | |
| else: | |
| exit | |
| ax1.clear() | |
| plot_all_points() | |
| x_range = np.arange(-5, 15, 0.025) | |
| y_range = np.arange(-5, 15, 0.025) | |
| X, Y = np.meshgrid(x_range, y_range) | |
| weight = np.dot(np.multiply(alpha, x[:, 2].T), x[:, 0:2]) | |
| f = weight[0] * X + weight[1] * Y + bias | |
| ax1.contour(X, Y, f, [0], colors=('green')) | |
| plt.xlim([-5, 15]) | |
| plt.ylim([-5, 15]) | |
| if __name__ == '__main__': | |
| plot_all_points() | |
| ani = animation.FuncAnimation(fig, animate, interval=500) | |
| plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment