Created
January 14, 2018 03:01
-
-
Save sughodke/3e86c792ec7bc792394fd9208688a9e8 to your computer and use it in GitHub Desktop.
Train an Estimator to learn how to encode any integer to binary
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
""" | |
Train an Estimator to learn how to encode integer to binary | |
""" | |
import numpy as np | |
X = np.array([ | |
[1, -1], [1, 0], [1, 1], | |
[0, -1], [0, 0], [0, 1], | |
[-1, -1], [-1, 0], [-1, 1], | |
]) | |
# Top | |
# Middle | |
# Bottom | |
# Corner | |
y = np.array([ | |
(1, 0, 0, 1), | |
(1, 0, 0, 0), | |
(1, 0, 0, 1), | |
(0, 1, 0, 0), | |
(0, 1, 0, 0), | |
(0, 1, 0, 0), | |
(0, 0, 1, 1), | |
(0, 0, 1, 0), | |
(0, 0, 1, 1), | |
]) | |
from sklearn.svm import SVC | |
clf = SVC() | |
from sklearn.neighbors import KNeighborsClassifier | |
clf = KNeighborsClassifier() | |
from sklearn.ensemble import RandomForestClassifier | |
clf = RandomForestClassifier() | |
clf.fit(X, y) | |
print(clf.predict([[-0.8, -1]])) | |
import matplotlib.pyplot as plt | |
from matplotlib.colors import ListedColormap | |
h = .02 # step size in the mesh | |
# Create color maps | |
cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF']) | |
cmap_bold = ListedColormap(['#FF0000', '#00FF00', '#0000FF']) | |
# Plot the decision boundary. For that, we will assign a color to each | |
# point in the mesh [x_min, x_max]x[y_min, y_max]. | |
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 | |
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 | |
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), | |
np.arange(y_min, y_max, h)) | |
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) | |
# Put the result into a color plot | |
Z = Z.reshape(xx.shape) | |
plt.figure() | |
plt.pcolormesh(xx, yy, Z, cmap=cmap_light) | |
# Plot also the training points | |
plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold) | |
plt.xlim(xx.min(), xx.max()) | |
plt.ylim(yy.min(), yy.max()) | |
plt.title("3-Class classification (k = %i, weights = '%s')" | |
% (n_neighbors, weights)) | |
plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment