Pylearn2を使ったDeep Learningの実装(多層パーセプトロン編)
以前の記事でも取り上げましたが、Deep Learningは今年に入ってさらに話題となっています。
実装する場合にまず参考となるのが公式の公式のチュートリアルページです。
このページに書かれている内容については一度理解する必要があるのですが、このページでも利用されているtheanoというライブラリは、勾配を求める部分など、Deep Learningを実装する際の関数集のようなものになっており、このページを参考に自分のデータへ適用させると、変更点が多いためコードが長くなってしまいます。
そこで、今回の記事からは、Deep Learningの代表的なアルゴリズムが実装されたライブラリである、Pylearn2の利用の仕方についてまとめたいと思います。
今回はその準備として、多層パーセプトロン(Multi Layer Perceptron)で、XORの分類を行うコードを紹介したいと思います。
コードはこちらのgithubリポジトリにもありますが、以下のようになっています。
【XOR.py】
# coding: utf-8 import sys, theano sys.path.append('/home/fujikawa/lib/python/other/pylearn2/pylearn2') from pylearn2.datasets.dense_design_matrix import DenseDesignMatrix import numpy as np from random import randint class XOR(DenseDesignMatrix): def __init__(self): self.class_names = ['0', '1'] X = [[randint(0, 1), randint(0, 1)] for _ in range(1000)] y = [] for a, b in X: if a + b == 1: y.append([0, 1]) else: y.append([1, 0]) X = np.array(X) y = np.array(y) super(XOR, self).__init__(X=X, y=y) def test(self, model): print '####### TEST #######' print 'Input: [0, 0] -> Predict: ' + str(model.fprop(theano.shared(np.array([[0, 0]]), name='inputs')).eval()) + ' (Correct: [1, 0])' print 'Input: [0, 1] -> Predict: ' + str(model.fprop(theano.shared(np.array([[0, 1]]), name='inputs')).eval()) + ' (Correct: [0, 1])' print 'Input: [1, 0] -> Predict: ' + str(model.fprop(theano.shared(np.array([[1, 0]]), name='inputs')).eval()) + ' (Correct: [0, 1])' print 'Input: [1, 1] -> Predict: ' + str(model.fprop(theano.shared(np.array([[1, 1]]), name='inputs')).eval()) + ' (Correct: [1, 0])'
【MLP.py】
# coding: utf-8 import theano, sys sys.path.append('/home/fujikawa/lib/python/other/pylearn2/pylearn2') from pylearn2.models import mlp from pylearn2.training_algorithms import sgd from pylearn2.termination_criteria import EpochCounter from pylearn2.train import Train import numpy as np from XOR import XOR ############################### #### Setting for dataset #### ############################### dataset = XOR() ########################## #### Setting for NN #### ########################## # create layers hidden_layer = mlp.Sigmoid(layer_name='hidden', dim=3, irange=.1, init_bias=1.) output_layer = mlp.Softmax(2, 'output', irange=.1) layers = [hidden_layer, output_layer] model = mlp.MLP(layers, nvis=2) #################### #### Training #### #################### train = Train( dataset, model, algorithm=sgd.SGD(learning_rate=.05, batch_size=10, termination_criterion=EpochCounter(400)) ) train.main_loop() ################# ### Testing ### ################# dataset.test(model)
上記のように、少ないコード量で実装ができ、内部的にはtheanoが利用されているので、環境を整えればGPUの利用等も可能であるのがこのライブラリの大きな利点です。
ただ、日本語はおろか、英語のドキュメントも少ないため、こちらの実装の中身を見て理解する必要があります。
- 作者: 岡谷貴之
- 出版社/メーカー: 講談社
- 発売日: 2015/04/08
- メディア: 単行本(ソフトカバー)
- この商品を含むブログ (6件) を見る