多层感知器学习

1.多层感知器简介

多层感知器(MLP)可以看做一个逻辑回归,不过它的输入要先进行一个非线性变换,这样数据就被映射到线性可分的空间了,这个空间我们称为隐藏层。通常单层隐藏层就可以作为一个感知器了,其结构如下图所示:

这里输入层首先通过权重矩阵和偏置得到总输出值并且通过tanh函数作一个非线性变换就可以得到hidden layer,然后从hidden layer到output layer可以使用之前的逻辑回归进行操作。

这里我们同样使用SGD算法来对参数进行更新,参数共有四个,分别是input-hidden权重、偏置以及hidden-output权重、偏置。

2.Python代码

2.1 程序流程

首先我们需要构建hidden layer类,其构造函数为:通过传入input layer,确定输入的维度以及hidden layer维度,然后使用均匀分布初始化input layer-hidden layer之间的权重矩阵,将hidden layer的bias初始化为0向量。并最终得到一个非线性激活函数的输出。

接下来我们定义一个MLP类,构造函数为输入层、输入层的维度、隐藏层维度、输出层维度,然后实例化一个HiddenLayer对象,然后对该对象的output进行逻辑回归(参考上一篇逻辑回归博文的代码,本文中的代码需要导入它),然后定义L1为HiddenLayer的W的和加上逻辑回归后的实例的W的和(简单说就是两个W各自求和再相加得到L1),同时定义L2为HiddenLayer的W的平方和加上逻辑回归后的实例的W的平方和(简单说就是两个W平方和相加得到L2),同时把逻辑回归的负对数似然、误差函数传给MLP,并且整合四个参数。

接下来是训练阶段,这里我们仍然对mnist手写字识别进行测试,这里定义损耗函数为负对数似然+L1+L2,然后定义两个函数test_model和validate_model的符号表达式,以及求参数的梯度及其更新的符号表达式,最后整合进train_model函数。

接下来开始执行训练,训练一共1000epoch,然后将数据分为多个minibatch,每次对minibatch_index的数据进行训练参数更新。

2.2 代码

"""
This tutorial introduces the multilayer perceptron using Theano.

 A multilayer perceptron is a logistic regressor where
instead of feeding the input to the logistic regression you insert a
intermediate layer, called the hidden layer, that has a nonlinear
activation function (usually tanh or sigmoid) . One can use many such
hidden layers making the architecture deep. The tutorial will also tackle
the problem of MNIST digit classification.

.. math::

    f(x) = G( b^{(2)} + W^{(2)}( s( b^{(1)} + W^{(1)} x))),

References:

    - textbooks: "Pattern Recognition and Machine Learning" -
                 Christopher M. Bishop, section 5

"""
__docformat__ = ‘restructedtext en‘

import os
import sys
import timeit

import numpy

import theano
import theano.tensor as T

from logistic_sgd import LogisticRegression, load_data

