【发布时间】:2021-01-03 03:32:34
【问题描述】:
我想为 k-nn 分类器绘制具有不同 k 值的图形。 我的问题是这些数字似乎具有相同的 k 值。 到目前为止,我尝试的是在循环中的每次运行中更改 k 的值:
clf = KNeighborsClassifier(n_neighbors=counter+1)
但是所有的数字似乎都是针对k=1
from sklearn.datasets import fetch_california_housing
data = fetch_california_housing()
import numpy as np
from sklearn.model_selection import train_test_split
c = np.array([1 if y > np.median(data['target']) else 0 for y in data['target']])
X_train, X_test, c_train, c_test = train_test_split(data['data'], c, random_state=0)
from sklearn.neighbors import KNeighborsClassifier
import mglearn
import matplotlib.pyplot as plt
fig, ax = plt.subplots(nrows=1, ncols=3, figsize=(20, 6))
for counter in range(3):
clf = KNeighborsClassifier(n_neighbors=counter+1)
clf.fit(X_test, c_test)
plt.tight_layout() # this will help create proper spacing between the plots.
mglearn.discrete_scatter(X_test[:,0], X_test[:,1], c_test, ax=ax[counter])
plt.legend(["Class 0", "Class 1"], loc=4)
plt.xlabel("First feature")
plt.ylabel("Second feature")
#plt.figure()
【问题讨论】:
标签: python machine-learning knn