VS Code Python3.8 Keras分类中调用sklearn compute_class_weight传参报错问题
问题原因
核心原因是两个运行环境的scikit-learn版本不一致,不是VS Code本身的编译环境问题
- scikit-learn 1.1.0及以上版本调整了
compute_class_weight的传参规则:classes和y两个参数必须使用关键字参数传递,不再支持位置参数直接传入 - 你的Jupyter环境中安装的是1.1.0之前版本的scikit-learn,支持3个位置参数传入,所以运行正常;VS Code关联的Python环境中scikit-learn为更高版本,因此触发参数数量报错
修复方案
- 调整传参方式,给后两个参数加上关键字声明,同时注意你原代码中字典生成行末尾多余的逗号会导致返回结果变成元组,建议一并修改:
from sklearn.utils import compute_class_weight import numpy as np train_classes = train_generator.classes class_weights = compute_class_weight( "balanced", classes=np.unique(train_classes), y=train_classes ) # 移除末尾多余的逗号,避免class_weights被转为元组 class_weights = dict(zip(np.unique(train_classes), class_weights)) class_weights
- 如需验证版本差异,可分别在两个环境执行以下代码查看scikit-learn版本:
import sklearn print(sklearn.__version__)
内容的提问来源于stack exchange,提问作者PCG
相关产品推荐
相关产品推荐