# start-snippet-1
class HiddenLayer(object):
    def __init__(self, rng, input, n_in, n_out, W=None, b=None,
                 activation=T.tanh):
        """
        Typical hidden layer of a MLP: units are fully-connected and have
        sigmoidal activation function. Weight matrix W is of shape (n_in,n_out)
        and the bias vector b is of shape (n_out,).

        NOTE : The nonlinearity used here is tanh

        Hidden unit activation is given by: tanh(dot(input,W) + b)

        :type rng: numpy.random.RandomState
        :param rng: a random number generator used to initialize weights

        :type input: theano.tensor.dmatrix
        :param input: a symbolic tensor of shape (n_examples, n_in)

        :type n_in: int
        :param n_in: dimensionality of input

        :type n_out: int
        :param n_out: number of hidden units

        :type activation: theano.Op or function
        :param activation: Non linearity to be applied in the hidden
                           layer
        """
        self.input = input
        # end-snippet-1

        # `W` is initialized with `W_values` which is uniformely sampled
        # from sqrt(-6./(n_in+n_hidden)) and sqrt(6./(n_in+n_hidden))
        # for tanh activation function
        # the output of uniform if converted using asarray to dtype
        # theano.config.floatX so that the code is runable on GPU
        # Note : optimal initialization of weights is dependent on the
        #        activation function used (among other things).
        #        For example, results presented in [Xavier10] suggest that you
        #        should use 4 times larger initial weights for sigmoid
        #        compared to tanh
        #        We have no info for other function, so we use the same as
        #        tanh.
        if W is None:
            W_values = numpy.asarray(
                rng.uniform(
                    low=-numpy.sqrt(6. / (n_in + n_out)),
                    high=numpy.sqrt(6. / (n_in + n_out)),
                    size=(n_in, n_out)
                ),
                dtype=theano.config.floatX
            )
            if activation == theano.tensor.nnet.sigmoid:
                W_values *= 4

            W = theano.shared(value=W_values, name=‘W‘, borrow=True)

        if b is None:
            b_values = numpy.zeros((n_out,), dtype=theano.config.floatX)
            b = theano.shared(value=b_values, name=‘b‘, borrow=True)

        self.W = W
        self.b = b

        lin_output = T.dot(input, self.W) + self.b
        self.output = (
            lin_output if activation is None
            else activation(lin_output)
        )
        # parameters of the model
        self.params = [self.W, self.b]

# start-snippet-2
class MLP(object):
    """Multi-Layer Perceptron Class

    A multilayer perceptron is a feedforward artificial neural network model
    that has one layer or more of hidden units and nonlinear activations.
    Intermediate layers usually have as activation function tanh or the
    sigmoid function (defined here by a ``HiddenLayer`` class)  while the
    top layer is a softmax layer (defined here by a ``LogisticRegression``
    class).
    """

    def __init__(self, rng, input, n_in, n_hidden, n_out):
        """Initialize the parameters for the multilayer perceptron

        :type rng: numpy.random.RandomState
        :param rng: a random number generator used to initialize weights

        :type input: theano.tensor.TensorType
        :param input: symbolic variable that describes the input of the
        architecture (one minibatch)

        :type n_in: int
        :param n_in: number of input units, the dimension of the space in
        which the datapoints lie

        :type n_hidden: int
        :param n_hidden: number of hidden units

        :type n_out: int
        :param n_out: number of output units, the dimension of the space in
        which the labels lie

        """

        # Since we are dealing with a one hidden layer MLP, this will translate
        # into a HiddenLayer with a tanh activation function connected to the
        # LogisticRegression layer; the activation function can be replaced by
        # sigmoid or any other nonlinear function
        self.hiddenLayer = HiddenLayer(
            rng=rng,
            input=input,
            n_in=n_in,
            n_out=n_hidden,
            activation=T.tanh
        )

        # The logistic regression layer gets as input the hidden units
        # of the hidden layer
        self.logRegressionLayer = LogisticRegression(
            input=self.hiddenLayer.output,
            n_in=n_hidden,
            n_out=n_out
        )
        # end-snippet-2 start-snippet-3
        # L1 norm ; one regularization option is to enforce L1 norm to
        # be small
        self.L1 = (
            abs(self.hiddenLayer.W).sum()
            + abs(self.logRegressionLayer.W).sum()
        )

        # square of L2 norm ; one regularization option is to enforce
        # square of L2 norm to be small
        self.L2_sqr = (
            (self.hiddenLayer.W ** 2).sum()
            + (self.logRegressionLayer.W ** 2).sum()
        )

        # negative log likelihood of the MLP is given by the negative
        # log likelihood of the output of the model, computed in the
        # logistic regression layer
        self.negative_log_likelihood = (
            self.logRegressionLayer.negative_log_likelihood
        )
        # same holds for the function computing the number of errors
        self.errors = self.logRegressionLayer.errors

        # the parameters of the model are the parameters of the two layer it is
        # made out of
        self.params = self.hiddenLayer.params + self.logRegressionLayer.params
        # end-snippet-3

        # keep track of model input
        self.input = input

