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

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为更高版本,因此触发参数数量报错

修复方案

  1. 调整传参方式,给后两个参数加上关键字声明,同时注意你原代码中字典生成行末尾多余的逗号会导致返回结果变成元组,建议一并修改:
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
  1. 如需验证版本差异,可分别在两个环境执行以下代码查看scikit-learn版本:
import sklearn
print(sklearn.__version__)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 07:54:01