teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

edit

2017/12/10 10:57

投稿

mkgrei
mkgrei

スコア8562

answer CHANGED
@@ -1,4 +1,61 @@
1
+ 修正:このコメントは正しくありません。
1
- ytrain.shape = (2, 1)
2
+ __(ytrain.shape = (2, 1)
2
3
 
3
4
  l2 = L.Linear(100,2)
4
- が相容れないせいではないでしょうか。
5
+ が相容れないせいではないでしょうか。)__
6
+
7
+ 追記:
8
+ SoftmaxCrossEntropyはnp.int32を教師データに要求します。
9
+ tに代入される部分を.astype('i')に変換しておく必要があります。
10
+ https://docs.chainer.org/en/stable/reference/generated/chainer.functions.softmax_cross_entropy.html
11
+ 例を見ると型の変換がありました。
12
+
13
+ ---
14
+
15
+ ```python
16
+ import numpy as np
17
+
18
+ from chainer import Link, Chain, ChainList
19
+ import chainer.functions as F
20
+ import chainer.links as L
21
+ from chainer import optimizers, datasets, iterators, training
22
+ from chainer.training import extensions
23
+
24
+ class MyChain(Chain):
25
+ def __init__(self):
26
+ super(MyChain, self).__init__(
27
+ cn1=L.Convolution2D(3, 8, (2, 3), stride=1, pad=1),
28
+ cn2=L.Convolution2D(8, 16, (2, 3), stride=1, pad=1),
29
+ l1=L.Linear(160, 100),
30
+ l2=L.Linear(100 ,2)
31
+ )
32
+
33
+ def __call__(self, x, t):
34
+ pt = self.fwd(x)
35
+ return F.softmax_cross_entropy(pt, t)
36
+
37
+ def fwd(self, x):
38
+ h1 = F.max_pooling_2d(F.relu(self.cn1(x)), 2) #8*3*10
39
+ h2 = F.max_pooling_2d(F.relu(self.cn2(h1)), 2) #16*2*5
40
+ h3 = F.dropout(F.relu(self.l1(h2)))
41
+ h4 = self.l2(h3)
42
+ return h4
43
+
44
+ xtrain = np.random.random((2, 3, 5, 20)).astype('f')
45
+ ytrain = np.random.randint(2, size=(2, 1))
46
+ ytrain = np.hstack((ytrain, 1-ytrain))
47
+ ytrain = np.argmax(ytrain, axis=1).astype('i')
48
+
49
+ model = MyChain()
50
+ optimizer = optimizers.Adam()
51
+ optimizer.setup(model)
52
+
53
+ train = datasets.tuple_dataset.TupleDataset(xtrain, ytrain)
54
+
55
+ iterator = iterators.SerialIterator(train, 2)
56
+ updater = training.StandardUpdater(iterator, optimizer)
57
+ trainer = training.Trainer(updater, (1000, 'epoch'))
58
+
59
+ trainer.extend(extensions.ProgressBar())
60
+ trainer.run()
61
+ ```