类型错误网格搜索

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 中提供字符串的参数,所以不确定为什么会出现此错误

我还想知道 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)

我根据答案更新了代码

您正在提供 'all' 作为 SelectKBest 中的参数。但是根据documentation,如果要传'all',需要指定为:

SelectKBest(k='all')

原因是它是关键字参数,应该用关键字指定。因为 SelectKBest 的第一个参数是评分函数的位置参数。因此,当您未指定 param 时,'all' 被视为函数的输入,因此会出现错误。

更新:

现在关于造型,原来的X就不改了。所以它会打印 (150,4)。数据将即时更改,在我的电脑上 best_param_n_components=1,因此进入 svm 的最终形状是 (150, 5),1 个来自 PCA,4 个来自 SelectKBest。