質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

0回答

1274閲覧

theanoを使ってニューラルネットワーク の実装でハマりました。

Tsukuni

総合スコア34

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

0クリップ

投稿2018/05/26 06:22

python,機械学習初心者です。
ニューラルネットワークを実装してあるコードをもらい、それを別のものに適応しようと思い変更を加えているのですが、詰まってしまいました。
入力データの設定がおかしいのかなと思ったのですが、わかりませんでした。わかる方がいれば教えていただけると嬉しいです。

発生している問題・エラーメッセージ

Traceback (most recent call last): File "homework.py", line 207, in <module> loss = func_update(x,t) File "/Users/t/.pyenv/versions/anaconda-2.1.0/lib/python2.7/site-packages/theano/compile/function_module.py", line 917, in __call__ storage_map=getattr(self.fn, 'storage_map', None)) File "/Users/t/.pyenv/versions/anaconda-2.1.0/lib/python2.7/site-packages/theano/gof/link.py", line 325, in raise_with_op reraise(exc_type, exc_value, exc_trace) File "/Users/t/.pyenv/versions/anaconda-2.1.0/lib/python2.7/site-packages/theano/compile/function_module.py", line 903, in __call__ self.fn() if output_subset is None else\ ValueError: number of rows in x (1) does not match length of y (3) Apply node that caused the error: CrossentropySoftmaxArgmax1HotWithBias(Dot22.0, b, t) Toposort index: 15 Inputs types: [TensorType(float64, matrix), TensorType(float64, vector), TensorType(int64, vector)] Inputs shapes: [(1, 3), (3,), (3,)] Inputs strides: [(24, 8), (8,), (8,)] Inputs values: [array([[ 0.29324024, -0.40678503, 0.03681703]]), array([0., 0., 0.]), array([1, 0, 0])] Outputs clients: [[Sum{acc_dtype=float64}(CrossentropySoftmaxArgmax1HotWithBias.0)], [CrossentropySoftmax1HotWithBiasDx(Elemwise{Inv}[(0, 0)].0, CrossentropySoftmaxArgmax1HotWithBias.1, t)], []] HINT: Re-running with most Theano optimization disabled could give you a back-trace of when this node was created. This can be done with by setting the Theano flag 'optimizer=fast_compile'. If that does not work, Theano optimizations can be disabled with 'optimizer=None'. HINT: Use the Theano flag 'exception_verbosity=high' for a debugprint and storage map footprint of this apply node.

入力と教師データ

python

1#data_x 2[[5.1 3.5 1.4 0.2] 3 [4.9 3. 1.4 0.2] 4 ...... 5 [4.7 3.2 1.3 0.2] 6 [4.6 3.1 1.5 0.2]] 7#data_t 8[[0 0 1] 9 [0 1 0] 10 ..... 11 [0 0 1] 12 [0 0 1]]

該当のソースコード

python

1 2from __future__ import print_function 3 4import numpy 5 6import theano 7import theano.tensor as T 8import csv 9 10class Linear(object): 11 12 13 def __init__(self, n_in, n_out): 14 15 # モデルパラメータの初期値を設定 16 17 W_values = numpy.asarray(numpy.random.normal( 18 0, numpy.sqrt(1. / n_in), (n_in, n_out)), 19 dtype=theano.config.floatX) 20 b_values = numpy.zeros((n_out,), dtype=theano.config.floatX) 21 22 self.W = theano.shared(value=W_values, name='W') 23 self.b = theano.shared(value=b_values, name='b') 24 25 def __call__(self, x): 26 return T.dot(x, self.W) + self.b 27 28# MLP モデルを定義しよう 29 30class MnistMLP(object): 31 32 # モデルパラメータ (重み行列やバイアスベクトル) 33 34 def __init__(self, n_in, n_units, n_out): 35 self.l1=Linear(n_in, n_units) 36 self.l2=Linear(n_units, n_units) 37 self.l3=Linear(n_units, n_out) 38 39 def __call__(self, x): 40 h1 = T.nnet.sigmoid(self.l1(x)) 41 h2 = T.nnet.sigmoid(self.l2(h1)) 42 return T.nnet.softmax(self.l3(h2)) 43# 設定変数 44n_epoch = 10 45n_units = 5 46lr = 0.1 47 48data = numpy.array([[ float(elm) for elm in v] for v in csv.reader(open("fisheriris.csv", "r"))]) 49 50data_x,data_t1= numpy.hsplit(data,[4]) 51 52data_t = numpy.zeros((data_t1.shape[0],3),dtype = int) 53for i in range(0,data_t.shape[0]): 54 if data_t1[i] == 1: 55 data_t[i,0] = 1 56 elif data_t1[i] == 2: 57 data_t[i,1] = 1 58 else: 59 data_t[i,2] = 1 60 61N_data = data_t.shape[0] 62print(data_t) 63print(data_x) 64 65 66x = T.dmatrix('x') 67t = T.lvector('t') 68 69# モデルを定義しよう 70 71model = MnistMLP(4,n_units,3) 72 73 74y = model(x) 75 76equ_loss = T.mean(T.nnet.categorical_crossentropy(y,t)) 77 78 79equ_grad = T.grad(equ_loss,[model.l1.W, model.l1.b, 80 model.l2.W, model.l2.b, 81 model.l3.W, model.l3.b]) 82 83 84equ_update=[(model.l1.W, model.l1.W - lr*equ_grad[0]), 85 (model.l1.b, model.l1.b - lr*equ_grad[1]), 86 (model.l2.W, model.l2.W - lr*equ_grad[2]), 87 (model.l2.b, model.l2.b - lr*equ_grad[3]), 88 (model.l3.W, model.l3.W - lr*equ_grad[4]), 89 (model.l3.b, model.l3.b - lr*equ_grad[5])] 90 91 92func_update=theano.function(inputs=[x,t],outputs=equ_loss,updates=equ_update) 93 94 95func_loss=theano.function(inputs=[x,t],outputs=equ_loss) 96 97equ_acc=(1.0-T.mean(T.neq(T.argmax(y,axis=1),t))) 98 99func_acc=theano.function(inputs=[x,t],outputs=equ_acc) 100 101 102for epoch in range(1, n_epoch + 1): 103 print('epoch', epoch) 104 105 sum_loss = 0.0 106 sum_accuracy = 0.0 107 perm = numpy.random.permutation(N_data) 108 109 for i in range(0, N_data): 110 111 x = numpy.asarray([data_x[i]]) 112 t = numpy.asarray(data_t[i]) 113 114 115 loss = func_update(x,t) 116 117 118 119 acc = func_acc(x,t) 120 121 122 sum_loss += float(loss) * len(t) 123 sum_accuracy += float(acc) * len(t) 124 125 126 print('train mean loss={}, accuracy={}'.format( 127 sum_loss / N_data, sum_accuracy / N_data)) 128 129 130sum_loss = 0.0 131sum_accuracy = 0.0 132for i in range(0, N_data, batchsize): 133 134 x = numpy.asarray(data_x[perm[i:i + batchsize]]) 135 t = data_t[perm[i:i + batchsize]] 136 137 loss = func_loss(x,t) 138 139 acc = func_acc(x,t) 140 141 sum_loss += float(loss) * len(t) 142 sum_accuracy += float(acc) * len(t) 143 144print('test mean loss={}, accuracy={}'.format( 145 sum_loss / N_data, sum_accuracy / N_data)) 146 147

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだ回答がついていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問