数学推导+纯Python实现机器学习算法:GBDT

2.28 GBDT算法原理详解:梯度提升决策树,从数学推导到代码实现 GBDT原理:串行训练,逐步修正误差数学基础:梯度下降,残差拟合实现方式:从零实现和使用sklearn优势:强大的预测能力,广泛应用。 阅读详情

Datawhale推荐

作者:louwill,Machine Learning Lab

时隔大半年,机器学习算法推导系列终于有时间继续更新了。在之前的14讲中,笔者将监督模型中主要的单模型算法基本都过了一遍。预计在接下来的10讲中,笔者将努力更新完以GBDT代表的集成学习模型,以EM算法、CRF和隐马为代表的概率图模型以及以聚类降维为代表的无监督学习算法。

在系列第4和第5讲,笔者集中对ID3和CART决策树算法进行了阐述,并给出二者算法的一些初步实现。本节我们来看集成学习的核心模型GBDT(Gradient Boosting Decision Tree),即梯度提升决策树,这也是一种决策树模型算法。GBDT近年来在一些数据竞赛上大杀四方,并不断衍生出像XGBoost和LightGBM等更强大的版本。从名字上看,GBDT是由决策树、提升模型和梯度下降一起构成的。所以,要搞清楚GBDT的基本原理,就必须对这三者及其相互作用有一个深入的理解。

GBDT基本原理

决策树的基本原理我们已经很清楚了,就是依据信息增益等原则不断选择特征构建树模型的过程,具体可参考数学推导+纯Python实现机器学习算法5:决策树之CART算法。Boosting则是一种集成学习模式,通过将多个单个决策树(弱学习器)进行线性组合构成一个强学习器的过程,Boosting以一个单模型作为作为弱分类器,GBDT中使用CART作为这种弱学习器(基模型)。而融入了梯度下降对Boosting树模型进行优化之后就有了梯度提升树模型。

我们先来用一个通俗的说法来理解GBDT。假设某位同学月薪10k,笔者先用一个树模型拟合了6k,发现有4k的损失,然后再用一棵树模型拟合了2k,这样持续拟合下去,拟合值和目标值之间的残差会越来越小,而我们将每一轮迭代,也就是每一棵树的预测值加起来就是模型最终的预测结果。不停的使用单棵决策树组合就是Boosting的过程,使用梯度下降对Boosting树模型进行优化的过程就是Gradient Boosting。

下面我们用数学语言来描述GBDT。

一个提升树模型可以描述为:

在给定初始模型的情况下,第m步的模型可以表示为:

然后我们通过如下目标函数来优化下一棵树的参数:

以回归问题的提升树为例展开,一棵回归树可表示为:


第0步、第m步和最终模型可表示为:

给定第m-1步的模型下,求解:


当损失函数为平方损失时:


相应的损失可推导为:


则有:


说明提升树模型每一次迭代是在拟合一个残差函数。

但实际工作中并不是每一个损失函数都如平方损失那样容易优化,所以有学者就提出近似梯度下降的方法来使用损失函数的负梯度在当前模型的值作为回归提升树中残差的近似值,即:


所以,综合提升树和梯度提升,GBDT模型算法的一般流程可归纳为:

(1) 初始化弱学习器:

(2) 对有:

  • 对每个样本,计算负梯度,即残差

  • 将上步得到的残差作为样本新的真实值,并将数据作为下棵树的训练数据,得到一颗新的回归树其对应的叶子节点区域为。其中为回归树t的叶子节点的个数。

  • 对叶子区域计算最佳拟合值

  • 更新强学习器

(3) 得到最终学习器

GBDT代码框架

手动从头开始写一个GBDT模型并非易事,需要我们对GBDT模型算法细节都有足够深入的理解。在动手写代码之前,我们需要梳理清楚代码框架,一个完整的GBDT系统应包括如下几个方面,如图所示。

GBDT的基模型为CART,所以定义决策树结点和构建CART树至关重要,CART算法笔者系列第5讲已经进行了初步实现。当基模型构建好后,即可根据GBDT算法流程搭建GBDT和GBRT。除此之外,一些辅助函数的定义(最大熵/Gini指数计算),损失函数定义和模型可视化方法等辅助功能也应该一应俱全。

因树结点和CART树模型第5讲已讲过,具体实现方法这里不再重写。

