赞
踩
import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn import ensemble from sklearn import metrics ############################################################################## # Load data data = pd.read_csv('Data for train_0.003D.csv') y = data.iloc[:,0] X = data.iloc[:,1:] offset = int(X.shape[0] * 0.9) X_train, y_train = X[:offset], y[:offset] X_test, y_test = X[offset:], y[offset:] ############################################################################## # Fit regression model params = {'n_estimators': 500, 'max_depth': 4, 'min_samples_split': 2, 'learning_rate': 0.01, 'loss': 'ls'} clf = ensemble.GradientBoostingRegressor(**params) clf.fit(X_train, y_train) y_pre = clf.predict(X_test) # Calculate metrics mse = metrics.mean_squared_error(y_test, y_pre) print("MSE: %.4f" % mse) mae = metrics.mean_absolute_error(y_test, y_pre) print("MAE: %.4f" % mae) R2 = metrics.r2_score(y_test,y_pre) print("R2: %.4f" % R2) ############################################################################## # Plot training deviance # compute test set deviance test_score = np.zeros((params['n_estimators'],), dtype=np.float64) for i, y_pred in enumerate(clf.staged_predict(X_test)): test_score[i] = clf.loss_(y_test, y_pred) plt.figure(figsize=(12, 6)) plt.subplot(1, 2, 1) plt.title('Deviance') plt.plot(np.arange(params['n_estimators']) + 1, clf.train_score_, 'b-', label='Training Set Deviance') plt.plot(np.arange(params['n_estimators']) + 1, test_score, 'r-', label='Test Set Deviance') plt.legend(loc='upper right') plt.xlabel('Boosting Iterations') plt.ylabel('Deviance') ############################################################################## # Plot feature importance feature_importance = clf.feature_importances_ # make importances relative to max importance feature_importance = 100.0 * (feature_importance / feature_importance.max()) sorted_idx = np.argsort(feature_importance) pos = np.arange(sorted_idx.shape[0]) + .5 plt.subplot(1, 2, 2) plt.barh(pos, feature_importance[sorted_idx], align='center') plt.yticks(pos, X.columns[sorted_idx]) plt.xlabel('Relative Importance') plt.title('Variable Importance') plt.show()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。