KNN算法Python实现遇SciPy mode函数警告,求解决及预测准确率
解决KNN代码中的scipy.stats.mode FutureWarning问题
问题现象
运行自定义KNN代码时出现以下警告:
FutureWarning: Unlike other reduction functions (e.g.
skew,kurtosis), the default behavior ofmodetypically preserves the axis it acts along. In SciPy 1.11.0, this behavior will change: the default value ofkeepdimswill become False, theaxisover which the statistic is taken will be eliminated, and the value None will no longer be accepted. Setkeepdimsto True or False to avoid this warning.
lab = mode(labels)
需要消除警告并确保代码正常输出预测结果与准确率。
解决方案
警告源于SciPy版本更新后mode函数的默认参数行为即将变更,需显式指定keepdims参数;同时清理代码中的冗余赋值,优化输出逻辑。
修改后的完整代码
# 导入所需模块 import numpy as np from scipy.stats import mode from sklearn.metrics import accuracy_score from sklearn.datasets import load_iris from numpy.random import randint # 欧几里得距离计算 def eucledian(p1, p2): dist = np.sqrt(np.sum((p1 - p2) ** 2)) return dist # KNN预测函数 def predict(x_train, y, x_input, k): op_labels = [] # 遍历待分类数据点 for item in x_input: # 存储距离的数组 point_dist = [] # 遍历每个训练数据 for j in range(len(x_train)): distances = eucledian(np.array(x_train[j, :]), item) # 计算距离 point_dist.append(distances) point_dist = np.array(point_dist) # 排序并保留索引,取前K个数据点 dist = np.argsort(point_dist)[:k] # 获取前K个数据点的标签 labels = y[dist] # 多数投票:显式设置keepdims参数消除警告 lab = mode(labels, keepdims=False) lab = lab.mode[0] op_labels.append(lab) return op_labels # 加载数据集 iris = load_iris() # 特征矩阵存储于X X = iris.data # 目标向量存储于y y = iris.target # 创建训练集:移除冗余变量赋值 train_idx = randint(0, 150, 100) X_train = X[train_idx] y_train = y[train_idx] # 创建测试集:移除冗余变量赋值 test_idx = randint(0, 150, 50) # 选取50个随机样本 X_test = X[test_idx] y_test = y[test_idx] # 调用预测函数 y_pred = predict(X_train, y_train, X_test, 7) # 计算并打印准确率 acc = accuracy_score(y_test, y_pred) print(f"预测准确率: {acc:.2f}")
关键修改点
- 消除警告:将
lab = mode(labels)改为lab = mode(labels, keepdims=False),显式指定参数匹配未来版本默认行为,彻底解决警告。 - 精简代码:删除
train_idx = xxx = randint(...)中的xxx =冗余赋值,让代码更简洁。 - 优化输出:添加
print(f"预测准确率: {acc:.2f}"),直接打印准确率结果,无需手动查看变量。
内容的提问来源于stack exchange,提问作者Walid
相关产品推荐
相关产品推荐

