Implementing Multiple Layer Neural Network from Scratch

All code can be find here.

Implementing Multiple Layer Neural Network from Scratch

This post is inspired by http://www.wildml.com/2015/09/implementing-a-neural-network-from-scratch.

In this post, we will implement a multiple layer neural network from scratch. You can regard the number of layers and dimension of each layer as parameter. For example, [2, 3, 2] represents inputs with 2 dimension, one hidden layer with 3 dimension and output with 2 dimension (binary classification) (using softmax as output).

We won’t derive all the math that’s required, but I will try to give an intuitive explanation of what we are doing. I will also point to resources for you read up on the details.

Generating a dataset

Let’s start by generating a dataset we can play with. Fortunately, scikit-learn has some useful dataset generators, so we don’t need to write the code ourselves. We will go with the make_moons function.

# Generate a dataset and plot it
np.random.seed(0)
X, y = sklearn.datasets.make_moons(200, noise=0.20)
plt.scatter(X[:,0], X[:,1], s=40, c=y, cmap=plt.cm.Spectral)

The dataset we generated has two classes, plotted as red and blue points. Our goal is to train a Machine Learning classifier that predicts the correct class given the x- and y- coordinates. Note that the data is not linearly separable, we can’t draw a straight line that separates the two classes. This means that linear classifiers, such as Logistic Regression, won’t be able to fit the data unless you hand-engineer non-linear features (such as polynomials) that work well for the given dataset.

In fact, that’s one of the major advantages of Neural Networks. You don’t need to worry about feature engineering. The hidden layer of a neural network will learn features for you.

Neural Network

Neural Network Architecture

