本示例演示了模型复杂性是如何影响预测精度和计算性能的。数据集是用于回归(或者分类)的波士顿住房(Boston Housing)数据集(或者20 Newsgroups)。对于每一类模型,我们通过选择相关的模型参数来改变模型的复杂度,并测量对计算性能(延迟)和预测能力(MSE或Hamming损失)的影响。

输出:

Benchmarking SGDClassifier(alpha=0.001, l1_ratio=0.25, loss='modified_huber',              penalty='elasticnet')Complexity: 4466 | Hamming Loss (Misclassification Ratio): 0.2491 | Pred. Time: 0.020835sBenchmarking SGDClassifier(alpha=0.001, l1_ratio=0.5, loss='modified_huber',              penalty='elasticnet')Complexity: 1663 | Hamming Loss (Misclassification Ratio): 0.2915 | Pred. Time: 0.015789sBenchmarking SGDClassifier(alpha=0.001, l1_ratio=0.75, loss='modified_huber',              penalty='elasticnet')Complexity: 880 | Hamming Loss (Misclassification Ratio): 0.3180 | Pred. Time: 0.013469sBenchmarking SGDClassifier(alpha=0.001, l1_ratio=0.9, loss='modified_huber',              penalty='elasticnet')Complexity: 639 | Hamming Loss (Misclassification Ratio): 0.3337 | Pred. Time: 0.011812sBenchmarking NuSVR(C=1000.0, gamma=3.0517578125e-05, nu=0.1)Complexity: 69 | MSE: 31.8139 | Pred. Time: 0.000301sBenchmarking NuSVR(C=1000.0, gamma=3.0517578125e-05, nu=0.25)Complexity: 136 | MSE: 25.6140 | Pred. Time: 0.000811sBenchmarking NuSVR(C=1000.0, gamma=3.0517578125e-05)Complexity: 244 | MSE: 22.3375 | Pred. Time: 0.000895sBenchmarking NuSVR(C=1000.0, gamma=3.0517578125e-05, nu=0.75)Complexity: 351 | MSE: 21.3688 | Pred. Time: 0.001237sBenchmarking NuSVR(C=1000.0, gamma=3.0517578125e-05, nu=0.9)Complexity: 404 | MSE: 21.1033 | Pred. Time: 0.001460sBenchmarking GradientBoostingRegressor(n_estimators=10)Complexity: 10 | MSE: 29.0148 | Pred. Time: 0.000120sBenchmarking GradientBoostingRegressor(n_estimators=50)Complexity: 50 | MSE: 8.6545 | Pred. Time: 0.000302sBenchmarking GradientBoostingRegressor()Complexity: 100 | MSE: 7.7179 | Pred. Time: 0.000264sBenchmarking GradientBoostingRegressor(n_estimators=200)Complexity: 200 | MSE: 6.7507 | Pred. Time: 0.000425sBenchmarking GradientBoostingRegressor(n_estimators=500)Complexity: 500 | MSE: 7.1471 | Pred. Time: 0.000922s
print(__doc__)# 作者: Eustache Diemert # 许可证: BSD 3 clauseimport timeimport numpy as npimport matplotlib.pyplot as pltfrom mpl_toolkits.axes_grid1.parasite_axes import host_subplotfrom mpl_toolkits.axisartist.axislines import Axesfrom scipy.sparse.csr import csr_matrixfrom sklearn import datasetsfrom sklearn.utils import shufflefrom sklearn.metrics import mean_squared_errorfrom sklearn.svm import NuSVRfrom sklearn.ensemble import GradientBoostingRegressorfrom sklearn.linear_model import SGDClassifierfrom sklearn.metrics import hamming_loss# ############################################################################## 例程(Routines)# 初始化随机生成器np.random.seed(0)def generate_data(case, sparse=False):"""生成回归/分类数据。"""if case == 'regression':        X, y = datasets.load_boston(return_X_y=True)elif case == 'classification':        X, y = datasets.fetch_20newsgroups_vectorized(subset='all',                                                      return_X_y=True)    X, y = shuffle(X, y)    offset = int(X.shape[0] * 0.8)    X_train, y_train = X[:offset], y[:offset]    X_test, y_test = X[offset:], y[offset:]if sparse:        X_train = csr_matrix(X_train)        X_test = csr_matrix(X_test)else:        X_train = np.array(X_train)        X_test = np.array(X_test)    y_test = np.array(y_test)    y_train = np.array(y_train)    data = {'X_train': X_train, 'X_test': X_test, 'y_train': y_train,'y_test': y_test}return datadef benchmark_influence(conf):"""    changing_param:对MSE和延迟的基准影响    """    prediction_times = []    prediction_powers = []    complexities = []for param_value in conf['changing_param_values']:        conf['tuned_params'][conf['changing_param']] = param_value        estimator = conf['estimator'](**conf['tuned_params'])print("Benchmarking %s" % estimator)        estimator.fit(conf['data']['X_train'], conf['data']['y_train'])        conf['postfit_hook'](estimator)        complexity = conf['complexity_computer'](estimator)        complexities.append(complexity)        start_time = time.time()for _ in range(conf['n_samples']):            y_pred = estimator.predict(conf['data']['X_test'])        elapsed_time = (time.time() - start_time) / float(conf['n_samples'])        prediction_times.append(elapsed_time)        pred_score = conf['prediction_performance_computer'](            conf['data']['y_test'], y_pred)        prediction_powers.append(pred_score)print("Complexity: %d | %s: %.4f | Pred. Time: %fs\n" % (            complexity, conf['prediction_performance_label'], pred_score,            elapsed_time))return prediction_powers, prediction_times, complexitiesdef plot_influence(conf, mse_values, prediction_times, complexities):"""    绘制模型复杂性对准确度和延迟的影响。    """    plt.figure(figsize=(12, 6))    host = host_subplot(111, axes_class=Axes)    plt.subplots_adjust(right=0.75)    par1 = host.twinx()    host.set_xlabel('Model Complexity (%s)' % conf['complexity_label'])    y1_label = conf['prediction_performance_label']    y2_label = "Time (s)"    host.set_ylabel(y1_label)    par1.set_ylabel(y2_label)    p1, = host.plot(complexities, mse_values, 'b-', label="prediction error")    p2, = par1.plot(complexities, prediction_times, 'r-',                    label="latency")    host.legend(loc='upper right')    host.axis["left"].label.set_color(p1.get_color())    par1.axis["right"].label.set_color(p2.get_color())    plt.title('Influence of Model Complexity - %s' % conf['estimator'].__name__)    plt.show()def _count_nonzero_coefficients(estimator):    a = estimator.coef_.toarray()return np.count_nonzero(a)# ############################################################################## 主要代码regression_data = generate_data('regression')classification_data = generate_data('classification', sparse=True)configurations = [    {'estimator': SGDClassifier,'tuned_params': {'penalty': 'elasticnet', 'alpha': 0.001, 'loss':'modified_huber', 'fit_intercept': True, 'tol': 1e-3},'changing_param': 'l1_ratio','changing_param_values': [0.25, 0.5, 0.75, 0.9],'complexity_label': 'non_zero coefficients','complexity_computer': _count_nonzero_coefficients,'prediction_performance_computer': hamming_loss,'prediction_performance_label': 'Hamming Loss (Misclassification Ratio)','postfit_hook': lambda x: x.sparsify(),'data': classification_data,'n_samples': 30},    {'estimator': NuSVR,'tuned_params': {'C': 1e3, 'gamma': 2 ** -15},'changing_param': 'nu','changing_param_values': [0.1, 0.25, 0.5, 0.75, 0.9],'complexity_label': 'n_support_vectors','complexity_computer': lambda x: len(x.support_vectors_),'data': regression_data,'postfit_hook': lambda x: x,'prediction_performance_computer': mean_squared_error,'prediction_performance_label': 'MSE','n_samples': 30},    {'estimator': GradientBoostingRegressor,'tuned_params': {'loss': 'ls'},'changing_param': 'n_estimators','changing_param_values': [10, 50, 100, 200, 500],'complexity_label': 'n_trees','complexity_computer': lambda x: x.n_estimators,'data': regression_data,'postfit_hook': lambda x: x,'prediction_performance_computer': mean_squared_error,'prediction_performance_label': 'MSE','n_samples': 30},]for conf in configurations:    prediction_performances, prediction_times, complexities = \        benchmark_influence(conf)    plot_influence(conf, prediction_performances, prediction_times,                   complexities)

