Пример #1
0
def reportPCA():
    # hyper parameters
    EPOCH = 100
    N_SPLITS = 10
    LEARNING_RATE = 0.1

    if len(emotions) <= 2:
        n_components = [3, 5, 8, 10]
    else:
        n_components = [10, 20, 40, 50]

    kfold = MyKFold(n_splits=N_SPLITS)
    df = pd.DataFrame(index=np.arange(0, len(n_components)),
                      columns=['n_components', 'avg_accuracy', 'avg_loss'])
    for i, n in enumerate(n_components):
        accuracy = 0
        loss = 0
        for d_train, d_valid, d_test in kfold.split_dict(images):
            classifier = SoftmaxRegression(lr=LEARNING_RATE)
            result = trainModel(classifier,
                                d_train,
                                d_valid,
                                d_test,
                                epoch=EPOCH,
                                n_components=n)
            accuracy += result.test_accuracy
            loss += result.test_loss
        accuracy /= kfold.n_splits
        loss /= kfold.n_splits
        df.loc[i] = (n, accuracy, loss)
    print("PCA Result (reported loss/accuracy on test set):")
    print(df)
Пример #2
0
def doRegression(images,
                 reg_type,
                 n_components=50,
                 epoch=100,
                 lr=0.1,
                 useBatch=True,
                 class_weight=None):
    # hyper parameters
    N_SPLITS = 10

    kfold = MyKFold(n_splits=N_SPLITS)
    results = []
    for d_train, d_valid, d_test in kfold.split_dict(images):
        if reg_type == 'softmax':
            classifier = SoftmaxRegression(lr=lr, class_weight=class_weight)
        elif reg_type == 'logistic':
            classifier = LogisticRegression(lr=lr)
        result = trainModel(classifier,
                            d_train,
                            d_valid,
                            d_test,
                            epoch=epoch,
                            n_components=n_components,
                            useBatch=useBatch)
        results.append(result)

    ret = AggregateResult.aggregate(results)
    print(
        "TEST result: loss_avg: {:.4f} ({:.4f}), accuracy: {:.4f}({:.4f}), balanced accuracy: {:.4f}({:.4f})"
        .format(ret.test_loss_avg, ret.test_loss_std, ret.test_accuracy_avg,
                ret.test_accuracy_std, ret.test_ber_avg, ret.test_ber_std))
    return ret
Пример #3
0
def visualizeWeights():
    # hyper parameters
    EPOCH = 100
    N_COMPONENTS = 50
    N_SPLITS = 10
    LEARNING_RATE = 0.1

    kfold = MyKFold(n_splits=N_SPLITS)
    test_accuracy = 0
    test_loss = 0

    model = SoftmaxRegression(lr=LEARNING_RATE)
    emotions = []
    i = 0
    for d_train, d_valid, d_test in kfold.split_dict(images):
        i += 1
        if i != 9: continue
        X_train, y_train = d_train
        pca = MyPCA(n_components=N_COMPONENTS)
        pca.fit(X_train)
        result = trainModel(model,
                            d_train,
                            d_valid,
                            d_test,
                            epoch=EPOCH,
                            n_components=N_COMPONENTS)

    print("test loss: {}, test accuracy: {}.".format(result.test_loss,
                                                     result.test_accuracy))
    # leave out bias term
    emotion_matrix = pca.components_.dot(model.coef_[1:, ]).T

    # linear scale
    emotion_matrix -= emotion_matrix.min(axis=1)
    emotion_matrix = np.multiply(emotion_matrix,
                                 255 / emotion_matrix.max(axis=1))
    emotion_matrix = emotion_matrix.astype(int)
    emotions = {}
    for i, label in enumerate(model.classes_):
        emotions[label] = np.array(emotion_matrix[i].reshape(224, 192))

    fig, axs = plt.subplots(2, 3)
    for ax, label in zip(axs.ravel(), emotions.keys()):
        ax.set_title(label)
        ax.set_axis_off()
        ax.imshow(emotions[label])
    plt.show()
