使用Theano实现kaggle手写识别:multilayer perceptron

前面一片博客介绍了使用logistic regression来实现kaggle上的手写识别,这篇博客继续介绍使用多层感知机来实现手写识别,并提高了正确率。写完上篇博客后,我去看了一些爬虫的东西(还没搞完),因此在40天后才有了这篇博客。

这里使用了pandas来读取csv文件,具体函数如下。我们使用了train.csv中的前8份做training set,第九份做validation set,第十份做testing set。

def load_data(path):
    print('...loading data')
    train_df = pandas.DataFrame.from_csv(path+'train.csv', index_col=False).fillna(0).astype(int)
    test_df = pandas.DataFrame.from_csv(path+'test.csv', index_col=False).fillna(0).astype(int)

    def shared_dataset(data_xy, borrow=True):
        """ Function that loads the dataset into shared variables

        The reason we store our dataset in shared variables is to allow
        Theano to copy it into the GPU memory (when code is run on GPU).
        Since copying data into the GPU is slow, copying a minibatch everytime
        is needed (the default behaviour if the data is not in a shared
        variable) would lead to a large decrease in performance.
        """
        data_x, data_y = data_xy
        shared_x = theano.shared(numpy.asarray(data_x, dtype=theano.config.floatX), borrow=borrow)
        shared_y = theano.shared(numpy.asarray(data_y, dtype=theano.config.floatX), borrow=borrow)
        # When storing data on the GPU it has to be stored as floats
        # therefore we will store the labels as ``floatX`` as well
        # (``shared_y`` does exactly that). But during our computations
        # we need them as ints (we use labels as index, and if they are
        # floats it doesn't make sense) therefore instead of returning
        # ``shared_y`` we will have to cast it to int. This little hack
        # lets ous get around this issue
        return shared_x, T.cast(shared_y, 'int32')

    train_set = [train_df.values[0:33600, 1:]/255.0, train_df.values[0:33600, 0]]
    valid_set = [train_df.values[33600:37800, 1:]/255.0, train_df.values[33600:37800, 0]]
    test_set = [train_df.values[37800:, 1:]/255.0, train_df.values[37800:, 0]]
    predict_set = test_df.values/255.0

下面定义了一个类,作为多层感知机的隐藏层。

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
        sigmoid 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
        :param W:
        :param b:
        :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 runnable 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]

下面是多层感知机的类,具体如下:

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 hiddenlayer 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 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 negative_log_likelihood(self, y):
        return -T.mean(T.log(self.logRegressionLayer.p_y_given_x)[T.arange(y.shape[0]), y])

    def errors(self, y):
        if y.ndim != self.logRegressionLayer.y_pred.ndim:
            raise TypeError(
                'y should have the same shape as self.y_pred',
                ('y', y.type, 'y_pred', self.logRegressionLayer.y_pred.type)
            )
        # check if y is of the correct datatype
        if y.dtype.startswith('int'):
            # the T.neq operator returns a vector of 0s and 1s, where a
            # represents a mistake in prediction
            return T.mean(T.neq(self.logRegressionLayer.y_pred, y))
        else:
            raise NotImplementedError()

    def __getstate__(self):
        return self.__dict__

下面是使用多层感知机来训练模型的函数,具体函数如下:

def test_mlp(learning_rate=0.0005, L1_reg=0.00, L2_reg=0.0001, n_epochs=100,
                path=r'', 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
    :param batch_size:
    :param n_hidden:
    :return:
    """

    datasets = load_data(path)
    # datasets = read_raw_train(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 (sorted 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)
    #  ]

    # using RMSprop(scaling the gradient based on running average)
    # to update the parameters of the model as a list of (variable,update expression) pairs
    def RMSprop(gparams, params, learning_rate, rho=0.9, epsilon=1e-6):
        """
        param:rho,the fraction we keep the previous gradient contribution
        """
        updates = []
        for p, g in zip(params, gparams):
            acc = theano.shared(p.get_value() * 0.)
            acc_new = rho * acc + (1 - rho) * g ** 2
            gradient_scaling = T.sqrt(acc_new + epsilon)
            g = g / gradient_scaling
            updates.append((acc, acc_new))
            updates.append((p, p - learning_rate * g))
        return updates

    # 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=RMSprop(gparams, classifier.params, learning_rate),
        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 += 1
        if epoch > 60:
            learning_rate = 0.001
        for minibatch_index in range(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 range(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 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 range(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.))

                    # save the best model
                    with open('mlp_best_model.pkl01', 'wb') as f:
                       pickle.dump(classifier, f)

            if patience <= iter:
                done_looping = True
                break
    end_time = timeit.default_timer()
    print(('Optimization complete. Besat validation score of %f %% '
           'obtained at iteration %i, with test performance %f %%') %
          (best_validation_loss*100., best_iter+1, test_score*100.))
    print(('The code for file ' + os.path.split(__file__)[1] +
           'ran for %.2fm' % ((end_time - start_time)/60.)), file=sys.stderr)

下面是预测函数,并将预测结果保存在了mlp_best_model_answer.csv。

def predict_kaggle(file1, file2):
    # load the saved model
    classifier = pickle.load(open(file1))
    # compile a predictor function
    predict_model = theano.function(inputs=[classifier.input], outputs=classifier.logRegressionLayer.y_pred,
                                    allow_input_downcast=True)

    # make prediction
    data_path = r'E:\Lab\digitrecognizer\test.csv'
    datasets = load_data(r'')
    test_set_x = datasets[3]
    test_set_x = test_set_x.get_value()
    predicted_values = predict_model(test_set_x[:28000])
    # 保存预测结果
    saveResult(predicted_values, file2)

这次使用了一个带GTX960M的笔记本来跑实验,速度跟之前比,算是飞起来了。跑完后的结果正确率为97.486%。下面我会做适当修改,尝试得到更高的准确率。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值