KNN Classifier报Unknown label type: 'continuous'错误代码问题排查
报错问题解决
核心问题
你的任务是预测连续型目标值,属于回归场景,但错误使用了K近邻分类器KNeighborsClassifier:
- 分类器仅支持离散类别标签作为训练目标,你传入的
y是连续数值类型,因此触发Unknown label type: 'continuous'的标签类型不匹配错误。 - 回归场景需要使用
KNeighborsRegressor(K近邻回归器)完成建模。
修正方案
仅需要替换KNN相关的导入和实例化代码即可,其余逻辑无需改动:
# training data x = np.arange(0 , 5 , 0.05) f_x = beta0 + beta1 * x + beta2 * x**2 + beta3 * x**3 epsilon = np.random.normal(loc=0, scale=sigma, size=100) y = f_x + epsilon ## test data x_test = np.arange(0 , 6, 0.1) f_x_test = beta0 + beta1 * x_test + beta2 * x_test**2 + beta3 * x_test**3 epsilon_test = np.random.normal(loc=0, scale=sigma, size=len(x_test)) y_test = f_x_test + epsilon_test z = np.random.multivariate_normal(size = 100, mean=[0]*20, cov=np.identity(20)) z_test = np.random.multivariate_normal(size = 60, mean=[0]*20, cov=np.identity(20)) train_x = np.concatenate((np.expand_dims(x, axis = 1),z),axis = 1) test_x = np.concatenate((np.expand_dims(x_test, axis = 1),z_test),axis = 1) # 替换分类器为回归器 from sklearn.neighbors import KNeighborsRegressor from sklearn import preprocessing knn = KNeighborsRegressor(n_neighbors = 15) from sklearn.metrics import mean_squared_error knn.fit(train_x,y) y_pred_train = knn.predict(train_x) y_pred_test = knn.predict(test_x) mse_train = mean_squared_error(y,y_pred_train) mse_test = mean_squared_error(y_test,y_pred_test)
内容的提问来源于stack exchange,提问作者analyticsaspirant
相关产品推荐
相关产品推荐

