Kaggle
Chainer

chainerの作法 その10

概要

chainerの作法を調べてみた。
kaggleのcat&dogやってみた。

結果

image.png

サンプルコード

import glob
import chainer
import chainer.functions as F
import chainer.links as L
from chainer import training, datasets, iterators, Chain, optimizers, serializers
from chainer.training import extensions
from PIL import Image
import numpy as np


class MLP(Chain):
    def __init__(self, n_units, n_out):
        super(MLP, self).__init__(l1 = L.Linear(None, n_units), l2 = L.Linear(None, n_units), l3 = L.Linear(None, n_out))
    def __call__(self, x):
        h1 = F.relu(self.l1(x))
        h2 = F.relu(self.l2(h1))
        return self.l3(h2)

def main():
    cats = glob.glob('../cats/dogs/cat*')
    dogs = glob.glob('../cats/dogs/dog*')
    data = []
    for i in cats:
        data.append((i, 0))
    for i in dogs:
        data.append((i, 1))
    dataset = datasets.LabeledImageDataset(data)
    def transform(inputs):
        img, label = inputs
        img = img[ : 3, ...]
        img = img.astype(np.uint8)
        img = Image.fromarray(img.transpose(1, 2, 0))
        img = img.resize((28, 28), Image.BICUBIC)
        img = img.convert('L')
        img = np.array(img, dtype = np.float32).reshape(1, -1) / 255
        return img, label
    dataset = datasets.TransformDataset(dataset, transform)
    train_iter = iterators.SerialIterator(dataset, 100)
    test_iter = iterators.SerialIterator(dataset, 100, repeat = False, shuffle = False)
    model = L.Classifier(MLP(1000, 10))
    optimizer = optimizers.Adam()
    optimizer.setup(model)
    updater = training.StandardUpdater(train_iter, optimizer, device = -1)
    trainer = training.Trainer(updater, (5, 'epoch'), out = 'result')
    trainer.extend(extensions.Evaluator(test_iter, model, device = -1))
    trainer.extend(extensions.LogReport())
    trainer.extend(extensions.PrintReport(['epoch', 'main/loss', 'main/accuracy', 'elapsed_time']))
    trainer.run()
    serializers.save_npz('cats.model', model)

if __name__ == '__main__':
    main()



以上。