我试图使用遗传算法通过TPOT来优化随机森林的超参数。我遇到了一个错误,并且不太确定如何解决。以下是我使用的主要代码。
from sklearn.ensemble import RandomForestClassifierfrom sklearn.model_selection import RandomizedSearchCVfrom sklearn.model_selection import train_test_splitfrom tpot import TPOTClassifierX = my_df_featuresy = my_df_targetX_train, X_test, y_train, y_test = train_test_split(X,y, random_state=42)model_parameters = {'n_estimators': [100,200], "max_depth" : [None, 5, 10], "max_features" : [10]} # 当我运行这段代码时,它似乎运行得很好# model_tuned = GridSearchCV(RandomForestClassifier(),model_parameters, cv=5)# 但这似乎不起作用 model_tuned = TPOTClassifier(generations= 2, population_size= 2, offspring_size= 2, verbosity= 2, early_stop= 10, config_dict= {'sklearn.ensemble.RandomForestClassifier': model_parameters}, cv = 5) model_tuned.fit(X_train,y_train)
当使用TPOT(而不是RandomForest)时,上面的最后一行会产生以下错误:
ValueError: cannot set using a slice indexer with a different length than the value"
回答:
我尝试使用iris数据集运行TPOT,没有出现任何错误
from sklearn.ensemble import RandomForestClassifierfrom sklearn.model_selection import RandomizedSearchCVfrom sklearn.model_selection import train_test_splitfrom tpot import TPOTClassifierfrom sklearn import datasetsiris = datasets.load_iris()X = iris.data y = iris.targetX_train, X_test, y_train, y_test = train_test_split(X,y, random_state=42)model_parameters = {'n_estimators': [100,200], "max_depth" : [None, 5, 10], "max_features" : [len(X_train[0])]} model_tuned = TPOTClassifier(generations= 2, population_size= 2, offspring_size= 2, verbosity= 2, early_stop= 10, config_dict={'sklearn.ensemble.RandomForestClassifier': model_parameters}, cv = 5) model_tuned.fit(X_train,y_train)
我认为你的数据集的形状或类型可能有问题
可能是由于你使用了pandas DataFrame
尝试这样做:
X = X.to_numpyy = y.to_numpy