show the code:

# Plot training deviance
def plot_training_deviance(clf, n_estimators, X_test, y_test):
# compute test set deviance
test_score = np.zeros((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')
train_score = clf.train_score_
logging.info("len(train_score): %s" % len(train_score))
logging.info(train_score)
logging.info("len(test_score): %s" % len(test_score))
logging.info(test_score)
plt.plot(np.arange(n_estimators) + 1, train_score, 'b-',
label='Training Set Deviance')
plt.plot(np.arange(n_estimators) + 1, test_score, 'r*', label='Test Set Deviance')
plt.legend(loc='upper right')
plt.xlabel('Boosting Iterations')
plt.ylabel('Deviance')
plt.show() # Plot feature importance
def plot_feature_importance(clf, feature_names):
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, feature_names[sorted_idx])
plt.yticks(pos, [feature_names[idx] for idx in sorted_idx])
plt.xlabel('Relative Importance')
plt.title('Variable Importance')
plt.show() class Train(object):
def __init__(self, data_file):
self.data_file = data_file
self.x_fields = ["xxx", "xxx", "xxx"]
self.x_features, self.y_labels = self.load_data() def load_data(self):
x_features, y_labels = [], []
# ......
return x_features, y_labels def train_model(self):
model = GradientBoostingRegressor(random_state=42)
model.fit(self.x_features, self.y_labels)
y_pred = model.predict(self.x_features)
logging.info("mean_squared_error: %.6f" % mean_squared_error(self.y_labels, y_pred))
logging.info("mean_squared_log_error: %.6f" % mean_squared_log_error(self.y_labels, y_pred)) plot_training_deviance(clf=model, n_estimators=model.get_params()["n_estimators"], X_test=self.x_features, y_test=self.y_labels) # 输出feature重要性
logging.info("feature_importances_: %s" % model.feature_importances_)
plot_feature_importance(clf=model, feature_names=self.x_fields)

参考的是sklearn中的样例: Gradient Boosting regression — scikit-learn 0.19.2 documentation

画出的图如下所示:

sklearn 可视化模型的训练测试收敛情况和特征重要性的更多相关文章

  1. 【集成学习】sklearn中xgboost模块中plot_importance函数(绘图--特征重要性)

    直接上代码,简单 # -*- coding: utf-8 -*- """ ################################################ ...

  2. 使用 TensorBoard 可视化模型、数据和训练

    使用 TensorBoard 可视化模型.数据和训练 在 60 Minutes Blitz 中,我们展示了如何加载数据,并把数据送到我们继承 nn.Module 类的模型,在训练数据上训练模型,并在测 ...

  3. sklearn——train_test_split 随机划分训练集和测试集

    sklearn——train_test_split 随机划分训练集和测试集 sklearn.model_selection.train_test_split随机划分训练集和测试集 官网文档:http: ...

  4. 机器学习使用sklearn进行模型训练、预测和评价

    cross_val_score(model_name, x_samples, y_labels, cv=k) 作用:验证某个模型在某个训练集上的稳定性,输出k个预测精度. K折交叉验证(k-fold) ...

  5. pytorch seq2seq模型训练测试

    num_sequence.py """ 数字序列化方法 """ class NumSequence: """ ...

  6. 学习笔记TF016:CNN实现、数据集、TFRecord、加载图像、模型、训练、调试

    AlexNet(Alex Krizhevsky,ILSVRC2012冠军)适合做图像分类.层自左向右.自上向下读取,关联层分为一组,高度.宽度减小,深度增加.深度增加减少网络计算量. 训练模型数据集 ...

  7. Python 3 利用 Dlib 19.7 和 sklearn机器学习模型 实现人脸微笑检测

    0.引言  利用机器学习的方法训练微笑检测模型,给一张人脸照片,判断是否微笑:   使用的数据集中69张没笑脸,65张有笑脸,训练结果识别精度在95%附近: 效果: 图1 示例效果 工程利用pytho ...

  8. sklearn保存模型的两种方式

    sklearn 中模型保存的两种方法   一. sklearn中提供了高效的模型持久化模块joblib,将模型保存至硬盘. from sklearn.externals import joblib # ...

  9. sklearn保存模型-【老鱼学sklearn】

    训练好了一个Model 以后总需要保存和再次预测, 所以保存和读取我们的sklearn model也是同样重要的一步. 比如,我们根据房源样本数据训练了一下房价模型,当用户输入自己的房子后,我们就需要 ...

随机推荐

  1. django基础之Ajax、分页、cookie与session

    目录: Ajax之json Ajax简介 jquery实现的ajax js实现的ajax django分页器 COOKIE与SESSION 一.Ajax之json 1.什么是json? 定义: JSO ...

  2. Spark Shuffle调优原理和最佳实践

    对性能消耗的原理详解 在分布式系统中,数据分布在不同的节点上,每一个节点计算一部份数据,如果不对各个节点上独立的部份进行汇聚的话,我们计算不到最终的结果.我们需要利用分布式来发挥Spark本身并行计算 ...

  3. [py]python中的==和is的区别

    is比较id id(a) == id(b) == id(c) a is d #false ==比较值 a==b #true 举个例子:a = 1 b = a c = 1 d = 1.0 这里有3个对象 ...

  4. cordic算法的verilog实现及modelsim仿真

    1. 算法介绍 CORDIC(Coordinate Rotation Digital Computer)算法即坐标旋转数字计算方法,是J.D.Volder1于1959年首次提出,主要用于三角函数.双曲 ...

  5. Python:数字的格式化输出

    >>> 'The value is {:0,.2f}'.format(x) 'The value is 1,234.57' 需要将数字格式化后输出,并控制数字的位数.对齐.千位分隔符 ...

  6. css 文档流中块级非替换元素水平区域的计算规则(1)

    最近在读<Basic Visual Formatting in CSS>,结合以前看的<css权威指南>和css标准.今天就做个笔记. 以前在遇到一些宽度不明确指明的一些布局的 ...

  7. 前端面试题之 sum(2)(3) (链式调用,toString,柯里化,数组操作)

    写一个函数让下面两个输出结果相同:console.log(sum(2)(3));console.log(sum(2,3)); var sum = (function() { var list = [] ...

  8. P1136 迎接仪式

    P1136 迎接仪式 $O(n^{2}k)$:$f[i][k]$表示到第$i$个字符为止,交换$k$次,得到的最多子串数 那么枚举位置$j$,状态可以从$f[j][k-1]+1$转移过来 $O(nk^ ...

  9. presto-cli通过hive查询hdfs

    1.  启动hive metastore 2. 启动hive thrift接口 参考:http://www.cnblogs.com/kisf/p/7497261.html 3. 下载presto se ...

  10. 20145326 《Java程序设计》第7周学习总结

    20145326 <Java程序设计>第7周学习总结 教材学习内容总结 第十二章 一.认识Lambda语法 1.Lambda语法概览 Arrays的sort()方法可以用来排序,只不过你要 ...