脚本的总运行时间: ( 0 分 20.261 秒)估计的内存使用量: 60 MB下载python源代码:plot_model_complexity_influence.py下载Jupyter notebook源代码:plot_model_complexity_influence.ipynb由Sphinx-Gallery生成的画廊☆☆☆为方便大家查阅,小编已将scikit-learn学习路线专栏文章统一整理到公众号底部菜单栏,同步更新中,关注公众号,点击左下方“系列文章”,如图:欢迎大家和我一起沿着scikit-learn文档这条路线,一起巩固机器学习算法基础。(添加微信:mthler,备注:sklearn学习,一起进【sklearn机器学习进步群】开启打怪升级的学习之旅。)

sklearn实现lda模型_使用python+sklearn实现模型复杂性的影响相关推荐

  1. python knn模型_使用Python训练KNN模型并进行分类

    K临近分类算法是数据挖掘中较为简单的一种分类方法,通过计算不同数据点间的距离对数据进行分类,并对新的数据进行分类预测.我们在之前的文章<K邻近(KNN)分类和预测算法的原理及实现>和< ...

  2. python数据分析天气预报论文_用python+sklearn(机器学习)实现天气预报数据 模型和使用...

    项目地址 系列教程 0.前言 在上一篇教程里我们已经获取了所需要的全部数据,包括训练数据集和测试数据集,使用ProcessData()调用,所以接下来写模型的建立和预测 1.建立模型 没段代码在文章后 ...

  3. python one hot编码_对python sklearn one-hot编码详解

    one-hot编码的作用 使用one-hot编码,将离散特征的取值扩展到了欧式空间,离散特征的某个取值就对应欧式空间的某个点 将离散特征通过one-hot编码映射到欧式空间,是因为,在回归,分类,聚类 ...

  4. python做var模型_【Python金融量化】VaR系列(五):Copula模型估计组合VaR-阿里云开发者社区...

    1. 资产组合VaR建模方法回顾 文章中总结了通过DCC模型估计组合向前一日VaR的方法,整体思路如下: ●  通过Garch族模型估计各资产的波动率 ●  通过DCC模型估计各资产间的相关系数,结合 ...

  5. python模型训练框架_以Python撰写 AI模型框架

    以Python撰写 AI模型框架 by 高焕堂 1. 前言: 在AI(人工智慧)方面,由于当今的机器学习本质是一种<大数据相关性支撑的>归纳性推理.软体框架的复用(Reuse)性愈高,对于 ...

  6. python给用户打标签_用Python实现RFM模型——互联网产品用户分层必备技巧

    1.前言 RFM模型即"R"--Recency(最近一次消费时间)."F"--Frequency(一段时间内消费频次)."M"--(一段时间 ...

  7. python做var模型_【Python金融量化】VaR系列(五):Copula模型估计组合VaR

    作者:量化小白H     Python爱好者社区专栏作者 个人公众号:量化小白上分记 前文传送门: 之前总结的大部分模型都是基于正态性的假设,但实际上,正态性假设并不非常符合金融时间序列的特征.如果从 ...

  8. python绘制太阳系模型_用python做一个漂亮的太阳系运动模拟

    贴一张静态图 太阳系现在只有8大行星,连太阳一起,一共是9张图片.如果没有的朋友,可以到文末的下载地址下载. def openSolor(solar): def loadImg(name): str1 ...

  9. python绘制太阳系模型_画一个太阳系的模型

    1 .画一个太阳系的模型? 2 .地球公转对地球有什么影响? 3 .摆在摆钟里是怎样工作的?摆在摆钟里起到了什么作用?人们为什么会选择摆作为摆钟 的控制核心?摆的快慢与那些因素有关? 4 . Xx 家 ...

最新文章

  1. NC:应对干旱 细菌崩了 真菌依然很稳(纯网络分析发Nature子刊)
  2. Java嵌套类(Nested Classes)总结
  3. python 正则表达式 re findall 返回能匹配的字符串
  4. c语言 文件f指针,C语言文件选择题
  5. 用Rocker制作模板
  6. pb预览状态下的pagecount_QuickLook高效文件预览神器,方便到令你意想不到
  7. Notepad++ 配置java编译环境
  8. 2020 各大厂分享ppt
  9. 汇编语言数据段查找ASCII码并回显
  10. python实现判断一个字符串是否是合法IP地址
  11. 关于DM8168中移植算法速度慢、效率低的新发现
  12. 关于“无法从传输连接中读取数据: 尝试读取或写入受保护的内存。这通常指示其他内存已损坏。”错误的解决方法之一
  13. win环境sftp软件_在Windows上使用sftp工具—WinSCP
  14. 今天分享一下做支付宝小程序遇到的坑。ISV权限不足,建议在开发者中心检查对应功能是否已经添加。验签出错,建议检查签名字符串或签名私钥与应用公钥是否匹配
  15. react-native Android使用阿里icon font图标
  16. yarn下载报错There appears to be trouble with your network connection. Retrying.
  17. 趣味点名软件_网传川大教授用刷脸软件点名 无人逃课
  18. 10款开发常用的代码编辑器
  19. 树莓派安装mplayer,并使用命令查看摄像头
  20. 【Android】【自动填充】自定义AutofillService(二):编写AutofillService代码

热门文章

  1. 20221218解决在Ubuntu18.04下编译Firefly的Core-3588J出现lz4的问题
  2. pandas 转换为文本类型_将文本文件转换为pandas datafram
  3. alertdialog怎么水平排列_网图骗人?别墅挂画怎么挂都不好看?答案在这里
  4. Unreal动画导入导出
  5. 将图片直接转换成xml文件_如何将jpg在线转换成pdf?jpg图片可以转换成pdf吗?
  6. Python爬虫笔记——多线程(threading)传参
  7. 面试官让我滚,我用了20分钟,狠狠装了一回逼!
  8. 服务器系统重装后anaconda3安装以及环境配置
  9. 嵌入式计算机系统设计第五次实验报告
  10. 2023 电脑PC 联想电脑风扇控制器软件工具