Пример #4
0
    def __init__(
        self,
        n_ins,
        hidden_layers_sizes,
        n_outs,
        numpy_rng,
        theano_rng=None,
        corruption_levels=[0.1, 0.1]
    ):
        """ This class is made to support a variable number of layers.

        :type numpy_rng: numpy.random.RandomState
        :param numpy_rng: numpy random number generator used to draw initial
                    weights

        :type theano_rng: theano.tensor.shared_randomstreams.RandomStreams
        :param theano_rng: Theano random generator; if None is given one is
                           generated based on a seed drawn from `rng`

        :type n_ins: int
        :param n_ins: dimension of the input to the sdA

        :type n_layers_sizes: list of ints
        :param n_layers_sizes: intermediate layers size, must contain
                               at least one value

        :type n_outs: int
        :param n_outs: dimension of the output of the network

        :type corruption_levels: list of float
        :param corruption_levels: amount of corruption to use for each
                                  layer
        """

        self.sigmoid_layers = []
        self.dA_layers = []
        self.params = []
        self.n_layers = len(hidden_layers_sizes)

        assert self.n_layers > 0

        if not theano_rng:
            theano_rng = RandomStreams(numpy_rng.randint(2 ** 30))
        # allocate symbolic variables for the data
        self.x = T.matrix('x')  # the data is presented as rasterized images
        self.y = T.ivector('y')  # the labels are presented as 1D vector of
                                 # [int] labels
        # end-snippet-1

        # The SdA is an MLP, for which all weights of intermediate layers
        # are shared with a different denoising autoencoders
        # We will first construct the SdA as a deep multilayer perceptron,
        # and when constructing each sigmoidal layer we also construct a
        # denoising AutoEncoder that shares weights with that layer
        # During pretraining we will train these autoencoders (which will
        # lead to chainging the weights of the MLP as well)
        # During finetunining we will finish training the SdA by doing
        # stochastich gradient descent on the MLP

        # start-snippet-2
        for i in xrange(self.n_layers):
            # construct the sigmoidal layer

            # the size of the input is either the number of hidden units of
            # the layer below or the input size if we are on the first layer
            if i == 0:
                input_size = n_ins
            else:
                input_size = hidden_layers_sizes[i - 1]

            # the input to this layer is either the activation of the hidden
            # layer below or the input of the SdA if you are on the first
            # layer
            if i == 0:
                layer_input = self.x
            else:
                layer_input = self.sigmoid_layers[-1].output

            sigmoid_layer = HiddenLayer(rng=numpy_rng,
                                        input=layer_input,
                                        n_in=input_size,
                                        n_out=hidden_layers_sizes[i],
                                        activation=T.nnet.sigmoid)
            # add the layer to our list of layers
            self.sigmoid_layers.append(sigmoid_layer)
            # its arguably a philosophical question...
            # but we are going to only declare that the parameters of the
            # sigmoid_layers are parameters of the StackedDAA
            # the visible biases in the dA are parameters of those
            # dA, but not the SdA
            self.params.extend(sigmoid_layer.params)

            # Construct a denoising AutoEncoder that shared weights with this
            # layer
            dA_layer = dA(numpy_rng=numpy_rng,
                          theano_rng=theano_rng,
                          input=layer_input,
                          n_visible=input_size,
                          n_hidden=hidden_layers_sizes[i],
                          W=sigmoid_layer.W,
                          bhid=sigmoid_layer.b)
            self.dA_layers.append(dA_layer)
        # end-snippet-2
        # We now need to add a logistic layer on top of the MLP
        self.softmax_layer = SoftmaxRegression(
            input=self.sigmoid_layers[-1].output,
            n_in=hidden_layers_sizes[-1],
            n_out=n_outs
        )

        self.params.extend(self.softmax_layer.params)
        # construct a function that implements one step of finetunining

        # compute the prediction for an input
        self.predict = self.softmax_layer.y_pred
        # compute the cost for second phase of training,
        # defined as the negative log likelihood
        self.finetune_cost = self.softmax_layer.negative_log_likelihood(self.y)
        # compute the gradients with respect to the model parameters
        # symbolic variable that points to the number of errors made on the
        # minibatch given by self.x and self.y
        self.errors = self.softmax_layer.errors(self.y)
