В моем процессе я обработал числовые данные c и категориальные переменные моих данных по следующему конвейеру:
from sklearn.base import BaseEstimator, TransformerMixin
class DataFrameSelector(BaseEstimator, TransformerMixin):
def __init__(self, attribute_names):
self.attribute_names=attribute_names
def fit(self, X, y=None):
return self
def transform(self, X):
return X[self.attribute_names].values
from sklearn.preprocessing import OneHotEncoder
from sklearn.pipeline import Pipeline
num_pipeline = Pipeline([
("select_numeric", DataFrameSelector(["LIMIT_BAL", "AGE", "PAY_1", "PAY_2", "PAY_3", "PAY_4", "PAY_5", "PAY_6",
"BILL_AMT1", "BILL_AMT2", "BILL_AMT3", "BILL_AMT4", "BILL_AMT5", "BILL_AMT6",
"PAY_AMT1", "PAY_AMT2", "PAY_AMT3", "PAY_AMT4", "PAY_AMT5", "PAY_AMT6"])),
])
cat_pipeline = Pipeline([
("select_cat", DataFrameSelector(["SEX", "EDUCATION", "MARRIAGE"])),
("cat_encoder", OneHotEncoder(handle_unknown='ignore')),
])
from sklearn.pipeline import FeatureUnion
preprocess_pipeline = FeatureUnion(transformer_list=[
("num_pipeline", num_pipeline),
("cat_pipeline", cat_pipeline),
])
credit = X_train.copy()
credit_prepared = preprocess_pipeline.fit_transform(credit)
Однако после этого мои обучающие данные будут credit_prepared, и они не будут иметь имена столбцов больше. После того как я использовал randomsearchCV, чтобы превратить случайный лес в эти данные, я захотел создать график важности объектов. Тем не менее, как я могу вернуть имя объекта и построить его? Ниже описан процесс, который я использовал для создания графика:
from sklearn.model_selection import RandomizedSearchCV
from scipy.stats import randint
# set parameter range
param_distribs = {
'n_estimators': randint(low=1, high=200),
'max_features': randint(low=1, high=8),
}
rf_clf = RandomForestClassifier(random_state=42, n_jobs=-1)
rnd_search_RF = RandomizedSearchCV(rf_clf, param_distributions=param_distribs,
n_iter=10, cv=5, scoring='roc_auc', random_state=42)
rnd_search_RF.fit(credit_prepared, y_train)
# plot feature importance
features = X_train.columns #this is wrong...
importances = best_rf.feature_importances_
indices = np.argsort(importances)
plt.title('Feature Importances')
plt.barh(range(len(indices)), importances[indices], color='b', align='center')
plt.yticks(range(len(indices)), [features[i] for i in indices])
plt.xlabel('Relative Importance')
plt.show()