def test_mlp(learning_rate=0.01, L1_reg=0.00, L2_reg=0.0001, n_epochs=1000,
             dataset=‘mnist.pkl.gz‘, batch_size=20, n_hidden=500):
    """
    Demonstrate stochastic gradient descent optimization for a multilayer
    perceptron

    This is demonstrated on MNIST.

    :type learning_rate: float
    :param learning_rate: learning rate used (factor for the stochastic
    gradient

    :type L1_reg: float
    :param L1_reg: L1-norm‘s weight when added to the cost (see
    regularization)

    :type L2_reg: float
    :param L2_reg: L2-norm‘s weight when added to the cost (see
    regularization)

    :type n_epochs: int
    :param n_epochs: maximal number of epochs to run the optimizer

    :type dataset: string
    :param dataset: the path of the MNIST dataset file from
                 http://www.iro.umontreal.ca/~lisa/deep/data/mnist/mnist.pkl.gz

   """
    datasets = load_data(dataset)

    train_set_x, train_set_y = datasets[0]
    valid_set_x, valid_set_y = datasets[1]
    test_set_x, test_set_y = datasets[2]

    # compute number of minibatches for training, validation and testing
    n_train_batches = train_set_x.get_value(borrow=True).shape[0] / batch_size
    n_valid_batches = valid_set_x.get_value(borrow=True).shape[0] / batch_size
    n_test_batches = test_set_x.get_value(borrow=True).shape[0] / batch_size

    ######################
    # BUILD ACTUAL MODEL #
    ######################
    print ‘... building the model‘

    # allocate symbolic variables for the data
    index = T.lscalar()  # index to a [mini]batch
    x = T.matrix(‘x‘)  # the data is presented as rasterized images
    y = T.ivector(‘y‘)  # the labels are presented as 1D vector of
                        # [int] labels

    rng = numpy.random.RandomState(1234)

    # construct the MLP class
    classifier = MLP(
        rng=rng,
        input=x,
        n_in=28 * 28,
        n_hidden=n_hidden,
        n_out=10
    )

    # start-snippet-4
    # the cost we minimize during training is the negative log likelihood of
    # the model plus the regularization terms (L1 and L2); cost is expressed
    # here symbolically
    cost = (
        classifier.negative_log_likelihood(y)
        + L1_reg * classifier.L1
        + L2_reg * classifier.L2_sqr
    )
    # end-snippet-4

    # compiling a Theano function that computes the mistakes that are made
    # by the model on a minibatch
    test_model = theano.function(
        inputs=[index],
        outputs=classifier.errors(y),
        givens={
            x: test_set_x[index * batch_size:(index + 1) * batch_size],
            y: test_set_y[index * batch_size:(index + 1) * batch_size]
        }
    )

    validate_model = theano.function(
        inputs=[index],
        outputs=classifier.errors(y),
        givens={
            x: valid_set_x[index * batch_size:(index + 1) * batch_size],
            y: valid_set_y[index * batch_size:(index + 1) * batch_size]
        }
    )

    # start-snippet-5
    # compute the gradient of cost with respect to theta (sotred in params)
    # the resulting gradients will be stored in a list gparams
    gparams = [T.grad(cost, param) for param in classifier.params]

    # specify how to update the parameters of the model as a list of
    # (variable, update expression) pairs

    # given two lists of the same length, A = [a1, a2, a3, a4] and
    # B = [b1, b2, b3, b4], zip generates a list C of same size, where each
    # element is a pair formed from the two lists :
    #    C = [(a1, b1), (a2, b2), (a3, b3), (a4, b4)]
    updates = [
        (param, param - learning_rate * gparam)
        for param, gparam in zip(classifier.params, gparams)
    ]

    # compiling a Theano function `train_model` that returns the cost, but
    # in the same time updates the parameter of the model based on the rules
    # defined in `updates`
    train_model = theano.function(
        inputs=[index],
        outputs=cost,
        updates=updates,
        givens={
            x: train_set_x[index * batch_size: (index + 1) * batch_size],
            y: train_set_y[index * batch_size: (index + 1) * batch_size]
        }
    )
    # end-snippet-5

    ###############
    # TRAIN MODEL #
    ###############
    print ‘... training‘

    # early-stopping parameters
    patience = 10000  # look as this many examples regardless
    patience_increase = 2  # wait this much longer when a new best is
                           # found
    improvement_threshold = 0.995  # a relative improvement of this much is
                                   # considered significant
    validation_frequency = min(n_train_batches, patience / 2)
                                  # go through this many
                                  # minibatche before checking the network
                                  # on the validation set; in this case we
                                  # check every epoch

    best_validation_loss = numpy.inf
    best_iter = 0
    test_score = 0.
    start_time = timeit.default_timer()

    epoch = 0
    done_looping = False

    while (epoch < n_epochs) and (not done_looping):
        epoch = epoch + 1
        for minibatch_index in xrange(n_train_batches):

            minibatch_avg_cost = train_model(minibatch_index)
            # iteration number
            iter = (epoch - 1) * n_train_batches + minibatch_index

            if (iter + 1) % validation_frequency == 0:
                # compute zero-one loss on validation set
                validation_losses = [validate_model(i) for i
                                     in xrange(n_valid_batches)]
                this_validation_loss = numpy.mean(validation_losses)

                print(
                    ‘epoch %i, minibatch %i/%i, validation error %f %%‘ %
                    (
                        epoch,
                        minibatch_index + 1,
                        n_train_batches,
                        this_validation_loss * 100.
                    )
                )

                # if we got the best validation score until now
                if this_validation_loss < best_validation_loss:
                    #improve patience if loss improvement is good enough
                    if (
                        this_validation_loss < best_validation_loss *
                        improvement_threshold
                    ):
                        patience = max(patience, iter * patience_increase)

                    best_validation_loss = this_validation_loss
                    best_iter = iter

                    # test it on the test set
                    test_losses = [test_model(i) for i
                                   in xrange(n_test_batches)]
                    test_score = numpy.mean(test_losses)

                    print((‘     epoch %i, minibatch %i/%i, test error of ‘
                           ‘best model %f %%‘) %
                          (epoch, minibatch_index + 1, n_train_batches,
                           test_score * 100.))

            if patience <= iter:
                done_looping = True
                break

    end_time = timeit.default_timer()
    print((‘Optimization complete. Best validation score of %f %% ‘
           ‘obtained at iteration %i, with test performance %f %%‘) %
          (best_validation_loss * 100., best_iter + 1, test_score * 100.))
    print >> sys.stderr, (‘The code for file ‘ +
                          os.path.split(__file__)[1] +
                          ‘ ran for %.2fm‘ % ((end_time - start_time) / 60.))

