You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

跟随《Hands-On Machine Learning》代码报错:AttributeError: 'Flags' object has no attribute 'c_contiguous'

解决cross_val_predict抛出AttributeError: 'Flags' object has no attribute 'c_contiguous'错误

问题场景

跟随Aurélien Géron所著《Hands-On Machine Learning》编写多标签分类代码时,执行cross_val_predict步骤抛出错误。

代码片段

y_train_large = (y_train.astype("int") >= 7)
y_train_odd = (y_train.astype("int") % 2 == 1)
y_multilabel = np.c_[y_train_large, y_train_odd]

# model
knn_clf = KNeighborsClassifier()
knn_clf.fit(X_train, y_multilabel)

y_train_knn_pred = cross_val_predict(knn_clf, X_train, y_multilabel, cv=3)

错误信息

AttributeError: 'Flags' object has no attribute 'c_contiguous'

原因分析

这个错误主要来自两个方面:

  1. 数组内存布局不兼容:np.c_生成的数组可能不是C连续内存布局,而scikit-learn的cross_val_predict对目标数组的内存布局有要求。
  2. 版本不匹配:numpy与scikit-learn版本不兼容(比如numpy 2.x搭配旧版scikit-learn,或反之),导致内部属性调用出错。

解决方案

方案1:强制转换为C连续数组

将构造的多标签数组转为C连续内存布局,直接修改y_multilabel的构造代码:

y_multilabel = np.ascontiguousarray(np.c_[y_train_large, y_train_odd])

修改后再执行后续的模型训练与交叉验证预测即可。

方案2:对齐numpy与scikit-learn版本

  • 若使用scikit-learn >=1.3.0,确保numpy版本 >=1.21.0;
  • 若安装了numpy 2.x,需升级scikit-learn到适配版本(>=1.4.0),或降级numpy到1.x稳定版:
# 降级numpy到1.x稳定版
pip install numpy==1.26.4
# 或升级scikit-learn到适配版本
pip install --upgrade scikit-learn

方案3:更换多标签数组构造方式

用np.column_stack()替代np.c_,该方法默认生成C连续数组:

y_multilabel = np.column_stack((y_train_large, y_train_odd))

内容的提问来源于stack exchange,提问作者ACX

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 13:43:23