我正在尝试对随机森林分类器进行网格搜索,测试不同的PCA成分和估计器数量(n_estimators)。
model_rf = RandomForestClassifier() pca_rf = Pipeline([('pca', PCA()), ('rf', RandomForestClassifier())]) param_grid_rf = [{ 'pca__n_components': [20], 'rf__n_estimators': [5] }] grid_cv_rf = GridSearchCV(estimator=pca_rf, cv=5,param_grid=param_grid_rf) grid_cv_rf.fit(x_train, y_train1) test_pca_evaluate = pca.transform(x_test) y_pred = model_rf.predict(test_pca_evaluate)#error here
在最后一行我得到了一个错误 “这个 RandomForestClassifier 实例尚未拟合。请在使用此方法之前调用 ‘fit’ 并传入合适的参数。”
回答:
这个错误非常明确 – 你正在调用的 RandomForestClassifier
方法尚未被拟合,意味着你还没有调用 model_rf.fit
。这个对象并没有被你的 grid_cv_rf
对象拟合。
我想你想要的是 grid_cv_rf.predict(x_test)
,因为那个 grid_cv_rf
对象同时完成了你的 PCA 和 RF 的拟合工作。