if __name__ == ‘__main__‘:
    test_mlp()
时间: 2024-10-09 20:41:28

多层感知器学习的相关文章

RBF神经网络学习算法及与多层感知器的比较

对于RBF神经网络的原理已经在我的博文<机器学习之径向基神经网络(RBF NN)>中介绍过,这里不再重复.今天要介绍的是常用的RBF神经网络学习算法及RBF神经网络与多层感知器网络的对比. 一.RBF神经网络学习算法 广义的RBF神经网络结构如下图所示: N-M-L结构对应着N维输入,M个数据中心点centers,L个输出. RBF 网络常用学习算法 RBF 网络的设计包括结构设计和参数设计.结构设计主要解决如何确定网络隐节点数的问题.参数设计一般需考虑包括3种参数:各基函数的数据中心和扩展常

神经网络入门回顾(感知器、多层感知器)

神经网络属于“连接主义”,和统计机器学习的理论基础区别还是很不一样. 以我自己的理解,统计机器学习的理论基于统计学,理论厚度足够强,让人有足够的安全感:而神经网络的理论更侧重于代数,表征能力特别强,不过可解释性欠佳. 这两个属于机器学习的两个不同的流派,偶尔也有相互等价的算法. 本文回顾神经网络最简单的构件:感知器.多层感知器. 感知器 感知器是二类分类的线性分类模型,将实例划分为正负两类的分离超平面(separating hyperplane),属于判别模型. 感知器基于线性阈值单元(Line

TFboy养成记 多层感知器 MLP

内容总结与莫烦的视频. 这里多层感知器代码写的是一个简单的三层神经网络,输入层,隐藏层,输出层.代码的目的是你和一个二次曲线.同时,为了保证数据的自然,添加了mean为0,steddv为0.05的噪声. 添加层代码: def addLayer(inputs,inSize,outSize,activ_func = None):#insize outsize表示输如输出层的大小,inputs是输入.activ_func是激活函数,输出层没有激活函数.默认激活函数为空 with tf.name_sco

从最简单的感知器学习到的一些有趣的现象

看了一些深度学习神经网络的视频,最近有了一点新的体会,在google的一个小工具上,地址:http://playground.tensorflow.org 一个神经网络训练的模拟器,发现了一些有意思的事情,有了些新的体会 这里分享给大家. 1 权值,刚开始都是设置的随机初始值,但是随着训练的深入,你会发现权值变化的一些规律,这里一二分类为列,某些对最终分类帮助性大的因素即输入的权值会越来越大,而那些对分类作用小的因素,甚至对分类起反作用的因素的权值会逐渐变得很小,或者为负值,有些同学会问权值之和

机器学习算法一:感知器学习

问题描述: 给定线性可分数据集:T={(x1,y1),(x2,y2),...,(xN,yN)},存在超平面S:$w\cdot x+b=0$ $ \left\{\begin{matrix} w\cdot x+b>0,y=+1\\  w\cdot x+b<0,y=-1 \end{matrix}\right. $ 学习策略: 定义点x0到超平面S的距离为: $\frac{1}{\left \| w \right \|}\left | w \cdot x +b \right |$ 对于误分类的数据$(

Keras 使用多层感知器 预测泰坦尼克 乘客 生还概率

# coding: utf-8 # In[6]: # -*- coding: utf-8 -*- import urllib.request import os # In[7]: url="http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic3.xls" filepath="data/titanic3.xls" if not os.path.isfile(filepath): result=u

Python_sklearn机器学习库学习笔记(七)the perceptron(感知器)

一.感知器 感知器是Frank Rosenblatt在1957年就职于Cornell航空实验室时发明的,其灵感来自于对人脑的仿真,大脑是处理信息的神经元(neurons)细胞和链接神经元细胞进行信息传递的突触(synapses)构成. 一个神经元可以看做将一个或者多个输入处理成一个输出的计算单元.一个感知器函数类似于一个神经元:它接受一个或多个输入,处理 他们然后返回一个输出.神经元可以实时,错误驱动的学习,神经元可以通过一个训练样本不断的更新参数,而非一次使用整套的数据.实时学习可能有效的处理

单层感知器--matlab神经网络

单层感知器属于单层前向网络,即除输入层和输出层之外,只拥有一层神经元节点. 特点:输入数据从输入层经过隐藏层向输出层逐层传播,相邻两层的神经元之间相互连接,同一层的神经元之间没有连接. 感知器(perception)是由美国学者F.Rosenblatt提出的.与最早提出的MP模型不同,神经元突触权值可变,因此可以通过一定规则进行学习.可以快速.可靠地解决线性可分的问题. 单层感知器由一个线性组合器和一个二值阈值元件组成. 输入是一个N维向量 x=[x1,x2,...,xn],其中每一个分量对应一

Coursera机器学习基石 第2讲:感知器

第一讲中我们学习了一个机器学习系统的完整框架,包含以下3部分:训练集.假设集.学习算法 一个机器学习系统的工作原理是:学习算法根据训练集,从假设集合H中选择一个最好的假设g,使得g与目标函数f尽可能低接近.H称为假设空间,是由一个学习模型的参数决定的假设构成的一个空间.而我们这周就要学习一个特定的H——感知器模型. 感知器模型在神经网络发展历史中占有特殊地位,并且是第一个具有完整算法描述的神经网络学习算法(称为感知器学习算法:PLA).这个算法是由一位心理学家Rosenblatt在1958年提出