You can read this tutorial (http://cs231n.github.io/neural-networks-1/) to learn the basic concepts of neural network. Like activation functions, feed-forward computation and so on.

Because we want our network to output probabilities the activation function for the output layer will be the softmax, which is simply a way to convert raw scores to probabilities. If you’re familiar with the logistic function you can think of softmax as its generalization to multiple classes.

When you choose softmax as output, you can use cross-entropy loss (also known as negative log likelihood) as loss function. More about Loss Function can be find in http://cs231n.github.io/neural-networks-2/#losses.

Learning the Parameters

Learning the parameters for our network means finding parameters (such as (W_1, b_1, W_2, b_2)) that minimize the error on our training data (loss function).

We can use gradient descent to find the minimum and I will implement the most vanilla version of gradient descent, also called batch gradient descent with a fixed learning rate. Variations such as SGD (stochastic gradient descent) or minibatch gradient descent typically perform better in practice. So if you are serious you’ll want to use one of these, and ideally you would also decay the learning rate over time.

The key of gradient descent method is how to calculate the gradient of loss function by the parameters. One approach is called Back Propagation. You can learn it more from http://colah.github.io/posts/2015-08-Backprop/ and http://cs231n.github.io/optimization-2/.

Implementation

We start by given the computation graph of neural network.


In the computation graph, you can see that it contains three components (gate, layer and output), there is two kinds of gate (multiply and add), and you can use tanh layer and softmax output.

gate, layer and output can all be seen as operation unit of computation graph, so they will implement the inner derivatives of their inputs (we call it backward), and use chain rule according to the computation graph. You can see the following figure for nice explanation.

gate.py

import numpy as np

class MultiplyGate:
    def forward(self,W, X):
        return np.dot(X, W)

    def backward(self, W, X, dZ):
        dW = np.dot(np.transpose(X), dZ)
        dX = np.dot(dZ, np.transpose(W))
        return dW, dX

class AddGate:
    def forward(self, X, b):
        return X + b

    def backward(self, X, b, dZ):
        dX = dZ * np.ones_like(X)
        db = np.dot(np.ones((1, dZ.shape[0]), dtype=np.float64), dZ)
        return db, dX

layer.py

import numpy as np

class Sigmoid:
    def forward(self, X):
        return 1.0 / (1.0 + np.exp(-X))

    def backward(self, X, top_diff):
        output = self.forward(X)
        return (1.0 - output) * output * top_diff

class Tanh:
    def forward(self, X):
        return np.tanh(X)

    def backward(self, X, top_diff):
        output = self.forward(X)
        return (1.0 - np.square(output)) * top_diff

output.py

import numpy as np

class Softmax:
    def predict(self, X):
        exp_scores = np.exp(X)
        return exp_scores / np.sum(exp_scores, axis=1, keepdims=True)

    def loss(self, X, y):
        num_examples = X.shape[0]
        probs = self.predict(X)
        corect_logprobs = -np.log(probs[range(num_examples), y])
        data_loss = np.sum(corect_logprobs)
        return 1./num_examples * data_loss

    def diff(self, X, y):
        num_examples = X.shape[0]
        probs = self.predict(X)
        probs[range(num_examples), y] -= 1
        return probs

We can implement out neural network by a class Model and initialize the parameters in the __init__ function. You can pass the parameter layers_dim = [2, 3, 2], which represents inputs with 2 dimension, one hidden layer with 3 dimension and output with 2 dimension

class Model:
    def __init__(self, layers_dim):
        self.b = []
        self.W = []
        for i in range(len(layers_dim)-1):
            self.W.append(np.random.randn(layers_dim[i], layers_dim[i+1]) / np.sqrt(layers_dim[i]))
            self.b.append(np.random.randn(layers_dim[i+1]).reshape(1, layers_dim[i+1]))

First let’s implement the loss function we defined above. It is just a forward propagation computation of out neural network. We use this to evaluate how well our model is doing:

def calculate_loss(self, X, y):
    mulGate = MultiplyGate()
    addGate = AddGate()
    layer = Tanh()
    softmaxOutput = Softmax()

    input = X
    for i in range(len(self.W)):
        mul = mulGate.forward(self.W[i], input)
        add = addGate.forward(mul, self.b[i])
        input = layer.forward(add)

    return softmaxOutput.loss(input, y)

We also implement a helper function to calculate the output of the network. It does forward propagation as defined above and returns the class with the highest probability.

def predict(self, X):
    mulGate = MultiplyGate()
    addGate = AddGate()
    layer = Tanh()
    softmaxOutput = Softmax()

    input = X
    for i in range(len(self.W)):
        mul = mulGate.forward(self.W[i], input)
        add = addGate.forward(mul, self.b[i])
        input = layer.forward(add)

    probs = softmaxOutput.predict(input)
    return np.argmax(probs, axis=1)

Finally, here comes the function to train our Neural Network. It implements batch gradient descent using the backpropagation algorithms we have learned above.

def train(self, X, y, num_passes=20000, epsilon=0.01, reg_lambda=0.01, print_loss=False):
    mulGate = MultiplyGate()
    addGate = AddGate()
    layer = Tanh()
    softmaxOutput = Softmax()

    for epoch in range(num_passes):
        # Forward propagation
        input = X
        forward = [(None, None, input)]
        for i in range(len(self.W)):
            mul = mulGate.forward(self.W[i], input)
            add = addGate.forward(mul, self.b[i])
            input = layer.forward(add)
            forward.append((mul, add, input))

        # Back propagation
        dtanh = softmaxOutput.diff(forward[len(forward)-1][2], y)
        for i in range(len(forward)-1, 0, -1):
            dadd = layer.backward(forward[i][1], dtanh)
            db, dmul = addGate.backward(forward[i][0], self.b[i-1], dadd)
            dW, dtanh = mulGate.backward(self.W[i-1], forward[i-1][2], dmul)
            # Add regularization terms (b1 and b2 don't have regularization terms)
            dW += reg_lambda * self.W[i-1]
            # Gradient descent parameter update
            self.b[i-1] += -epsilon * db
            self.W[i-1] += -epsilon * dW

        if print_loss and epoch % 1000 == 0:
            print("Loss after iteration %i: %f" %(epoch, self.calculate_loss(X, y)))

A network with a hidden layer of size 3

Let’s see what happens if we train a network with a hidden layer size of 3.

import matplotlib.pyplot as plt
import numpy as np
import sklearn
import sklearn.datasets
import sklearn.linear_model
import mlnn
from utils import plot_decision_boundary

# Generate a dataset and plot it
np.random.seed(0)
X, y = sklearn.datasets.make_moons(200, noise=0.20)
plt.scatter(X[:,0], X[:,1], s=40, c=y, cmap=plt.cm.Spectral)
plt.show()

layers_dim = [2, 3, 2]

model = mlnn.Model(layers_dim)
model.train(X, y, num_passes=20000, epsilon=0.01, reg_lambda=0.01, print_loss=True)

# Plot the decision boundary
plot_decision_boundary(lambda x: model.predict(x), X, y)
plt.title("Decision Boundary for hidden layer size 3")
plt.show()

This looks pretty good. Our neural networks was able to find a decision boundary that successfully separates the classes.

The plot_decision_boundary function is referenced by http://www.wildml.com/2015/09/implementing-a-neural-network-from-scratch.

import matplotlib.pyplot as plt
import numpy as np

# Helper function to plot a decision boundary.
def plot_decision_boundary(pred_func, X, y):
    # Set min and max values and give it some padding
    x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5
    y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5
    h = 0.01
    # Generate a grid of points with distance h between them
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
    # Predict the function value for the whole gid
    Z = pred_func(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)
    # Plot the contour and training examples
    plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral)
    plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Spectral)

