Import


In [ ]:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from sklearn import datasets, cross_validation, metrics

import chainer.functions as F
import chainer.links as L
from chainer import optimizers, Chain
from commonml.skchainer import ChainerEstimator, SoftmaxCrossEntropyClassifier

import logging
logging.basicConfig(format='%(levelname)s : %(message)s', level=logging.INFO)
logging.root.level = 20

Load dataset


In [ ]:
digits = datasets.load_digits()
X = digits.images
y = digits.target

Reshape


In [ ]:
X = X.reshape((len(X), 1, 8, 8))

Split it into train / test subsets


In [ ]:
X_train, X_test, y_train, y_test = cross_validation.train_test_split(X, y,
                                                                     test_size=0.2,
                                                                     random_state=42)

Create a classifier, train and predict.


In [ ]:
class Model(Chain):

    def __init__(self):
        super(Model, self).__init__(conv1=F.Convolution2D(1, 12, 3),
                                    l2=L.Linear(6*3*12, 10),
                                   )

    def __call__(self, x):
        h1 = F.max_pooling_2d(F.relu(self.conv1(x)), (1, 2))
        h2 = self.l2(h1)
        return h2

classifier = ChainerEstimator(model=SoftmaxCrossEntropyClassifier(Model()),
                              optimizer=optimizers.AdaGrad(lr=0.05),
                              batch_size=128,
                              device=0,
                              stop_trigger=(100, 'epoch'))

classifier.fit(X_train, y_train)
score = metrics.accuracy_score(y_test, classifier.predict(X_test))
print('Test Accuracy: {0:f}'.format(score))