分类和绘制的数据点数与数据集中的点数不匹配

The number of data points being classified and plotted do not match the number of points in the dataset

我正在使用一个数据集,该数据集有 54 个数据点要在 Python 中使用 k-NN 分类器和 # of neighbors 进行分类:20.My 代码进行分类并绘制结果,但我只看到我的散点图中有 22 个数据点,而不是被分类的 54 个数据点。

机器学习中是否存在未对所有数据点进行分类和绘制的原因?

所选择的邻居数量是否会影响被分类和绘制的数据点数量?谢谢

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

# Preprocessing of dataset done here.
n_neighbors = 20
dataset = pd.read_csv('cereal.csv')
X = dataset.iloc[:, [3,5]].values
y = dataset.iloc[:, 1].values
y_set = preprocessing.LabelEncoder()
y_fit = y_set.fit(y)
y_trans = y_set.transform(y)

# sorting dataset done here.Total number of data points :77 but 54 will 
# be selected to use
j = 0
for i in range (0,77):
if y[i] == 'K' or y[i] == 'G' or y[i] == 'P':
    j = j+1

new_data = np.zeros((j,2))
new_let = [0] * j
j = 0

for i in range (0,77):
if y[i] == 'K' or y[i] == 'G' or y[i] == 'P':
    new_data[j] = X[i]
    new_let[j] = y[i]
    j = j+1

# Plotting and setting up mesh grid done here

h = .02
cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF'])
cmap_bold = ListedColormap(['#FF0000', '#00FF00', '#0000FF'])

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

# 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)

plt.scatter(X[:, 0], X[:, 1], c=y_trans, 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()

首先,您在分类器和绘图中使用了数据集的所有 77 个点。您创建的包含 54 个点的变量未用于拟合分类器或生成结果图。

您应该在 运行 脚本之后检查 Anaconda 中的变量资源管理器,以查看您正在使用的不同变量的大小。

关于您生成的图,如果您查看数据的分布方式,您就会明白为什么只看到 22 个点:

如果您查看原始数据集,就会发现这两列(脂肪和卡路里)中有几个点共享重复值。结果,图中有几个点堆叠在一起,因此尽管您绘制了 77 个点,但您的图中只有 "see" 22 个。如果你想看到它们很好地分开,你可能想选择一些其他属性。