|
| 1 | +# Learner: Nguyen Truong Thinh |
| 2 | +# Contact me: [email protected] || +84393280504 |
| 3 | +# |
| 4 | +# Topic: Supervised Learning: Classifications in Action. |
| 5 | +# A primitive kind of support vector machine - Perceptron |
| 6 | + |
| 7 | +import pandas as pd |
| 8 | +import numpy as np |
| 9 | +import matplotlib.pyplot as plt |
| 10 | + |
| 11 | +# Can try two different arrangements of x |
| 12 | +# x = np.array([[1,2], [3,6], [4,7], [5,6], [1,3], [2.5,4], [2,3]]) |
| 13 | +x = np.array([[5, 2], [3, 6], [2, 7], [1, 6], [5, 3], [3.5, 4], [4, 3]]) |
| 14 | +y_orig = np.array([-1, 1, 1, 1, -1, -1, -1]) |
| 15 | +plt.scatter(x[:, 0], x[:, 1], c=y_orig) |
| 16 | +plt.show() |
| 17 | + |
| 18 | +# Length of y(input) vector |
| 19 | +L = y_orig.size |
| 20 | +# Separate X1, X2 to see algorithm clearly |
| 21 | +X1 = x[:, 0].reshape(L, 1) |
| 22 | +X2 = x[:, 1].reshape(L, 1) |
| 23 | +y = y_orig.reshape(L, 1) |
| 24 | +# Creating our weights, start at 0 for 1st iteration |
| 25 | +w0, w1, w2 = 1, 0, 0 |
| 26 | +# Counter to go through each point |
| 27 | +count = 0 |
| 28 | +iteration = 1 |
| 29 | +# Learning rate |
| 30 | +alpha = 0.01 |
| 31 | + |
| 32 | +while iteration < 1000: |
| 33 | + y_hat = w0 + X1 * w1 + X2 * w2 |
| 34 | + prod = y_hat * y # If > 1, the prediction is correct |
| 35 | + for p in prod: |
| 36 | + if p <= 1: |
| 37 | + # Nudge w vector in right direction |
| 38 | + w0 = w0 + alpha * y[count] |
| 39 | + w1 = w1 + alpha * y[count] * X1[count] |
| 40 | + w2 = w2 + alpha * y[count] * X2[count] |
| 41 | + |
| 42 | + count += 1 |
| 43 | + count = 0 |
| 44 | + iteration += 1 |
| 45 | + |
| 46 | +print('w0', w0) |
| 47 | +print('w1', w1) |
| 48 | +print('w2', w2) |
| 49 | + |
| 50 | +# Final perceptron answers (If < 0 -> category 1, else > 0 -> category 2) |
| 51 | +y = w0 + X1 * w1 + X2 * w2 |
| 52 | +# Plot the predictions via Perceptron algorithm |
| 53 | +plt.scatter(x[:, 0], x[:, 1], c=(y < 0).reshape(1, -1)[0]) |
| 54 | +# Plot the line |
| 55 | +q = np.array([0, 7]) # 2 points on x axis. |
| 56 | +# Calculated hyperplane (a line) |
| 57 | +x_ = -(w1 / w2).reshape(1, -1) * q - w0 / w2 |
| 58 | +# f(x) = w.x+b+1 support vector line |
| 59 | +x_p = -(w1 / w2).reshape(1, -1) * q - w0 / w2 - 1 / w2 |
| 60 | +# f(x) = w.x+b+1 support vector line |
| 61 | +x_n = -(w1 / w2).reshape(1, -1) * q - w0 / w2 + 1 / w2 |
| 62 | + |
| 63 | +plt.plot(q, x_[0]) |
| 64 | +plt.plot(q, x_p[0], 'r--') |
| 65 | +plt.plot(q, x_n[0], 'r--') |
| 66 | +plt.xlim([0, 6]) |
| 67 | +plt.ylim([0, 12]) |
| 68 | +plt.grid() |
| 69 | +plt.xlabel(r'$X_{1}$') |
| 70 | +plt.ylabel(r'$X_{2}$') |
| 71 | +plt.show() |
0 commit comments