1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ChainerでXORを学習してみた。

Last updated at Posted at 2018-06-14

Chainer でTrainerの使い方を学ぶためにXORを学習してみました。
入力データを作るところで躓いてしまいましたが、
[ ( [ 入力1 ] , ラベル1 ) , ( [ 入力2 ] , ラベル2) , ... , ( [入力N ], ラベルN) ]
のように整形したところうまくいきました。
Iteraterで各データセットごとに分けられ、更にUpdater内のConverterで入力とラベルに分けられているようです。

import chainer
from chainer import functions as F
from chainer import links as L
import numpy as np
from chainer.training import extensions

class MLP(chainer.Chain):
    def __init__(self):
        super(MLP,self).__init__()
        with self.init_scope():
            self.Affine1 = L.Linear(2,10)
            self.Affine2 = L.Linear(10,2) # 2値分類の時は,出力層を2,n値分類の場合はn個用意する
        
    def __call__(self,x):
        z1 = F.relu(self.Affine1(x))
        z2 = self.Affine2(z1)
        return z2
    

data = np.array([ [0,0], [0,1], [1,0], [1,1]], dtype='float32')
#target = np.array([[0,1],[1,0],[1,0],[0,1]], dtype = 'int32')
target = np.array([0,1,1,0], dtype = 'int32')
#分類問題の時,教師ラベルはone hot vectorでなく,分類数のint型の値とする必要が有る。
#すなわち,2値分類であれば[0 or 1], 3値分類の場合は[0 or 1 or 2]となる

dataset = chainer.datasets.TupleDataset(data, target)
train_iter = chainer.iterators.SerialIterator(dataset,4)
test_iter = chainer.iterators.SerialIterator(dataset,4,repeat = False,shuffle = False)

model = L.Classifier(MLP())

optimizer = chainer.optimizers.Adam(0.01).setup(model)
updater = chainer.training.StandardUpdater(train_iter,optimizer)


trainer = chainer.training.Trainer(updater,(500,'epoch'),out = 'result')
trainer.extend(extensions.LogReport())
trainer.extend(extensions.PrintReport(['epoch', 'main/loss', 'main/accuracy', 'test/loss', 'test/main/accuracy','elapsed_time']))
trainer.extend(extensions.Evaluator(test_iter, model))

trainer.run()
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?