Further more

  1. Instead of batch gradient descent, use minibatch gradient to train the network. Minibatch gradient descent typically performs better in practice (more info).
  2. We used a fixed learning rate epsilon for gradient descent. Implement an annealing schedule for the gradient descent learning rate (more info).
  3. We used a tanh activation function for our hidden layer. Experiment with other activation functions (more info).
  4. Extend the network from two to three classes. You will need to generate an appropriate dataset for this.
  5. Try some other Parameter updates method, like Momentum update, Nesterov momentum, Adagrad, RMSprop and Adam(more info).
  6. Some other tricks of training neural network can be find http://cs231n.github.io/neural-networks-2 and http://cs231n.github.io/neural-networks-3, like dropout reglarization, batch normazation, Gradient checks and Model Ensembles.

Some useful resources

  1. http://cs231n.github.io/
  2. http://www.wildml.com/2015/09/implementing-a-neural-network-from-scratch
  3. http://colah.github.io/posts/2015-08-Backprop/
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末徽鼎,一起剝皮案震驚了整個(gè)濱河市盛末,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌否淤,老刑警劉巖悄但,帶你破解...
    沈念sama閱讀 219,366評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異石抡,居然都是意外死亡檐嚣,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,521評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門啰扛,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)嚎京,“玉大人,你說我怎么就攤上這事侠讯⊥诓兀” “怎么了?”我有些...
    開封第一講書人閱讀 165,689評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵厢漩,是天一觀的道長(zhǎng)膜眠。 經(jīng)常有香客問我,道長(zhǎng)溜嗜,這世上最難降的妖魔是什么宵膨? 我笑而不...
    開封第一講書人閱讀 58,925評(píng)論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮炸宵,結(jié)果婚禮上辟躏,老公的妹妹穿的比我還像新娘。我一直安慰自己土全,他們只是感情好捎琐,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,942評(píng)論 6 392
  • 文/花漫 我一把揭開白布会涎。 她就那樣靜靜地躺著,像睡著了一般瑞凑。 火紅的嫁衣襯著肌膚如雪末秃。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,727評(píng)論 1 305
  • 那天籽御,我揣著相機(jī)與錄音练慕,去河邊找鬼。 笑死技掏,一個(gè)胖子當(dāng)著我的面吹牛铃将,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播哑梳,決...
    沈念sama閱讀 40,447評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼劲阎,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了涧衙?” 一聲冷哼從身側(cè)響起哪工,我...
    開封第一講書人閱讀 39,349評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤奥此,失蹤者是張志新(化名)和其女友劉穎弧哎,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體稚虎,經(jīng)...
    沈念sama閱讀 45,820評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡撤嫩,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,990評(píng)論 3 337
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了蠢终。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片序攘。...
    茶點(diǎn)故事閱讀 40,127評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖寻拂,靈堂內(nèi)的尸體忽然破棺而出程奠,到底是詐尸還是另有隱情,我是刑警寧澤祭钉,帶...
    沈念sama閱讀 35,812評(píng)論 5 346
  • 正文 年R本政府宣布瞄沙,位于F島的核電站,受9級(jí)特大地震影響慌核,放射性物質(zhì)發(fā)生泄漏距境。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,471評(píng)論 3 331
  • 文/蒙蒙 一垮卓、第九天 我趴在偏房一處隱蔽的房頂上張望垫桂。 院中可真熱鬧,春花似錦粟按、人聲如沸诬滩。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,017評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)疼鸟。三九已至蒙挑,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間愚臀,已是汗流浹背忆蚀。 一陣腳步聲響...
    開封第一講書人閱讀 33,142評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留姑裂,地道東北人馋袜。 一個(gè)月前我還...
    沈念sama閱讀 48,388評(píng)論 3 373
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像舶斧,于是被迫代替她去往敵國(guó)和親欣鳖。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,066評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容