Kerasでシンプルなニューラルネットワークを実装する

はじめに

パッケージ

import numpy as np
import sklearn
import matplotlib.pyplot as plt
matplotlib.rcParams['figure.figsize'] = (10.0, 8.0)
from keras.models import Sequential
from keras.layers.core import Dense, Activation, Dropout
from keras.regularizers import l1l2

moon データセット

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)

f:id:moyomot:20160718134224p:plain

モデル構築

model = Sequential()
model.add(Dense(20, input_shape=(2,), W_regularizer=l1l2(l1=0., l2=0. )))
model.add(Activation('relu'))
model.add(Dropout(0.))
model.add(Dense(2))
model.add(Activation('softmax'))
model.compile(loss='sparse_categorical_crossentropy', optimizer='Adadelta')
model.fit(X, y, validation_split=0.2, batch_size=20, nb_epoch=100, verbose=1)

描画

def plot_decision_boundary(pred_func):
    # 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)
    
def predict(model, x):
    y = model.predict(x)
    return np.argmax(y.data, axis=1)

plot_decision_boundary(lambda x: predict(model, x))

f:id:moyomot:20160718134239p:plain

circle データセット

np.random.seed(0)
X, y = sklearn.datasets.make_circles(noise=0.2, factor=0.5, random_state=1)
plt.scatter(X[:,0], X[:,1], s=40, c=y, cmap=plt.cm.Spectral)

f:id:moyomot:20160718134400p:plain

描画

f:id:moyomot:20160718134415p:plain