Home

gentlesnow

23 Oct 2018

【ML】2 k近邻法

scikit-learn
Nearest Neighbors Classification

print(__doc__)

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from sklearn import neighbors, datasets

n_neighbors = 15

# import some data to play with
iris = datasets.load_iris()

# we only take the first two features. We could avoid this ugly
# slicing by using a two-dim dataset
X = iris.data[:, :2]
y = iris.target

h = .02  # step size in the mesh

# Create color maps
cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF'])
cmap_bold = ListedColormap(['#FF0000', '#00FF00', '#0000FF'])

for weights in ['uniform', 'distance']:
    # we create an instance of Neighbours Classifier and fit the data.
    clf = neighbors.KNeighborsClassifier(n_neighbors, weights=weights)
    clf.fit(X, y)

    # 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,
                edgecolor='k', s=20)
    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()

#!/user/bin/env python
# coding:utf-8
'''
Created on 2018-10-23
Upgrate on 2018-11-03
Anthor: Moriarty12138
Github: https://github.com/Moriarty12138/machine-learning-practice
'''
import numpy as np
from sklearn.datasets import load_boston

def mykNN(X_train, y_train, X_test, K):
    '''
    get the most close point
    :param X_train: train dataset X
    :param y_train: train dataset target
    :param X_test: test data
    :param K: the K
    :return: the most close point in X_train
    '''
    # cal the distance X_test to X_train.
    diff = X_train - X_test
    squaredDiff = diff ** 2
    squaredDist = np.sum(squaredDiff, axis=1)
    dist = squaredDist ** 0.5
    # sort distance.
    sortedDistIndex = np.argsort(dist)
    indexCount = {}
    for i in range(K):
        vote = y_train[sortedDistIndex[i]]
        indexCount[vote] = indexCount.get(vote, 0) + 1
    # vote the most close point.
    maxCount = 0
    for key, value in indexCount.items():
        if value > maxCount:
            maxCount = value
            pred = key
    # return the point.
    return pred

if __name__ == '__main__':
    boston = load_boston()
    print("loading boston dataset.")
    point = 5
    K = 10
    X_train, X_test, y_train, y_test = boston.data[point:], boston.data[:point], boston.target[point:], boston.target[:point]
    X = X_test[1]
    y = y_test[1]
    y_pred = mykNN(X_train, y_train, X, K)
    print("y and pred is:")
    print(y,y_pred)

Til next time,
gentlesnow at 21:48

scribble