簡體   English   中英

TypeError 網格搜索

[英]TypeError grid search

我曾經創建循環來為我的模型尋找最佳參數,這增加了我的編碼錯誤,所以我決定使用GridSearchCV
我正在嘗試為我的模型找出 PCA 的最佳參數(我想要進行網格搜索的唯一參數)。
在這個模型中,在歸一化之后,我想將原始特征與 PCA 減少的特征結合起來,然后應用線性 SVM。
然后我保存整個模型來預測我的輸入。

我在嘗試擬合數據的行中出錯,因此我可以使用best_estimator_best_params_函數。
錯誤說: TypeError: The score function should be a callable, all (<type 'str'>) was passed. 我沒有使用任何可能需要在GridSearchCV提供字符串的GridSearchCV所以不知道為什么會出現此錯誤

我還想知道在保存我的模型之前print("shape after model",X.shape)print("shape after model",X.shape)是否應該基於所有可能的參數打印(150, 7) and (150, 5)

 from sklearn.pipeline import Pipeline, FeatureUnion from sklearn.model_selection import GridSearchCV from sklearn.svm import SVC from sklearn.datasets import load_iris from sklearn.decomposition import PCA from sklearn.feature_selection import SelectKBest from sklearn.preprocessing import StandardScaler from sklearn.externals import joblib from numpy import array iris = load_iris() X, y = iris.data, iris.target print(X.shape) #prints (150, 4) print (y) #cretae models and piplline them combined_features = FeatureUnion([("pca", PCA()), ("univ_select", SelectKBest(k='all'))]) svm = SVC(kernel="linear") pipeline = Pipeline([("scale", StandardScaler()),("features", combined_features), ("svm", svm)]) # Do grid search over n_components: param_grid = dict(features__pca__n_components=[1,3]) grid_search = GridSearchCV(pipeline, param_grid=param_grid, cv=5, verbose=10) grid_search.fit(X, y) print("best parameters", grid_search.best_params_) print("shape after model",X.shape) #should this print (150, 7) or (150, 5) based on best parameter? #save the model joblib.dump(grid_search.best_estimator_, 'model.pkl', compress = 1) #new data to predict Input=[ 2.9 , 4. ,1.2 ,0.2] Input= array(Input) #use the saved model to predict the new data modeltrain="model.pkl" modeltrain_saved = joblib.load(modeltrain) model_predictions = modeltrain_saved.predict(Input.reshape(1, -1)) print(model_predictions)

我根據答案更新了代碼

您在 SelectKBest 中提供'all'作為參數。 但是根據文檔,如果要傳遞“全部”,則需要將其指定為:

SelectKBest(k='all')

原因是它是一個關鍵字參數,應該用關鍵字指定。 因為 SelectKBest 的第一個參數是評分函數的位置參數。 因此,當您不指定param , 'all' 被視為函數的輸入,因此會產生錯誤。

更新:

現在關於形狀,原來的X不會改變。 所以它會打印(150,4) 數據將即時更改,在我的電腦上, best_param_n_components=1 ,因此進入 svm 的最終形狀是(150, 5) ,PCA 的 1 和 SelectKBest 的 4。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM