向RandomForestClassifier传入GridSearch最优参数字典时触发参数错误求助
解决RandomForestClassifier参数传入错误的问题
这个问题我之前也踩过坑,太典型了!你现在直接把params字典作为位置参数传给RandomForestClassifier,但这个类的第一个位置参数是n_estimators(默认值是100),Python会把整个字典当成n_estimators的取值,自然就会触发类型错误——毕竟字典可不是整数类型的参数值。
正确的传参方式:用字典解包运算符**
你只需要在params前面加上**,Python就会自动把字典里的键值对解析成对应的关键字参数传入模型,代码修改如下:
from sklearn.ensemble import RandomForestClassifier params = {'bootstrap': 'True', 'criterion': 'entropy', 'max_depth': 'None', 'max_features': '3', 'min_samples_leaf': '4', 'min_samples_split': '3'} # 关键是这里的**params clf = RandomForestClassifier(**params)
额外提醒:参数值的类型要匹配
另外还有个容易忽略的细节:你字典里的参数值都是字符串类型(比如'True'、'None'、'3'),但RandomForestClassifier的大部分参数需要布尔值、None或者整数类型。比如:
bootstrap应该是布尔值True,不是字符串'True'max_depth应该是None,不是字符串'None'max_features、min_samples_leaf这些应该是整数3、4,不是字符串'3'、'4'
如果这些参数是从GridSearch直接导出的,大概率是因为你在GridSearchCV的参数网格里用了字符串类型的取值。建议先把这些值转换成正确的类型,否则可能还是会出现隐性问题,处理代码示例:
# 转换参数类型为模型要求的格式 params_clean = { 'bootstrap': params['bootstrap'] == 'True', 'criterion': params['criterion'], 'max_depth': None if params['max_depth'] == 'None' else int(params['max_depth']), 'max_features': int(params['max_features']), 'min_samples_leaf': int(params['min_samples_leaf']), 'min_samples_split': int(params['min_samples_split']) } clf = RandomForestClassifier(**params_clean)
这样就能确保每个参数的类型都符合模型的要求啦!
内容的提问来源于stack exchange,提问作者Paul-Emile Moreau
相关产品推荐
相关产品推荐

