Skip to content

Building your own model

Tu Dinh Nguyen edited this page Nov 9, 2018 · 2 revisions

How to build your own model

Written by Mahmoud Hossam

1- Create a development branch for your new model

You must not develop on the main branch (the master branch) which must be always kept stable and used by everyone. You should develop, commit and push into your own branch, then after you reach a stage where you think that it is ready to be merged to the master, you can request the team to discuss your changes and approve (this is done by a pull request, which is the last step that we will discuss at the end).

Create a local branch on your machine:

git checkout -b mahmoud_MLP

As a naming convention, we name the new branch with first author name and the name of the new model. For example, in this case, we are adding MLP (Multilayer Perceptron) to the package.

2- Add your model's class definition .py file

In male\models folder, add a new .py file for your model. This file will contain the new model class definition, e.g. mlp.py in our case. Create folders in an appropriate hierarchy if necessary. For example, MLP model is a deep learning model, so we first add a folder called deep_learning (if it doesn't exist) and place the mlp.py file in it.

  • All new models in the package must inherit from the base class Model. The two main methods to implement from the base class Model in your new class are _fit_loop and predict. But we also need proper initialization and other helper functions from the base class. So first, we will implement initialization then add other methods. For example, our new MLP class looks like this:
class MLP(Model):

    def __init__(self,
                 model_name='MLP',
                 hidden_units_list=[],
                 learning_rate=0.01,
                 reg_lambda=0.01,
                 **kwargs
                 ):

        super(MLP, self).__init__(model_name=model_name, **kwargs)
        # initialize class parameters here
        self.hidden_units_list = hidden_units_list
        self.learning_rate = learning_rate
        self.reg_lambda = reg_lambda

    def _init(self):
        super(MLP, self)._init()
        # declare other members here, e.g. model learnable parameters (weights and biases) and other helpers
        self.W1 = None
        self.b1 = None
        self.W2 = None
        self.b2 = None
        self.onehot_encoder = None

    def _init_params(self, x):
        # initialize and reset model's learnable parameters here, e.g. weights and biases
        self.W1 = self.random_engine.randn(x.shape[1], self.hidden_units_list[0]) / np.sqrt(x.shape[1])
        self.b1 = np.zeros((1, self.hidden_units_list[0]))
        self.W2 = self.random_engine.randn(self.hidden_units_list[0], self.num_classes) / np.sqrt(self.hidden_units_list[0])
        self.b2 = np.zeros((1, self.num_classes))

We use the constructor __init__() for collecting model's parameters from the user of the class, _init() method to declare the rest of the class members like the learnable parameters and any helpers, and _init_params() to initialize and reset the learnable parameters according to the passed data argument x.

  • Add your _fit_loop and predict methods. For our case, they look like this:
    def _fit_loop(self, x, y,
                  do_validation=False,
                  x_valid=None, y_valid=None,
                  callbacks=None, callback_metrics=None):

        batches = make_batches(x.shape[0], self.batch_size)

        while (self.epoch < self.num_epochs) and (not self.stop_training):
            epoch_logs = {}
            callbacks.on_epoch_begin(self.epoch)

            for batch_idx, (batch_start, batch_end) in enumerate(batches):
                batch_logs = {'batch': batch_idx,
                              'size': batch_end - batch_start}
                callbacks.on_batch_begin(batch_idx, batch_logs)

                x_batch = x[batch_start:batch_end]
                y_batch = y[batch_start:batch_end]
                current_batch_size = batch_end - batch_start

                # Fit loop computation starts here ---------------------

                # Forward propagation
                z1 = x_batch.dot(self.W1) + self.b1
                a1 = np.tanh(z1)
                z2 = a1.dot(self.W2) + self.b2
                exp_scores = np.exp(z2)
                probs = exp_scores / np.sum(exp_scores, axis=1, keepdims=True)

                # Backpropagation
                delta3 = probs
                delta3[range(current_batch_size), np.argmax(y_batch, axis=1)] -= 1
                delta3 /= x_batch.shape[0]

                dW2 = (a1.T).dot(delta3)
                db2 = np.sum(delta3, axis=0, keepdims=True)
                delta2 = delta3.dot(self.W2.T) * (1 - np.power(a1, 2))
                dW1 = np.dot(x_batch.T, delta2)
                db1 = np.sum(delta2, axis=0)

                # Add regularization terms
                dW2 += self.reg_lambda * self.W2
                dW1 += self.reg_lambda * self.W1

                # Gradient descent parameter update
                self.W1 += - self.learning_rate * dW1
                self.b1 += - self.learning_rate * db1
                self.W2 += - self.learning_rate * dW2
                self.b2 += - self.learning_rate * db2

                # Fit loop computation ends here ---------------------

                batch_logs.update(self._on_batch_end(x_batch, y_batch))
                callbacks.on_batch_end(batch_idx, batch_logs)

            callbacks.on_epoch_end(self.epoch, epoch_logs)
            self._on_epoch_end()

    def predict(self, x):
        W1, b1, W2, b2 = self.W1, self.b1, self.W2, self.b2
        # Forward propagation
        z1 = x.dot(W1) + b1
        a1 = np.tanh(z1)
        z2 = a1.dot(W2) + b2
        exp_scores = np.exp(z2)
        probs = exp_scores / np.sum(exp_scores, axis=1, keepdims=True)
        return self._decode_labels(probs)
  • Finally, we need three helper methods from the base _encode_labels, _decode_labels and get_params:
    def _encode_labels(self, y):
        y_copy = y.copy()
        y_copy = super(MLP, self)._encode_labels(y_copy)
        self.onehot_encoder = OneHotEncoder()
        y_encoded = self.onehot_encoder.fit_transform(y_copy.reshape(-1, 1)).toarray()
        return y_encoded

    def _decode_labels(self, y):
        y_copy = y.copy()
        y_copy = np.argmax(y_copy , axis=1)
        return super(MLP, self)._decode_labels(y_copy)
    def get_params(self, deep=True):
        out = super(MLP, self).get_params(deep=deep)
        param_names = MLP._get_param_names()
        out.update(self._get_params(param_names=param_names, deep=deep))
        return out

3- Create a test file for your model

Add a test file to tests\male\models and run to test your new model. For example, in our case, it will be a file named test_mlp.py inside tests\male\models\deep-learning folder. Please notice that the functions you add to the test file will get automatically called by the pytest testing procedure, so if the test takes a lot of time, make sure to leave it with less time consuming parameters. The best is to finish within a few seconds. Basic tests to include are simple input/output tests, gradient checking and grid search.

The file looks like this:

from __future__ import division
from __future__ import print_function
from __future__ import absolute_import

import pytest
import numpy as np

from sklearn.base import clone
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import PredefinedSplit

from male.configs import random_seed
from male.datasets import demo
from male.models.deep_learning.mlp import MLP
from male.callbacks import Display

def test_mlp_softmax():
    print("========== Test MLP for multiclass classification ==========")

    np.random.seed(random_seed())

    (x_train, y_train), (x_test, y_test) = demo.load_iris()

    print("Number of training samples = {}".format(x_train.shape[0]))
    print("Number of testing samples = {}".format(x_test.shape[0]))

    clf = MLP(model_name="MLP_softmax",
              hidden_units_list=[5],
              batch_size=16,
              num_epochs=700,
              learning_rate=0.05,
              reg_lambda=0.01,
              random_state=random_seed())

    clf.fit(x_train, y_train)
    train_err = 1.0 - clf.score(x_train, y_train)
    test_err = 1.0 - clf.score(x_test, y_test)
    print("Training error = %.4f" % train_err)
    print("Testing error = %.4f" % test_err)

Gradient Checking test

To check our model's gradients, we need to implement these Model methods: _get_loss_check_grad(), _get_grad_check_grad() that compute the loss and the gradients receptively. In addition, two helpers are needed: _roll_params() and _unroll_params().

It is better to also implement these methods from Model: get_loss() and get_grad(), to modularize the code and increase re-usability. Besides, these methods are necessary if you want to use an optimizer from MALE package. (See the notes below)

Our implementation looks like this:

def get_loss(self, x, y, *args, **kwargs):
    w1 = kwargs['w1'] if 'w1' in kwargs else self.w1
    b1 = kwargs['b1'] if 'b1' in kwargs else self.b1
    w2 = kwargs['w2'] if 'w2' in kwargs else self.w2
    b2 = kwargs['b2'] if 'b2' in kwargs else self.b2

    # Forward propagation
    z1 = x.dot(w1) + b1
    a1 = np.tanh(z1)
    z2 = a1.dot(w2) + b2
    exp_scores = np.exp(z2)
    probs = exp_scores / np.sum(exp_scores, axis=1, keepdims=True)

    # Calculate the loss
    correct_logprobs = -np.log(probs[range(x.shape[0]), np.argmax(y, axis=1)])
    data_loss = np.sum(correct_logprobs) / x.shape[0]

    # Add regularization term to loss
    data_loss += self.reg_lambda / 2.0 * (np.sum(np.square(w1)) + np.sum(np.square(w2)))
    return data_loss

def get_grad(self, x, y, *args, **kwargs):
    w1 = kwargs['w1'] if 'w1' in kwargs else self.w1
    b1 = kwargs['b1'] if 'b1' in kwargs else self.b1
    w2 = kwargs['w2'] if 'w2' in kwargs else self.w2
    b2 = kwargs['b2'] if 'b2' in kwargs else self.b2

    # Forward propagation
    z1 = x.dot(w1) + b1
    a1 = np.tanh(z1)
    z2 = a1.dot(w2) + b2
    exp_scores = np.exp(z2)
    probs = exp_scores / np.sum(exp_scores, axis=1, keepdims=True)

    # Backpropagation
    delta3 = probs
    delta3[range(x.shape[0]), np.argmax(y, axis=1)] -= 1
    delta3 /= x.shape[0]

    dw2 = a1.T.dot(delta3)
    db2 = np.sum(delta3, axis=0, keepdims=True)
    delta2 = delta3.dot(w2.T) * (1 - np.power(a1, 2))
    dw1 = np.dot(x.T, delta2)
    db1 = np.sum(delta2, axis=0)

    # Add regularization terms
    dw2 += self.reg_lambda * w2
    dw1 += self.reg_lambda * w1

    return dw1, db1, dw2, db2

def _get_loss_check_grad(self, w, x, y):
    w1, b1, w2, b2 = self._unroll_params(w)
    return self.get_loss(x, y, w1=w1, b1=b1, w2=w2, b2=b2)

def _get_grad_check_grad(self, w, x, y):
    w1, b1, w2, b2 = self._unroll_params(w)
    dw1, db1, dw2, db2 = self.get_grad(x, y, w1=w1, b1=b1, w2=w2, b2=b2)
    return np.concatenate([np.ravel(dw1), np.ravel(db1), np.ravel(dw2), np.ravel(db2)])

def _roll_params(self):
    return np.concatenate([super(MLP, self)._roll_params(),
                            np.ravel(self.w1.copy()),
                            np.ravel(self.b1.copy()),
                            np.ravel(self.w2.copy()),
                            np.ravel(self.b2.copy())])

def _unroll_params(self, params):
    parent_params = super(MLP, self)._unroll_params(params)
    parent_params = tuple([parent_params]) if not isinstance(parent_params, tuple) else parent_params
    idx = np.sum([i.size for i in parent_params], dtype=np.int32)
    w1_ = params[idx:idx + self.w1.size].reshape(self.w1.shape).copy()
    idx += self.w1.size
    b1_ = params[idx:idx + self.b1.size].reshape(self.b1.shape).copy()
    idx += self.b1.size
    w2_ = params[idx:idx + self.w2.size].reshape(self.w2.shape).copy()
    idx += self.w2.size
    b2_ = params[idx:idx + self.b2.size].reshape(self.b2.shape).copy()
    return parent_params + (w1_, b1_, w2_, b2_)    

Finally, we need to add a test function that calls the Model's check_grad() method:

def test_mlp_check_grad():
    eps = 1e-6
    num_data = 10
    num_features = 4
    num_classes = 3
    x = np.random.rand(num_data, num_features)
    y = np.random.randint(0, num_classes, num_data)

    model = MLP(model_name="checkgrad_MLP_softmax",
                task='classification',
                hidden_units_list=[5],
                reg_lambda=0.01,
                random_state=random_seed())
    assert model.check_grad(x, y) < eps

Grid Search test

Grid search test (for optimal parameter searching) looks like this:

def test_mlp_softmax_gridsearch():
    print("========== Tune parameters for MLP for multiclass classification ==========")

    np.random.seed(random_seed())

    (x_train, y_train), (x_test, y_test) = demo.load_iris()
    print("Number of training samples = {}".format(x_train.shape[0]))
    print("Number of testing samples = {}".format(x_test.shape[0]))

    x = np.vstack((x_train, x_test))
    y = np.concatenate((y_train, y_test))

    params = {'learning_rate': [0.1, 0.05, 0.01],
              'hidden_units_list': [[1], [5], [20]],
              'reg_lambda': [0.01, 0.001, 0.0001]}

    ps = PredefinedSplit(test_fold=[-1] * x_train.shape[0] + [1] * x_test.shape[0])

    clf = MLP(model_name="mlp_softmax_gridsearch",
              batch_size=16,
              num_epochs=700,
              catch_exception=True,
              random_state=random_seed())

    gs = GridSearchCV(clf, params, cv=ps, n_jobs=-1, refit=False, verbose=True)
    gs.fit(x, y)

    print("Best error {} @ params {}".format(1 - gs.best_score_, gs.best_params_))

    best_clf = clone(clf).set_params(**gs.best_params_)
    best_clf.fit(x_train, y_train)

    train_err = 1.0 - best_clf.score(x_train, y_train)
    test_err = 1.0 - best_clf.score(x_test, y_test)
    print("Training error = %.4f" % train_err)
    print("Testing error = %.4f" % test_err)
    assert abs(test_err - (1.0 - gs.best_score_)) < 1e-4

Finally the main function of the test is to call the pytest testing on all functions in the file.

if __name__ == '__main__':
    pytest.main([__file__])
    # test_mlp_softmax()
    # test_mlp_softmax_gridsearch()

Make sure to run your test file and that the results are correct as expected.

4- Push your changes to your remote branch

Push your changes to a remote branch (a new remote branch will be created with the same name the first time you push your local branch):

git add *
git commit -m "Add Multilayer Perception (MLP)*
git push -u origin mahmoud_MLP

5- Create pull request

When you reach a stage where you think that the model is ready to be merged to the main branch, you can request the team to discuss your changes and approve by creating a GitHub Pull Request.

From GitHub's main repo page, create a new pull request, setting the _base_ to the master branch, and the _compare_ to your new remote branch, then create the pull request.


Notes

  • Callbacks: MALE package has various callbacks that provide different functionalities during model fitting, like displaying weights or loss graph, early stopping, saving model checkpoints and logging. Please refer to test_glm.py on how to use the callbacks.
  • Use a MALE optimizer: Instead of implementing SGD or Adam your self for your model, you can use a ready-implemented optimizer from MALE package. Please refer to glm.py on how to use a MALE optimizer.
  • Cross validation test : You can add a cross validation test by using the cv parameter of the Model class. Please refer to test_glm.py on how to implement a cross validation test.