部署IPL比赛获胜概率预测模型时遇ColumnTransformer属性错误
解决Streamlit部署IPL获胜概率预测模型时的AttributeError问题
错误信息
AttributeError: 'ColumnTransformer' object has no attribute '_name_to_fitted_passthrough'
用户代码片段
ColumnTransformer 定义
from sklearn.compose import ColumnTransformer from sklearn.preprocessing import OneHotEncoder trf = ColumnTransformer([('trf',OneHotEncoder(sparse=False,drop='first'), ['batting_team','bowling_team','city'])],remainder='passthrough')
Pipeline 定义
pipe = Pipeline(steps=[ ('step1',trf), ('step2',LogisticRegression(solver='liblinear'))])
解决方法
- 统一scikit-learn版本:这个错误大多是训练模型的环境与Streamlit部署环境的scikit-learn版本不匹配导致的。
_name_to_fitted_passthrough是scikit-learn特定版本新增的属性,版本不一致会引发该报错。- 查看训练环境的scikit-learn版本:
pip show scikit-learn - 在部署环境安装完全相同的版本:
将命令中的pip install scikit-learn==x.x.xx.x.x替换为训练环境显示的版本号。
- 查看训练环境的scikit-learn版本:
- 规范模型的保存与加载:建议使用
joblib工具来保存和加载模型,避免版本兼容问题:
训练阶段保存模型:
Streamlit部署时加载模型:import joblib joblib.dump(pipe, 'ipl_win_predictor.pkl')import joblib pipe = joblib.load('ipl_win_predictor.pkl')
内容的提问来源于stack exchange,提问作者Jagadeesh Pangala
相关产品推荐
相关产品推荐