Пример #5
0
class SdA(object):
    """Stacked denoising auto-encoder class (SdA)

    A stacked denoising AutoEncoder model is obtained by stacking several
    dAs. The hidden layer of the dA at layer `i` becomes the input of
    the dA at layer `i+1`. The first layer dA gets as input the input of
    the SdA, and the hidden layer of the last dA represents the output.
    Note that after pretraining, the SdA is dealt with as a normal MLP,
    the dAs are only used to initialize the weights.
    """

    def __init__(
        self,
        n_ins,
        hidden_layers_sizes,
        n_outs,
        numpy_rng,
        theano_rng=None,
        corruption_levels=[0.1, 0.1]
    ):
        """ This class is made to support a variable number of layers.

        :type numpy_rng: numpy.random.RandomState
        :param numpy_rng: numpy random number generator used to draw initial
                    weights

        :type theano_rng: theano.tensor.shared_randomstreams.RandomStreams
        :param theano_rng: Theano random generator; if None is given one is
                           generated based on a seed drawn from `rng`

        :type n_ins: int
        :param n_ins: dimension of the input to the sdA

        :type n_layers_sizes: list of ints
        :param n_layers_sizes: intermediate layers size, must contain
                               at least one value

        :type n_outs: int
        :param n_outs: dimension of the output of the network

        :type corruption_levels: list of float
        :param corruption_levels: amount of corruption to use for each
                                  layer
        """

        self.sigmoid_layers = []
        self.dA_layers = []
        self.params = []
        self.n_layers = len(hidden_layers_sizes)

        assert self.n_layers > 0

        if not theano_rng:
            theano_rng = RandomStreams(numpy_rng.randint(2 ** 30))
        # allocate symbolic variables for the data
        self.x = T.matrix('x')  # the data is presented as rasterized images
        self.y = T.ivector('y')  # the labels are presented as 1D vector of
                                 # [int] labels
        # end-snippet-1

        # The SdA is an MLP, for which all weights of intermediate layers
        # are shared with a different denoising autoencoders
        # We will first construct the SdA as a deep multilayer perceptron,
        # and when constructing each sigmoidal layer we also construct a
        # denoising AutoEncoder that shares weights with that layer
        # During pretraining we will train these autoencoders (which will
        # lead to chainging the weights of the MLP as well)
        # During finetunining we will finish training the SdA by doing
        # stochastich gradient descent on the MLP

        # start-snippet-2
        for i in xrange(self.n_layers):
            # construct the sigmoidal layer

            # the size of the input is either the number of hidden units of
            # the layer below or the input size if we are on the first layer
            if i == 0:
                input_size = n_ins
            else:
                input_size = hidden_layers_sizes[i - 1]

            # the input to this layer is either the activation of the hidden
            # layer below or the input of the SdA if you are on the first
            # layer
            if i == 0:
                layer_input = self.x
            else:
                layer_input = self.sigmoid_layers[-1].output

            sigmoid_layer = HiddenLayer(rng=numpy_rng,
                                        input=layer_input,
                                        n_in=input_size,
                                        n_out=hidden_layers_sizes[i],
                                        activation=T.nnet.sigmoid)
            # add the layer to our list of layers
            self.sigmoid_layers.append(sigmoid_layer)
            # its arguably a philosophical question...
            # but we are going to only declare that the parameters of the
            # sigmoid_layers are parameters of the StackedDAA
            # the visible biases in the dA are parameters of those
            # dA, but not the SdA
            self.params.extend(sigmoid_layer.params)

            # Construct a denoising AutoEncoder that shared weights with this
            # layer
            dA_layer = dA(numpy_rng=numpy_rng,
                          theano_rng=theano_rng,
                          input=layer_input,
                          n_visible=input_size,
                          n_hidden=hidden_layers_sizes[i],
                          W=sigmoid_layer.W,
                          bhid=sigmoid_layer.b)
            self.dA_layers.append(dA_layer)
        # end-snippet-2
        # We now need to add a logistic layer on top of the MLP
        self.softmax_layer = SoftmaxRegression(
            input=self.sigmoid_layers[-1].output,
            n_in=hidden_layers_sizes[-1],
            n_out=n_outs
        )

        self.params.extend(self.softmax_layer.params)
        # construct a function that implements one step of finetunining

        # compute the prediction for an input
        self.predict = self.softmax_layer.y_pred
        # compute the cost for second phase of training,
        # defined as the negative log likelihood
        self.finetune_cost = self.softmax_layer.negative_log_likelihood(self.y)
        # compute the gradients with respect to the model parameters
        # symbolic variable that points to the number of errors made on the
        # minibatch given by self.x and self.y
        self.errors = self.softmax_layer.errors(self.y)

    def pretraining_functions(self, train_set_x, batch_size):
        ''' Generates a list of functions, each of them implementing one
        step in trainnig the dA corresponding to the layer with same index.
        The function will require as input the minibatch index, and to train
        a dA you just need to iterate, calling the corresponding function on
        all minibatch indexes.

        :type train_set_x: theano.tensor.TensorType
        :param train_set_x: Shared variable that contains all datapoints used
                            for training the dA

        :type batch_size: int
        :param batch_size: size of a [mini]batch

        :type learning_rate: float
        :param learning_rate: learning rate used during training for any of
                              the dA layers
        '''

        # index to a [mini]batch
        index = T.lscalar('index')  # index to a minibatch
        corruption_level = T.scalar('corruption')  # % of corruption to use
        learning_rate = T.scalar('lr')  # learning rate to use
        # begining of a batch, given `index`
        batch_begin = index * batch_size
        # ending of a batch given `index`
        batch_end = batch_begin + batch_size

        pretrain_fns = []
        for dA in self.dA_layers:
            # get the cost and the updates list
            cost, updates = dA.get_cost_updates(corruption_level,
                                                learning_rate)
            # compile the theano function
            fn = theano.function(
                inputs=[
                    index,
                    theano.Param(corruption_level, default=0.2),
                    theano.Param(learning_rate, default=0.1)
                ],
                outputs=cost,
                updates=updates,
                givens={
                    self.x: train_set_x[batch_begin: batch_end]
                }
            )
            # append `fn` to the list of functions
            pretrain_fns.append(fn)

        return pretrain_fns

    def build_finetune_functions(self, datasets, batch_size, learning_rate):
        '''Generates a function `train` that implements one step of
        finetuning, a function `validate` that computes the error on
        a batch from the validation set, and a function `test` that
        computes the error on a batch from the testing set

        :type datasets: list of pairs of theano.tensor.TensorType
        :param datasets: It is a list that contain all the datasets;
                         the has to contain three pairs, `train`,
                         `valid`, `test` in this order, where each pair
                         is formed of two Theano variables, one for the
                         datapoints, the other for the labels

        :type batch_size: int
        :param batch_size: size of a minibatch

        :type learning_rate: float
        :param learning_rate: learning rate used during finetune stage
        '''

        (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_valid_batches = valid_set_x.get_value(borrow=True).shape[0]
        n_valid_batches /= batch_size
        n_test_batches = test_set_x.get_value(borrow=True).shape[0]
        n_test_batches /= batch_size

        index = T.lscalar('index')  # index to a [mini]batch

        # compute the gradients with respect to the model parameters
        gparams = T.grad(self.finetune_cost, self.params)

        # compute list of fine-tuning updates
        updates = [
            (param, param - gparam * learning_rate)
            for param, gparam in zip(self.params, gparams)
        ]

        train_fn = theano.function(
            inputs=[index],
            outputs=self.finetune_cost,
            updates=updates,
            givens={
                self.x: train_set_x[
                    index * batch_size: (index + 1) * batch_size
                ],
                self.y: train_set_y[
                    index * batch_size: (index + 1) * batch_size
                ]
            },
            name='train'
        )

        test_score_i = theano.function(
            [index],
            self.errors,
            givens={
                self.x: test_set_x[
                    index * batch_size: (index + 1) * batch_size
                ],
                self.y: test_set_y[
                    index * batch_size: (index + 1) * batch_size
                ]
            },
            name='test'
        )

        valid_score_i = theano.function(
            [index],
            self.errors,
            givens={
                self.x: valid_set_x[
                    index * batch_size: (index + 1) * batch_size
                ],
                self.y: valid_set_y[
                    index * batch_size: (index + 1) * batch_size
                ]
            },
            name='valid'
        )

        # Create a function that scans the entire validation set
        def valid_score():
            return [valid_score_i(i) for i in xrange(n_valid_batches)]

        # Create a function that scans the entire test set
        def test_score():
            return [test_score_i(i) for i in xrange(n_test_batches)]

        return train_fn, valid_score, test_score

    def build_predict_function(self, inputs):
        predict_fn = theano.function(
            [],
            self.predict,
            givens={
                self.x: inputs
            },
            name='predict'
        )
        return predict_fn
Пример #6
0
def train(all_data):
    """
    Run training on data

    Reports different metrics after training

    :param all_data: input data
    """
    best_model = None
    stochastic_data = None

    folds = kfold(all_data)
    avg_epoch_data_train = EpochData()
    avg_epoch_data_val = EpochData()
    test_acc = []

    k = len(folds)
    for fold in range(k):
        for stochastic in range(2 if STOCHASTIC_VS_BATCH else 1):

            # define the model
            if LOGISTIC:
                model = LogisticRegression(LEARNING_RATE, PRINCIPAL_COMPONENTS)
            else:
                model = SoftmaxRegression(LEARNING_RATE, PRINCIPAL_COMPONENTS, len(CATEGORIES))

            # split data
            val_data, test_data = split_x_y(folds[fold]), split_x_y(folds[(fold + 1) % k])
            train_data = None
            for i in range(k):
                if i != fold and i != ((fold + 1) % k):
                    if train_data is None:
                        train_data = folds[i]
                    else:
                        train_data = np.concatenate((train_data, folds[i]))
            train_data = split_x_y(train_data)

            pca = PCA(train_data[0], PRINCIPAL_COMPONENTS)

            # PCA and one_hot
            train_data, test_data, val_data = transform(pca, train_data), transform(pca, test_data), transform(pca,
                                                                                                               val_data)
            validation_performance = EpochData()
            training_performance = EpochData()

            assert not (any([val_img in train_data for val_img in val_data]))

            for epoch in range(EPOCHS):
                if STOCHASTIC_GRADIENT or (STOCHASTIC_VS_BATCH and stochastic == 0):
                    model.stochastic_gradient_descent(train_data[0], train_data[1])
                else:
                    model.batch_gradient_descent(train_data[0], train_data[1])

                train_prob = model.probabilities(train_data[0])
                val_prob = model.probabilities(val_data[0])

                training_error = model.loss(train_data[1], train_prob)
                validation_error = model.loss(val_data[1], val_prob)

                traning_acc = model.accuracy(train_prob, train_data[1])
                validation_acc = model.accuracy(val_prob, val_data[1])

                if epoch % 10 == 0:
                    print("Training error: {}, validation error: {}, accuracy: {}".format(training_error,
                                                                                          validation_error,
                                                                                          traning_acc))

                # save
                validation_performance.save(validation_error, validation_acc)
                training_performance.save(training_error, traning_acc)

                # early stopping
                if validation_performance.increments > EARLY_STOPPING_THRESHOLD:
                    break

            # plot the graphs
            data_to_plot = [training_performance.error, validation_performance.error]
            legends = ["Training error", "Validation error"]
            visualize_data(data_to_plot, legends, "Epoch", "Cross entropy error")

            data_to_plot = [training_performance.acc, validation_performance.acc]
            legends = ["Training accuracy", "Validation accuracy"]
            visualize_data(data_to_plot, legends, "Epoch", "Accuracy")

            # save the validation data to the model
            model.epoch_data = validation_performance

            # save the test data to the model
            model.test_data = test_data

            # save the pca
            model.pca = pca

            # save the epoch data
            avg_epoch_data_train.add(training_performance)
            avg_epoch_data_val.add(validation_performance)

            # save test accuracy
            test_acc.append(model.accuracy(model.probabilities(test_data[0]),
                                           test_data[1]))
            print("Test accuracy: {} ".format(test_acc[-1]))

            # save the best model
            if best_model is None:
                best_model = model
            elif best_model.epoch_data.score() > model.epoch_data.score():
                best_model = model

            if STOCHASTIC_VS_BATCH:
                # display graph
                if stochastic == 1:
                    data_to_visualize = [stochastic_data.error,
                                         training_performance.error]
                    visualize_data(data_to_visualize, ["Stochastic - train error", "Batch - train error"], "Epoch", "Loss")
                else:
                    stochastic_data = training_performance

    avg_test_acc = np.average(np.array(test_acc))
    avg_test_acc_std = np.std(np.array(test_acc))
    print("Avg test accuracy: {} ({})".format(avg_test_acc, avg_test_acc_std))

    avg_epoch_data_train.align(FOLDS)
    avg_epoch_data_val.align(FOLDS)

    visualize_data_avg(avg_epoch_data_train, avg_epoch_data_val)
    if not LOGISTIC:
        best_model.visualize_weights(model.pca)

    if SHOW_CONFUSION_MATRIX:
        confusion_matrix(best_model)

    if SHOW_PRINCIPAL_COMPONENTS:
        show_principal_components(pca)