我试图使用 UCI 机器学习鸢尾花数据集生成鸢尾花物种的预测。我使用了 RandomForestClassifier 和 GridSearchCV 并计算了平均绝对误差。然而,在使用测试集生成预测时,它给了我一个可疑的 MAE 0.000000,得分为 1.0。模型是否可能过拟合?如果是这样,为什么会发生这种情况,我该如何防止这种情况发生?
iris = pd.read_csv('/iris/Iris.csv')
le = LabelEncoder()
i2 = iris.copy()
labelled_iris_df = pd.DataFrame(le.fit_transform(i2.Species)).rename(columns={0:'Species_Encoded'})
i3 = i2.drop('Species', axis=1)
i3 = pd.concat([i3, labelled_iris_df], axis=1) #Encoded dataset
y = i3.Species_Encoded
X = i3.drop('Species_Encoded', axis=1)
X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.75, random_state=42)
params = {
'n_estimators':[50,100,150,200],
'max_depth':[3,4,5,6]
}
rfc = RandomForestClassifier(random_state=42)
gc = GridSearchCV(rfc, params, cv=3).fit(X,y)
print (gc.best_params_) #n_estimators: 50, max_depth:4
model = RandomForestClassifier(n_estimators=50, max_depth=4, random_state=42)
model.fit(X_train,y_train)
preds = model.predict(X_test)
mae = mean_absolute_error(y_test, preds)
sc = model.score(X_test, y_test)
print("mae: %f \t\t score: %f" % (mae, sc)) #Prints mae: 0.000000 score: 1.0
我是机器学习的初学者,因此请随时评论此代码的不良部分以及如何改进它们。