理论上,当k=1时,训练MSE应为零。然而,以下脚本显示的情况却并非如此。我首先生成了一些玩具数据:x代表睡眠时间,y代表幸福感。然后我训练数据并预测结果。最后,我通过两种方法计算训练数据的MSE。谁能告诉我哪里出了问题?
from sklearn.neighbors import KNeighborsRegressormodel = KNeighborsRegressor(n_neighbors=1)import numpy as npx = np.array([7,8,6,7,5.7,6.8,8.6,6.5,7.8,5.7,9.8,7.7,8.8,6.2,7.1,5.7]).reshape(16,1)y = np.array([5,7,4,5,6,9,7,6.8,8,7.6,9.3,8.2,7,6.2,3.8,6]).reshape(16,1)model = model.fit(x,y)for hours_slept in range(1,11): happiness = model.predict([[hours_slept]]) print("if you sleep %.0f hours, you will be %.1f happy!" %(hours_slept, happiness))# calculate MSE# fast methoddef model_mse(model,x,y): predictions = model.predict(x) return np.mean(np.power(y-predictions,2))print(model_mse(model,x,y))
输出结果:
if you sleep 1 hours, you will be 6.0 happy!if you sleep 2 hours, you will be 6.0 happy!if you sleep 3 hours, you will be 6.0 happy!if you sleep 4 hours, you will be 6.0 happy!if you sleep 5 hours, you will be 6.0 happy!if you sleep 6 hours, you will be 4.0 happy!if you sleep 7 hours, you will be 5.0 happy!if you sleep 8 hours, you will be 7.0 happy!if you sleep 9 hours, you will be 7.0 happy!if you sleep 10 hours, you will be 9.3 happy!0.15999999999999992 #严格大于0!
回答:
理论上,当k=1时,训练MSE应为零
这里的隐含假设是没有x
的重复样本,或者更准确地说,相同的特征x
应该有相同的数值y
。这里的情况是否如此?我们来看看
pred = model.predict(x)np.where(pred!=y)[0]# array([9])
因此,确实存在一个y
和pred
不同的值:
y[9]# array([7.6])pred[9]# array([6.])
其中
x[9]# array([5.7])
有多少x
样本的值为5.7
,对应的y
值是什么?
ind = np.where(x==5.7)[0]ind# array([ 4, 9, 15])y[ind]# 结果:array([[6. ], [7.6], [6. ]])pred[ind]# 结果array([[6.], [6.], [6.]])
因此,实际上发生的情况是,对于x=5.7
,算法无法明确决定哪个样本是唯一的最近邻——是y=6
的那个,还是y=7.6
的那个;在这里,它选择了与真实y
不符的那个,导致MSE不为零。
我想,如果深入研究knn的源代码,应该能够解释这种情况是如何在内部处理的,但我将其留作练习。