python使用KNeighborsClassifier出现FutureWarning: Unlike other reduction functions (e.g. `skew`, `kurtosi

问题:

在python中使用KNeighborsClassifier函数出现如下警告:

FutureWarning: Unlike other reduction functions (e.g. `skew`, `kurtosis`), the default behavior of `mode` typically preserves the axis it acts along. In SciPy 1.11.0, this behavior will change: the default value of `keepdims` will become False, the `axis` over which the statistic is taken will be eliminated, and the value None will no longer be accepted. Set `keepdims` to True or False to avoid this warning.

mode, _ = stats.mode(_y[neigh_ind, k], axis=1)

未来警告:不像其他缩减函数(如`skew', `kurtosis'),`mode'的默认行为通常会保留它所沿的轴。在SciPy 1.11.0中,这种行为将发生变化:`keepdims`的默认值将变为False,统计的`轴'将被消除,不再接受None值。将`keepdims'设置为True或False以避免这种警告。

mode, _ = stats.mode(_y[neigh_ind, k], axis=1)

即在未来的1.11.0版本SciPy中,stats.mode里面的keepdims的默认值不再是None了。需要将`keepdims'设置为True或False以避免这种警告。

查看scipy.stats.mode的官方文档

scipy.stats.mode(a, axis=0, nan_policy='propagate', keepdims=None)

其中keepdims如果设置为False,则统计数据所在的轴将被消耗(从输出阵列中消除),就像其他缩减函数(例如偏度、峰度)一样。如果设置为True,则轴将保留为大小1,并且结果将针对输入阵列正确广播。默认值None是为向后兼容而保留的未定义的遗留行为

在SciPy 1.11.0中,此行为将发生变化:keepdims的默认值将变为False,统计数据所在的轴将被消除,None将不再被接受。

从1.9.0版开始出现此警告,目前(2023年1月)为1.10.0版本,换句话说,将SciPy降到1.8.0可能也可以消除此警告(未尝试)

解决方法:

方法一:

(ctrl+左键)打开KNeighborsClassifier的源码,搜索

mode, _ = stats.mode(_y[neigh_ind, k], axis=1)

 在里面加上“, keepdims=True”,重启jupyter内核即可。

方法二:

在使用KNeighborsClassifier(n_neighbors=5, *, weights='uniform', algorithm='auto', leaf_size=30, p=2, metric='minkowski', metric_params=None, n_jobs=None)

时,只有在weights='uniform' 时才会用到stats.mode。其中uniform是均等权重,即邻域中的所有点的权重相等,相当于取众数

可将其改为weights='distance' 。这种情况下,距离近的近邻点比距离远的近邻点具有更大的权重,且未使用stats.mode

(weights='uniform' 相当于直接取众数,类似简单平均;

weights='distance' 类似加权平均,可以简单地理解为以距离的倒数作为权重的"加权众数"。

由于KNN假设距离近的样本更相似,距离远的样本不相似,因此这种方式看上去似乎更合理)

物联沃分享整理
物联沃-IOTWORD物联网 » python使用KNeighborsClassifier出现FutureWarning: Unlike other reduction functions (e.g. `skew`, `kurtosi

发表评论