结点定义代码框架:

class TreeNode():
    def __init__(self, feature_i=None, threshold=None,
                 value=None, true_branch=None, false_branch=None):
         pass

树定义代码框架,主要包括树的基本属性和方法。基本属性包括根结点、最小划分样本数、最大深度和是否为叶子结点等等。基本方法包括决策树构建、决策树拟合、决策树预测和打印等方法。

class Tree(object):
    def __init__(self, min_samples_split=2, min_impurity=1e-7,
                 max_depth=float("inf"), loss=None):
        self.root = None  # Root node in dec. tree
        # Minimum n of samples to justify split
        self.min_samples_split = min_samples_split
        # The minimum impurity to justify split
        self.min_impurity = min_impurity
        # The maximum depth to grow the tree to
        self.max_depth = max_depth
        # Function to calculate impurity (classif.=>info gain, regr=>variance reduct.)
        # 切割树的方法,gini,方差等
        self._impurity_calculation = None
        # Function to determine prediction of y at leaf
        # 树节点取值的方法,分类树:选取出现最多次数的值,回归树:取所有值的平均值
        self._leaf_value_calculation = None
        # If y is one-hot encoded (multi-dim) or not (one-dim)
        self.one_dim = None
        # If Gradient Boost
        self.loss = loss


    def fit(self, X, y, loss=None):
        """ Build decision tree """
        pass


    def _build_tree(self, X, y, current_depth=0):
        """ Recursive method which builds out the decision tree and splits X and respective y
        pass


    def predict_value(self, x, tree=None):
        """ Do a recursive search down the tree and make a prediction of the data sample by the
            value of the leaf that we end up at """
        pass


    def predict(self, X):
        """ Classify samples one by one and return the set of labels """
        pass


    def print_tree(self, tree=None, indent=" "):
        pass

以回归树为例,基于以上树模型,可定义回归树模型如下:

class RegressionTree(Tree):
    # 使用方差法进行树分割
    def _calculate_variance_reduction(self, y, y1, y2):
        var_tot = calculate_variance(y)
        var_1 = calculate_variance(y1)
        var_2 = calculate_variance(y2)
        frac_1 = len(y1) / len(y)
        frac_2 = len(y2) / len(y)
        # Calculate the variance reduction
        variance_reduction = var_tot - (frac_1 * var_1 + frac_2 * var_2)
        return sum(variance_reduction)


    # 使用均值法取叶子结点值
    def _mean_of_y(self, y):
        value = np.mean(y, axis=0)
        return value if len(value) > 1 else value[0]


    # 回归树拟合
    def fit(self, X, y):
        self._impurity_calculation = self._calculate_variance_reduction
        self._leaf_value_calculation = self._mean_of_y
        super(RegressionTree, self).fit(X, y)

在定义GBRT之前,先定义损失均方误差损失函数:

class Loss(object):
    def loss(self, y_true, y_pred):
        return NotImplementedError()
    def gradient(self, y, y_pred):
        raise NotImplementedError()
    def acc(self, y, y_pred):
        return 0


class SquareLoss(Loss):
    def __init__(self): pass
    def loss(self, y, y_pred):
        return 0.5 * np.power((y - y_pred), 2)
    def gradient(self, y, y_pred):
        return -(y - y_pred)

然后定义初始版本的GBDT模型:

class GBDT(object):
    def __init__(self, n_estimators, learning_rate, min_samples_split,
                 min_impurity, max_depth, regression):
        # 基本参数
        self.n_estimators = n_estimators
        self.learning_rate = learning_rate
        self.min_samples_split = min_samples_split
        self.min_impurity = min_impurity
        self.max_depth = max_depth
        self.regression = regression
        self.loss = SquareLoss()
        if not self.regression:
            self.loss = SotfMaxLoss()
        # 分类问题也可以使用回归树,利用残差去学习概率
        self.estimators = []
        for i in range(self.n_estimators):
            self.estimators.append(RegressionTree(min_samples_split=self.min_samples_split,
                                             min_impurity=self.min_impurity,
                                             max_depth=self.max_depth))
    # 拟合方法
    def fit(self, X, y):
        # 让第一棵树去拟合模型
        self.estimators[0].fit(X, y)
        y_pred = self.estimators[0].predict(X)
        for i in range(1, self.n_estimators):
            gradient = self.loss.gradient(y, y_pred)
            self.estimators[i].fit(X, gradient)
            y_pred -= np.multiply(self.learning_rate, self.estimators[i].predict(X))
    # 预测方法
    def predict(self, X):
        y_pred = self.estimators[0].predict(X)
        for i in range(1, self.n_estimators):
            y_pred -= np.multiply(self.learning_rate, self.estimators[i].predict(X))
        if not self.regression:
            # Turn into probability distribution
            y_pred = np.exp(y_pred) / np.expand_dims(np.sum(np.exp(y_pred), axis=1), axis=1)
            # Set label to the value that maximizes probability
            y_pred = np.argmax(y_pred, axis=1)
        return y_pred

     

然后可分别定义GBDT和GBRT:

# regression tree
class GBDTRegressor(GBDT):
      def __init__(self, n_estimators=200, learning_rate=0.5, min_samples_split=2,
                 min_var_red=1e-7, max_depth=4, debug=False):
        super(GBDTRegressor, self).__init__(n_estimators=n_estimators,
                                            learning_rate=learning_rate,
                                            min_samples_split=min_samples_split,
                                            min_impurity=min_var_red,
                                            max_depth=max_depth,
                                            regression=True)
# classification tree
class GBDTClassifier(GBDT):
      def __init__(self, n_estimators=200, learning_rate=.5, min_samples_split=2,
                 min_info_gain=1e-7, max_depth=2, debug=False):
         super(GBDTClassifier, self).__init__(n_estimators=n_estimators,
                                             learning_rate=learning_rate,
                                             min_samples_split=min_samples_split,
                                             min_impurity=min_info_gain,
                                             max_depth=max_depth,
                                             regression=False)
      def fit(self, X, y):
        y = to_categorical(y)
        super(GBDTClassifier, self).fit(X, y)

     

最后基于boston房价数据集给出一个计算例子:

from sklearn import datasets
boston = datasets.load_boston()
X, y = shuffle_data(boston.data, boston.target, seed=13)
X = X.astype(np.float32)
offset = int(X.shape[0] * 0.9)


X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)
print(X_train.shape, y_train.shape, X_test.shape, y_test.shape)


model = GBDTRegressor()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
# Color map
cmap = plt.get_cmap('viridis')
mse = mean_squared_error(y_test, y_pred)
print ("Mean Squared Error:", mse)


# Plot the results
m1 = plt.scatter(range(X_test.shape[0]), y_test, color=cmap(0.5), s=10)
m2 = plt.scatter(range(X_test.shape[0]), y_pred, color='black', s=10)
plt.suptitle("Regression Tree")
plt.title("MSE: %.2f" % mse, fontsize=10)
plt.xlabel('sample')
plt.ylabel('house price')
plt.legend((m1, m2), ("Test data", "Prediction"), loc='lower right')
plt.show();

slearn中为我们提供了GBDT算法完整的API可供调用,实际工程中更不可能自己手写这么复杂的算法系统。但作为学习,手写算法不失为一种深入理解算法细节和锻炼代码能力的好方法。

完整代码可参考:

https://github.com/RRdmlearning/Machine-Learning-From-Scratch/blob/master/gradient_boosting_decision_tree

欢迎扫码关注:

【机器学习核心总结】什么是GBDT(梯度提升树) 以苹果打分为例,我们会先训练一棵树大体预测一下苹果们的分数,再去训练一棵树去预测它们与真实分数间的差距,如果两者相加仍与真实分数存在差距,我们再训练第三棵树预测这部分差距,重复这个过程不断减少误差,将这些树的预测值加起来,就是苹果的分数。通过预测关联程度、点击率或是用户的喜好程度来排序,GBDT在搜索、广告、推荐系统等领域有着广泛应用,能处理标签、数值等各类数据,解释性强,这些都是GBDT的优点。其中之一是GBDT中的树都是回归树,树有分类有回归,区分它们的方法很简单。什么是GBDT(梯度提升树) 阅读详情

相关推荐

python实现GBDT的回归、二分类以及多分类

python实现GBDT的回归、二分类以及多分类,将算法流程详情进行展示解读并可视化,庖丁解牛地理解GBDT

数学推导+纯Python实现机器学习算法:XGBoost

点击上方“小白学视觉”,选择加"星标"或“置顶”重磅干货,第一时间送达 自从陈天奇于2015年提出XGBoost以来,该模型就一直在各大数据竞赛中当作大杀器被频繁祭出。速度快、效果好是XGBoost的最大优点。XGBoost与GBDT同出一脉,都属于boosting集成学习算法,但XGBoost相较于GBDT要青出于蓝而胜于蓝。 XGBoost的全程为eXtreme Gradien...

小白学视觉 526

经典机器学习算法的python实现

该附件提供了机器学习中的一些经典算法,包括分类、聚类、关联规则挖掘等。使用python实现,对初学者比较有用。

Python实现GBDT(梯度提升树)分类模型(GradientBoostingClassifier算法)并应用网格搜索算法寻找最优参数项目实战

Python实现GBDT(梯度提升树)分类模型(GradientBoostingClassifier算法)并应用网格搜索算法寻找最优参数项目实战

张陈亚的博客 8119

GBDT单机版Python实现源代码

GBDT单机版Python实现源代码

3dsMax高效导入OSGB倾斜模型的3个关键步骤与插件应用

本文详细解析了在3dsMax中高效导入OSGB倾斜模型的三个核心步骤:建立索引、处理贴图路径以及选择合适的插件。针对导入过程中常见的模型崩溃、贴图丢失和操作卡顿问题,提供了从数据结构理解到插件选型的实战解决方案,帮助用户实现大规模实景模型在3dsMax中的流畅导入与编辑。

weixin_29238147的博客 471

数学推导+纯Python实现机器学习算法2:逻辑回归

自本系列第一讲推出以来,得到了不少同学的反响和赞成,也有同学留言说最好能把数学推导部分写的详细点,笔者只能说尽力,因为打公式实在是太浪费时间了。。本节要和大家一起...

weixin_37737254的博客 602

DDR5内存调优实战:手把手教你搞定Write Leveling Training Mode(附时序图解析)

本文深入解析DDR5内存调优中的Write Leveling Training Mode技术,详细介绍了其核心原理、硬件准备、实战步骤及常见问题解决方案。通过JESD79-5标准定义的反馈机制,帮助硬件工程师精确对齐DQS与CK信号,提升系统稳定性和数据可靠性。附有时序图解析和代码示例,适合DDR5内存系统设计与调试参考。

weixin_29256771的博客 552

【项目实战】Python实现GBDT(梯度提升树)回归模型(GradientBoostingRegressor算法)项目实战

Python实现GBDT(梯度提升树)回归模型(GradientBoostingRegressor算法)项目实战

张陈亚的博客 1万+

LoFTR训练避坑指南:从零到一复现论文训练流程

本文是一份详细的LoFTR模型训练避坑指南,旨在帮助开发者从零开始复现论文训练流程。文章系统性地讲解了环境配置、数据准备、代码调试与显存优化等关键步骤,并针对常见的训练错误提供了解决方案,确保训练过程顺利进行。

weixin_29091837的博客 204

ESP32蓝牙广播数据自定义指南:让你的设备更容易被手机发现

本文详细介绍了如何通过自定义ESP32蓝牙广播数据提升设备在手机端的可发现性。从广播数据结构、扫描响应优化到跨平台兼容性设置,提供了全面的技术指南和实战代码示例,帮助开发者解决智能硬件开发中的蓝牙连接难题。

weixin_29172201的博客 273

数学推导+纯Python实现机器学习算法15:GBDT

Python机器学习算法实现Author:louwillMachine Learning Lab 时隔大半年,机器学习算法推导系列终于有时间继续更新了。在之前的14讲...

weixin_37737254的博客 535

C++软件异常分析概述

本文将详细讲述Windows系统中软件异常的分类以及常用的排查方法,给大家提供一个借鉴与参考。

dvlinker的技术专栏 4万+

【机器学习基础】数学推导+纯Python实现机器学习算法15:GBDT

Python机器学习算法实现Author:louwillMachine Learning Lab 时隔大半年,机器学习算法推导系列终于有时间继续更新了。在之前的14讲中...

fengdu78的博客 643

C++性能优化:深入理解缓存一致性与伪共享

在现代多核处理器的世界里,理解缓存一致性和伪共享就像理解一个复杂社会系统的运作规则。正如心理学家阿德勒所说:"人的行为总是有目的的",CPU缓存的每一次同步也都有其深层的硬件逻辑。本文将带你深入探索这些看不见的性能杀手,以及如何在实际项目中与它们优雅共处。

探索C++编程的奥秘,分享深入的技术见解和实践,旨在激发读者创造力与解决问题的思维。 936

Microsoft Forms功能深度解析:企业数据收集与协作的智能利器

Microsoft Forms是微软365生态中的在线表单工具,支持问卷调查、测验和投票创建,具备拖拽式界面、多题型设计和实时数据分析功能。其核心价值在于易用性、跨平台兼容性以及与Teams、SharePoint等微软服务的深度集成,满足GDPR/HIPAA等合规要求。提供表单创建、权限管理、自动化流程(通过Power Automate)和审计日志等功能,适用于金融、医疗、教育等多行业场景。虽然存在逻辑分支有限等约束,但通过案例证明能显著提升数据收集效率(达70-85%)。使用时需注意许可证配置(Busin

xueyunshengling的博客 9126

xgboost实例_【机器学习基础】数学推导+纯Python实现机器学习算法17:XGBoost

Python机器学习算法实现Author:louwillMachine Learning Lab 自从陈天奇于2015年提出XGBoost以来,该模型就一直在各大数据竞赛中当作大杀器被频繁祭出。速度快、效果好是XGBoost的最大优点。XGBoost与GBDT同出一脉,都属于boosting集成学习算法,但XGBoost相较于GBDT要青出于蓝而胜于蓝。 XGBoost的...

weixin_39740283的博客 167

【Unity3D插件】XCharts插件完全教程《全网最全》-专栏文章目录

最近在做图表类需求功能的时候,发现了一款强大的Unity3D插件,也就是XCharts图表插件,功能强大,支持多种图表。官方介绍:一款基于UGUI的功能强大、简单易用的数据可视化图表插件。支持折线图、饼状图、饼图、雷达图、散点图、热力图、环形图、K线图、极坐标、平行坐标等十多种内置图表,以及3D饼图、3D金字塔、漏斗图、仪表盘、水位图、象形柱图、甘特图、矩形树图等拓展图表。内置丰富示例和模板,参数可视化配置,效果实时预览,纯代码绘制。支持折线图、柱状图、饼图、雷达图、散点图、热力图等常见图表。

优快云博客专家,Unity3D高级软件工程师,《Unity 3D从入门到实战》作者。 3199

【机器学习基础】数学推导+纯Python实现机器学习算法30:系列总结与感悟

Python机器学习算法实现Author:louwillMachine Learning Lab 终于到了最后的总结。从第一篇线性回归的文章开始到现在,已经接近有两年的...

fengdu78的博客 1608

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

数学推导+纯Python实现机器学习算法30:系列总结与感悟

Python机器学习算法实现Author:louwillMachine Learning Lab 终于到了最后的总结。从第一篇线性回归的文章开始到现在,已经接近有两年的...

weixin_37737254的博客 836

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

数学推导+纯Python实现机器学习算法17:XGBoost

Python机器学习算法实现Author:louwillMachine Learning Lab 自从陈天奇于2015年提出XGBoost以来,该模型就一直在各大数据...

weixin_37737254的博客 691

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

ism模型python算法_数学推导+纯Python实现机器学习算法30:系列总结与感悟

Python机器学习算法实现Author:louwillMachine Learning Lab 终于到了最后的总结。从第一篇线性回归的文章开始到现在,已经接近有两年的时间了。当然,也不是纯写这30篇文章用了这么长时间,在第14篇Ridge回归之后中间断更了10个多月,好在今年抽出时间把全部补齐了。一点总结 整个系列对常用的、主流的机器学习模型与算法进行了梳理,主题只有两...

weixin_39834149的博客 722

【机器学习基础】数学推导+纯Python实现机器学习算法17:XGBoost

Python机器学习算法实现Author:louwillMachine Learning Lab 自从陈天奇于2015年提出XGBoost以来,该模型就一直在各大数据竞...

fengdu78的博客 689
上一篇: 零基础入门数据挖掘之建模调参
下一篇: 我用动画展现Pycharm十大实用技巧
机器学习算法那些事
博客等级 码龄9年 1633粉丝 62原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值