好的,所以我想在我的数据集上运行具有 X 个特征的递归特征提取,并在每次迭代中删除排名最低的特征,而不是重新运行 RFE,直到我只剩下 5 个特征。但是,我不知道如何编码。
运行 RFE 的第一部分很好,但我不想坐下来手动重新运行 RFE 并一次删除一个功能,这将花费很长时间。有人可以帮我编码吗?
import matplotlib.pyplot as plt
from sklearn.model_selection import cross_val_score
from sklearn.metrics import accuracy_score
from sklearn.ensemble import RandomForestClassifier
from sklearn.feature_selection import RFE
from sklearn.datasets import make_friedman1
X, y = make_friedman1(n_samples=2000, n_features=85, random_state=42)
# split data into train and test split
from sklearn.model_selection import train_test_split
# if we need train test split
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3,random_state=42)
estimator = RandomForestClassifier(n_estimators=500, min_samples_leaf=5,
min_samples_split=8, max_features='auto',
max_depth=90, bootstrap=True)
selector = RFE(estimator, 83, step=1)
selector = selector.fit(X_train, y_train)
# predict and get rankings and optimal number of features
selector.fit(X_test, y_test)
selector.predict(X_test)
ranking = selector.ranking_
y_hats = selector.predict(X_test)
predictions = [round(value) for value in y_hats]
accuracy = accuracy_score(y_test, predictions)
print("Test Accuracy: %.2f%%" % (accuracy*100.0))
# index rankings
header = X_test.columns
frame = pd.DataFrame(ranking, index=header)
frame = frame.rename(columns = {frame.columns[0]: 'rankings'}, inplace = False)
frame = frame.sort_values(by = 'rankings', ascending=True)
# save table
from pandas.tools.plotting import table
ax = plt.subplot(111, frame_on=True) # no visible frame
ax.xaxis.set_visible(False) # hide the x axis
ax.yaxis.set_visible(False) # hide the y axis
table(ax, frame) # where df is your data frame