python3经典例子_python3机器学习经典实例-第五章构建推荐引擎23

构建一个KNN 分类器

KNN(k-nearest neighbors)是用k个最近邻的训练数据集来寻找未知对象分类的一种算法。如果希望找到未知数据点属于哪个类,可以找到KNN并做一个多数表决。接下来学习如何构建这样的分类器。

修改的内容

修改:test_datapoint = np.array([4.5, 3.6]).reshape(1,-1)#改

修改:plt.scatter(test_datapoint[:,0], test_datapoint[:,1], marker='x',

linewidth=3, s=100, facecolors='cyan')#改

修改:plt.scatter(test_datapoint[:,0], test_datapoint[:,1], marker='x',

linewidth=3, s=100, facecolors='cyan')#改创建nn_classification.py文件,导入必要的数据包

import numpy as np

import matplotlib.pyplot as plt

import matplotlib.cm as cm

from sklearn import neighbors

from utilities import load_data我们将用到data_nn_classifier.txt文件作为输入数据。加载该输入数据:

# Load input data

input_file = 'data_nn_classifier.txt'

data = load_data(input_file)

X, y = data[:,:-1], data[:,-1].astype(np.int)

前两列包含输入数据,最后一列包含标签,因此分别将其用X和y两个变量表示。将输入数据可视化:

# Plot input data

plt.figure()

plt.title('Input datapoints')

markers = '^sov<>hp'

mapper = np.array([markers[i] for i in y])

colors = plt.cm.Spectral(np.linspace(0, 1, 3))

colors = np.array([colors[i] for i in y])

for i in range(X.shape[0]):

plt.scatter(X[i, 0], X[i, 1], marker=mapper[i],

s=50, edgecolors='black', facecolors=colors[i])

迭代所有的数据点,并用合适的标记区分不同的类为了构建分类器,需要指定我们考虑的最近邻的个数

# Number of nearest neighbors to consider

num_neighbors = 10为了将边界可视化,需要定义一个网格,用这个网格评价该分类器

# step size of the grid

h = 0.01接下来创建KNN分类器并进行训练:

# Create a K-Neighbours Classifier model and train it

classifier = neighbors.KNeighborsClassifier(num_neighbors, weights='distance')

classifier.fit(X, y)生成一个网格来画出边界。对网格做如下定义:

# Create the mesh to plot the boundaries

x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1

y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1

x_grid, y_grid = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))评价分类器对所有点的输出:将其画出;我们画出了彩色网格,现在要将训练数据点覆盖在其上,查看这些点与边界的关系在哪里:

# Compute the outputs for all the points on the mesh

predicted_values = classifier.predict(np.c_[x_grid.ravel(), y_grid.ravel()])

# Put the computed results on the map

predicted_values = predicted_values.reshape(x_grid.shape)

plt.figure()

plt.pcolormesh(x_grid, y_grid, predicted_values, cmap=cm.Pastel1)

# Overlay the training points on the map

for i in range(X.shape[0]):

plt.scatter(X[i, 0], X[i, 1], marker=mapper[i],

s=50, edgecolors='black', facecolors=colors[i])

plt.xlim(x_grid.min(), x_grid.max())

plt.ylim(y_grid.min(), y_grid.max())

plt.title('k nearest neighbors classifier boundaries')接下来测试数据点,查看分类器能否准确分类。定义并画出它; 用以下模型提取KNN:画出KNN并突出显示:

# Test input datapoint

test_datapoint = np.array([4.5, 3.6]).reshape(1,-1)#改

plt.figure()

plt.title('Test datapoint')

for i in range(X.shape[0]):

plt.scatter(X[i, 0], X[i, 1], marker=mapper[i],

s=50, edgecolors='black', facecolors=colors[i])

plt.scatter(test_datapoint[:,0], test_datapoint[:,1], marker='x',

linewidth=3, s=100, facecolors='cyan')#改

# Extract k nearest neighbors

dist, indices = classifier.kneighbors(test_datapoint)

# Plot k nearest neighbors

plt.figure()

plt.title('k nearest neighbors')

for i in indices:

plt.scatter(X[i, 0], X[i, 1], marker='o',

linewidth=3, s=50, facecolors='cyan')

plt.scatter(test_datapoint[:,0], test_datapoint[:,1], marker='x',

linewidth=3, s=100, facecolors='cyan')#改

for i in range(X.shape[0]):

plt.scatter(X[i, 0], X[i, 1], marker=mapper[i],

s=50, edgecolors='black', facecolors=colors[i])

print ("Predicted output:", classifier.predict(test_datapoint)[0])

plt.show()结果输出out

Predicted output: 2第一幅输出图像展示了输入数据的分布第二幅输出图像展示了用KNN分类器获得的边界第三幅输出图像展示了测试数据点的位置第四幅输出图像展示了10个最近邻的位置

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值