我使用 scikit-learn 定義了以下管道:
model_lg = Pipeline([("preprocessing", StandardScaler()), ("classifier", LogisticRegression())])
model_dt = Pipeline([("preprocessing", StandardScaler()), ("classifier", DecisionTreeClassifier())])
model_gb = Pipeline([("preprocessing", StandardScaler()), ("classifier", HistGradientBoostingClassifier())])
然后我使用交叉驗證來評估每個模型的性能:
cv_results_lg = cross_validate(model_lg, data, target, cv=5, return_train_score=True, return_estimator=True)
cv_results_dt = cross_validate(model_dt, data, target, cv=5, return_train_score=True, return_estimator=True)
cv_results_gb = cross_validate(model_gb, data, target, cv=5, return_train_score=True, return_estimator=True)
當我嘗試使用該coef_方法檢查每個模型的特征重要性時,它給了我一個歸因錯誤:
model_lg.steps[1][1].coef_
AttributeError: 'LogisticRegression' object has no attribute 'coef_'
model_dt.steps[1][1].coef_
AttributeError: 'DecisionTreeClassifier' object has no attribute 'coef_'
model_gb.steps[1][1].coef_
AttributeError: 'HistGradientBoostingClassifier' object has no attribute 'coef_'
我想知道,我該如何解決這個錯誤?還是有任何其他方法來檢查每個模型中的特征重要性?
uj5u.com熱心網友回復:
Imo,這里的重點如下。一方面,管道實體model_lg等model_dt沒有明確安裝(您沒有.fit()直接在它們上呼叫方法),這會阻止您嘗試訪問coef_實體本身的屬性。
另一方面,通過.cross_validate()使用引數呼叫return_estimator=True(.cross_validate()僅在交叉驗證方法中可能),您可以為每個 cv 拆分獲取擬合的估計器cv_results_lg,但您應該通過您的字典等訪問它們cv_results_dt(在'estimator'密鑰上) . 這是代碼中的參考,這是一個示例:
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.datasets import load_iris
from sklearn.model_selection import cross_validate
X, y = load_iris(return_X_y=True)
model_lg = Pipeline([("preprocessing", StandardScaler()), ("classifier", LogisticRegression())])
cv_results_lg = cross_validate(model_lg, X, y, cv=5, return_train_score=True, return_estimator=True)
例如,這些將是在第一次折疊時計算的結果。
cv_results_lg['estimator'][0].named_steps['classifier'].coef_
有關相關主題的有用見解可在以下位置找到:
- 如何獲得多標簽分類問題的特征重要性?
- 在 Python 3 中使用 Pipeline 獲取 RFE 的支持和排名屬性
uj5u.com熱心網友回復:
在某些演算法和列印精度中進行回圈
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/456586.html
上一篇:如何通過回圈獲得混淆矩陣值?
