In [1]:
# From: http://rolisz.ro/2013/04/18/neural-networks-in-python/

In [14]:
import numpy as np

def tanh(x):
    return np.tanh(x)

def tanh_deriv(x):
    return 1.0 - x**2

def logistic(x):
    return 1/(1 + np.exp(-x))

def logistic_derivative(x):
    return logistic(x)*(1-logistic(x))

class NeuralNetwork:

    def __init__(self, layers, activation='tanh'):
        """
        :param layers: A list containing the number of units in each layer. Should be at least two values
        :param activation: The activation function to be used. Can be "logistic" or "tanh"
        """
        if activation == 'logistic':
            self.activation = logistic
            self.activation_deriv = logistic_derivative
        elif activation == 'tanh':
            self.activation = tanh
            self.activation_deriv = tanh_deriv

        self.weights = []
        for i in range(1, len(layers) - 1):
            self.weights.append((2*np.random.random((layers[i - 1] + 1, layers[i] + 1))-1)*0.25)
        self.weights.append((2*np.random.random((layers[i] + 1, layers[i + 1]))-1)*0.25)
        
    def fit(self, X, y, learning_rate=0.2, epochs=10000):
        X = np.atleast_2d(X)
        temp = np.ones([X.shape[0], X.shape[1]+1])
        temp[:, 0:-1] = X  # adding the bias unit to the input layer
        X = temp
        y = np.array(y)

        for k in range(epochs):
            i = np.random.randint(X.shape[0])
            a = [X[i]]

            for l in range(len(self.weights)):
                    a.append(self.activation(np.dot(a[l], self.weights[l])))
            error = y[i] - a[-1]
            deltas = [error * self.activation_deriv(a[-1])]

            for l in range(len(a) - 2, 0, -1): # we need to begin at the second to last layer
                deltas.append(deltas[-1].dot(self.weights[l].T)*self.activation_deriv(a[l]))
            deltas.reverse()
            for i in range(len(self.weights)):
                layer = np.atleast_2d(a[i])
                delta = np.atleast_2d(deltas[i])
                self.weights[i] += learning_rate * layer.T.dot(delta)
    
    def predict(self, x):
        x = np.array(x)
        temp = np.ones(x.shape[0]+1)
        temp[0:-1] = x
        a = temp
        for l in range(0, len(self.weights)):
            a = self.activation(np.dot(a, self.weights[l]))
        return a

In [15]:
nn = NeuralNetwork([2,2,1], 'tanh')
    X = np.array([[0, 0],
                  [0, 1],
                  [1, 0],
                  [1, 1]])
    y = np.array([0, 1, 1, 0])
    nn.fit(X, y)
    for i in [[0, 0], [0, 1], [1, 0], [1,1]]:
        print(i,nn.predict(i))


([0, 0], array([ 0.00046681]))
([0, 1], array([ 0.98814349]))
([1, 0], array([ 0.9857397]))
([1, 1], array([-0.00042141]))

In [16]:
#now try sklearn digits dataset
import numpy as np
from sklearn.datasets import load_digits
from sklearn.metrics import confusion_matrix, classification_report
from sklearn.preprocessing import LabelBinarizer
from sklearn.cross_validation import train_test_split
#from NeuralNetwork import NeuralNetwork

digits = load_digits()
X = digits.data
y = digits.target
X -= X.min()     # normalize the values to bring them into the range 0-1
X /= X.max()

nn = NeuralNetwork([64,100,10],'tanh')
X_train, X_test, y_train, y_test = train_test_split(X, y)
labels_train = LabelBinarizer().fit_transform(y_train)
labels_test = LabelBinarizer().fit_transform(y_test)

nn.fit(X_train,labels_train,epochs=30000)
predictions = []
for i in range(X_test.shape[0]):
    o = nn.predict(X_test[i] )
    predictions.append(np.argmax(o))
print confusion_matrix(y_test,predictions)
print classification_report(y_test,predictions)


[[ 2  0 23  0  1  0  0  0  2 13]
 [ 0 38  1  0  0  1  0  0  8  2]
 [ 0  0 33  0  0  0  0  0  0  0]
 [ 0  0  7 24  0  0  0  0 11  2]
 [ 0  0  0  0 39  0  0  0  0  1]
 [ 0  0  0  0  0 36  1  0  2  5]
 [ 0  1  0  0  0  0 47  0  1  0]
 [ 0  0  1  0  5  0  0 52  1  0]
 [ 0  0  0  0  0  1  0  0 42  0]
 [ 0  0  0  0  0  0  0  0  6 41]]
             precision    recall  f1-score   support

          0       1.00      0.05      0.09        41
          1       0.97      0.76      0.85        50
          2       0.51      1.00      0.67        33
          3       1.00      0.55      0.71        44
          4       0.87      0.97      0.92        40
          5       0.95      0.82      0.88        44
          6       0.98      0.96      0.97        49
          7       1.00      0.88      0.94        59
          8       0.58      0.98      0.72        43
          9       0.64      0.87      0.74        47

avg / total       0.86      0.79      0.76       450


In [17]:
# now lets try with logistic function
nn = NeuralNetwork([64,100,10],'logistic')
X_train, X_test, y_train, y_test = train_test_split(X, y)
labels_train = LabelBinarizer().fit_transform(y_train)
labels_test = LabelBinarizer().fit_transform(y_test)

nn.fit(X_train,labels_train,epochs=30000)
predictions = []
for i in range(X_test.shape[0]):
    o = nn.predict(X_test[i] )
    predictions.append(np.argmax(o))
print confusion_matrix(y_test,predictions)
print classification_report(y_test,predictions)


[[38  0  0  0  0  0  0  0  0  0]
 [ 0 41  0  0  0  0  0  0  0  1]
 [ 0  0 39  0  0  0  0  0  0  0]
 [ 0  0  0 41  0  2  0  0  1  2]
 [ 0  0  0  0 52  0  0  0  0  2]
 [ 0  0  0  0  0 41  0  0  0  2]
 [ 0  1  0  0  0  0 53  0  0  0]
 [ 0  0  0  0  0  0  0 39  0  0]
 [ 0  5  0  0  0  0  0  0 46  0]
 [ 0  0  0  0  1  1  0  0  0 42]]
             precision    recall  f1-score   support

          0       1.00      1.00      1.00        38
          1       0.87      0.98      0.92        42
          2       1.00      1.00      1.00        39
          3       1.00      0.89      0.94        46
          4       0.98      0.96      0.97        54
          5       0.93      0.95      0.94        43
          6       1.00      0.98      0.99        54
          7       1.00      1.00      1.00        39
          8       0.98      0.90      0.94        51
          9       0.86      0.95      0.90        44

avg / total       0.96      0.96      0.96       450


In [ ]: