質問するログイン新規登録
Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Python

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

Q&A

解決済

3回答

1028閲覧

tensorflowでのalexnetの実装で精度が変化しない

aika_y

総合スコア8

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Python

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

0グッド

3クリップ

投稿2017/11/08 07:07

編集2017/11/08 07:49

0

3

###前提・実現したいこと
こんにちは。
趣味で画像認識を勉強しているものです。
「tensorflowでゆるゆりの製作会社を判定してみた」(http://mobiles-han.blogspot.jp/2017/01/tensorflow_13.html)のhanさんのコードを参考にalex-netの実装を行い、画像の識別をしようとしているのですが、問題が発生しました。

原因が自分では全くわからず、1ヶ月ほど悩んでおります。
お手数おかけしますが、どうかご教授願います。

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

accuracyが一定の値から全く変化しなく、結果もひとつのラベルしか返さない状態が続いています。

step 0, training accuracy 0.106504 step 1, training accuracy 0.106504 step 2, training accuracy 0.106504 ………… test accuracy 0.1 #ここからラベルの表示 0 0 0 0 …………

###試したこと
学習率を0.0001〜0.009まで変化させながら実行してみましたが、実行結果にあまり変化がでませんでした。

###補足情報(言語/FW/ツール等のバージョンなど)
OS :Ubuntu 16.04
使用言語 :python 3.5.2
使用ライブラリ:tensorflow 1.2.1
GPU :geforce GTX 1080
画像枚数 :1330枚(訓練用1230、テスト用100枚)

コードについてのなのですが、文字数制限でのせることができなかったのでコメントにて載せます。

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

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

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

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

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

guest

回答3

0

ベストアンサー

確実に学習したというモデルを上げておきます。
手元のパソコンにとってAlexNetは非常に重いので、いたるところでパラメータが縮小されています。
少なくとも有名なKaggleの犬猫分類に対して判定精度99%(追記:教師データに対して100%に過学習できるほど学習できる……このパラメータではテストデータに対しては70%程度ですね。)を超えることができます。
犬猫分類のパラメータなので、2値分類です。
多クラスに使う場合は修正を忘れずに。

詳しくはコードを追っていただくとして、ポイントをいくつかだけ。
0. おそらくオリジナルのコードで一番問題となったのは教師データをシャッフルしていないことだと思います。エポックごとにシャッフルすべきです。

  1. 学習ではlossが小さくなるように重みを更新します。なので、学習率次第ではaccuracyははじめのうちは変化しません。それに対して、lossが先が変動します。(学習している証拠です。)これを出力すべきです。今回の場合はtensorflowの泥臭いところを全部自分で書きたい(のかもしれない)ので、もとのコードに修正を加えましたが、Kerasなどの高度なライブラリを使うことで、デフォルトでaccuracyとlossの両方を出力させることができます。
  2. cross_entropyの計算が正しくありませんでした。本家のチュートリアルを参考にするとよいのですが、reduction_indices=[1]が欠けているせいで、一定の精度以上学習できません。(追記:勾配に対してclipをつけろと言われていますね。またyの値のクリッピングも学習にバイアスをあたえるので、ない方がよいです。理由はyが1以上であれば、みなlossがおなじになるので重みを更新しようがないことが挙げられます。)
  3. lossを出力させていないことにもつながりますが、重みの初期化次第ではlossがnanになることがあります。このような場合も学習することはできません。(追記:lossがnanになるのはyの値をclipしていないことによるようですね。)
  4. 画像取り込みのpathに関するバグを修正しました。
  5. 以前の回答でも指摘した、conv2d_firstのカッコの閉じる場所を修正しました。
  6. 以前の回答の最後のコードのインデントが正しくなかった箇所を修正しました。

python

1import sys 2import cv2 3import math 4import numpy as np 5import tensorflow as tf 6import tensorflow.python.platform 7 8NUM_CLASSES = 2 9IMAGE_SIZE = 32 10IMAGE_PIXELS = IMAGE_SIZE*IMAGE_SIZE*3 11 12flags = tf.app.flags 13FLAGS = flags.FLAGS 14flags.DEFINE_string('train', 'train.txt', 'File name of train data') 15flags.DEFINE_string('test', 'test.txt', 'File name of train data') 16flags.DEFINE_string('train_dir', '/tmp/data', 'Directory to put the training data.') 17flags.DEFINE_integer('max_steps', 50, 'Number of steps to run trainer.') 18flags.DEFINE_integer('batch_size', 12, 'Batch size. Must divide evenly into the dataset sizes.') 19flags.DEFINE_float('learning_rate', 0.001, 'Initial learning rate.') 20 21def inference(images_placeholder, keep_prob): 22 def weight_variable(shape, num): 23 initial = tf.truncated_normal(shape, stddev=0.1, mean=0.) 24 return (tf.Variable(initial).initialized_value()) 25 26 def bias_variable(shape): 27 initial = tf.constant(0.0, shape=shape) 28 return (tf.Variable(initial).initialized_value()) 29 30 def conv2d_first(x, W): 31 return (tf.nn.conv2d(x, W, strides=[1, 4, 4, 1], padding='SAME')) 32 33 def conv2d(x,W): 34 return (tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')) 35 36 def max_pool_2x2(x): 37 return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], 38 strides=[1, 2, 2, 1], padding='SAME') 39 40 x_image = tf.reshape(images_placeholder, [-1, IMAGE_SIZE, IMAGE_SIZE, 3]) 41 42 with tf.name_scope('conv1') as scope: 43 W_conv1 = weight_variable([2, 2, 3, 32], IMAGE_SIZE*IMAGE_SIZE) 44 b_conv1 = bias_variable([32]) 45 h_conv1 = tf.nn.relu(conv2d_first(x_image, W_conv1) + b_conv1) 46 47 with tf.name_scope('pool1') as scope: 48 h_pool1 = max_pool_2x2(tf.nn.local_response_normalization(h_conv1)) 49 50 with tf.name_scope('conv2') as scope: 51 W_conv2 = weight_variable([2, 2, 32, 64], 96) 52 b_conv2 = bias_variable([64]) 53 h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) 54 55 with tf.name_scope('pool2') as scope: 56 h_pool2 = max_pool_2x2(tf.nn.local_response_normalization(h_conv2)) 57 58 with tf.name_scope('conv3') as scope: 59 W_conv3 = weight_variable([2,2,64,64], 256) 60 b_conv3 = bias_variable([64]) 61 h_conv3 = tf.nn.relu(conv2d(h_pool2, W_conv3) + b_conv3) 62 63 with tf.name_scope('conv4') as scope: 64 W_conv4 = weight_variable([2,2,64,64], 384) 65 b_conv4 = bias_variable([64]) 66 h_conv4 = tf.nn.relu(conv2d(h_conv3, W_conv4) + b_conv4) 67 68 with tf.name_scope('conv5') as scope: 69 W_conv5 = weight_variable([2,2,64,64], 384) 70 b_conv5 = bias_variable([64]) 71 h_conv5 = tf.nn.relu(conv2d(h_conv4, W_conv5) + b_conv5) 72 73 with tf.name_scope('pool3') as scope: 74 h_pool3 = max_pool_2x2(h_conv5) 75 76 with tf.name_scope('fc1') as scope: 77 n = np.prod(h_pool3.get_shape().as_list()[1:]) 78 W_fc1 = weight_variable([n, 1024], (7*7*256)) 79 b_fc1 = bias_variable([1024]) 80 h_pool3_flat = tf.reshape(h_pool3, [-1, n]) 81 h_fc1 = tf.nn.relu(tf.matmul(h_pool3_flat, W_fc1) + b_fc1) 82 h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) 83 84 with tf.name_scope('fc2') as scope: 85 w_fc2 = weight_variable([1024,1024], 1024) 86 b_fc2 = bias_variable([1024]) 87 h_fc2 = tf.nn.relu(tf.matmul(h_fc1_drop,w_fc2) + b_fc2) 88 h_fc2_drop = tf.nn.dropout(h_fc2, keep_prob) 89 90 with tf.name_scope('fc3') as scope: 91 W_fc3 = weight_variable([1024, NUM_CLASSES], 1024) 92 b_fc3 = bias_variable([NUM_CLASSES]) 93 y_conv = tf.matmul(h_fc2_drop, W_fc3) + b_fc3 94 95 with tf.name_scope('softmax') as scope: 96 y_conv = tf.nn.softmax(tf.matmul(h_fc2_drop, W_fc3) + b_fc3) 97 98 return y_conv 99 100def loss(logits, labels): 101 cross_entropy = tf.reduce_mean(-tf.reduce_sum(labels*tf.log(logits), reduction_indices=[1])) 102 103 tf.summary.scalar("cross_entropy", cross_entropy) 104 return cross_entropy 105 106def training(loss, learning_rate): 107 train_step = tf.train.AdamOptimizer(learning_rate).minimize(loss) 108 return train_step 109 110def accuracy(logits, labels): 111 correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(labels, 1)) 112 accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) 113 tf.summary.scalar("accuracy", accuracy) 114 return accuracy 115 116if __name__ == '__main__': 117 with open(FLAGS.train, 'r') as fs: 118 f = fs.readlines() 119 120 train_image = [] 121 train_label = [] 122 for line in f: 123 line = line.rstrip() 124 l = line.split() 125 ff = '{0}/{1}'.format(FLAGS.train_dir, l[0]) 126 img = cv2.imread(ff) 127 img = cv2.resize(img, (IMAGE_SIZE, IMAGE_SIZE)) 128 train_image.append(img.flatten().astype(np.float32)/255.0) 129 tmp = np.zeros(NUM_CLASSES) 130 tmp[int(l[1])] = 1 131 train_label.append(tmp) 132 train_image = np.asarray(train_image) 133 train_label = np.asarray(train_label) 134 135 f = open(FLAGS.test, 'r') 136 test_image = [] 137 test_label = [] 138 for line in f: 139 line = line.rstrip() 140 l = line.split() 141 ff = '{0}/{1}'.format(FLAGS.train_dir, l[0]) 142 img = cv2.imread(ff) 143 img = cv2.resize(img, (IMAGE_SIZE, IMAGE_SIZE)) 144 test_image.append(img.flatten().astype(np.float32)/255.0) 145 tmp = np.zeros(NUM_CLASSES) 146 tmp[int(l[1])] = 1 147 test_label.append(tmp) 148 test_image = np.asarray(test_image) 149 test_label = np.asarray(test_label) 150 f.close() 151 152 with tf.Graph().as_default(): 153 images_placeholder = tf.placeholder("float32", shape=(None, IMAGE_PIXELS)) 154 labels_placeholder = tf.placeholder("float32", shape=(None, NUM_CLASSES)) 155 keep_prob = tf.placeholder("float") 156 157 logits = inference(images_placeholder, keep_prob) 158 loss_value = loss(logits, labels_placeholder) 159 train_op = training(loss_value, FLAGS.learning_rate) 160 acc = accuracy(logits, labels_placeholder) 161 saver = tf.train.Saver() 162 sess = tf.Session() 163 sess.run(tf.global_variables_initializer()) 164 summary_op = tf.summary.merge_all() 165 summary_writer = tf.summary.FileWriter(FLAGS.train_dir, sess.graph_def) 166 167 idx = np.array(list(range(train_image.shape[0]))) 168 for step in range(FLAGS.max_steps): 169 np.random.shuffle(idx) 170 train_image = train_image[idx] 171 train_label = train_label[idx] 172 for i in range(len(train_image)//FLAGS.batch_size): 173 batch = FLAGS.batch_size*i 174 point = sess.run(train_op, feed_dict={ 175 images_placeholder: train_image[batch:batch+FLAGS.batch_size], 176 labels_placeholder: train_label[batch:batch+FLAGS.batch_size], 177 keep_prob: 0.5}) 178 179 train_accuracy = sess.run(acc, feed_dict={ 180 images_placeholder: train_image, 181 labels_placeholder: train_label, 182 keep_prob: 1.0}) 183 train_loss = sess.run(loss_value, feed_dict={ 184 images_placeholder: train_image, 185 labels_placeholder: train_label, 186 keep_prob: 1.0}) 187 print ("step %d, training accuracy %g"%(step, train_accuracy)) 188 print ("step %d, training loss %g"%(step, train_loss)) 189 190 summary_str = sess.run(summary_op, feed_dict={ 191 images_placeholder: train_image, 192 labels_placeholder: train_label, 193 keep_prob: 1.0}) 194 summary_writer.add_summary(summary_str, step) 195 196 print ("test accuracy %g"%sess.run(acc, feed_dict={ 197 images_placeholder: test_image, 198 labels_placeholder: test_label, 199 keep_prob: 1.0})) 200 201 save_path = saver.save(sess, "model.ckpt") 202 203 images_placeholder = tf.placeholder("float32", shape=(None, IMAGE_PIXELS)) 204 labels_placeholder = tf.placeholder("float32", shape=(None, NUM_CLASSES)) 205 keep_prob = tf.placeholder("float32") 206 logits = inference(images_placeholder,keep_prob) 207 sess = tf.InteractiveSession() 208 saver = tf.train.Saver() 209 hoge = sess.run(tf.global_variables_initializer()) 210 saver.restore(sess,"model.ckpt")

投稿2017/11/08 16:02

編集2017/11/09 16:46
mkgrei

総合スコア8562

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

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

aika_y

2017/11/09 03:41

コードの件について、埋め込み方がわからずあのような形になってしまいました。 大変申し訳ございません。 懇切丁寧な回答ありがとうございます。 こちらでも実行してみたところ、きちんと実行することができました。 しかし、Alex-netで用いていたパラメーターを使用して動かしてみたところ、学習が進まないような状態になりました。 この場合、どのパラメーターの要因が大きく影響しているのでしょうか?
mkgrei

2017/11/09 10:44

思い当たるフシがありすぎるのでなんとも言えないです。 すべてが理想の状況であると仮定して、学習率が悪いはずです。 基本的にバッチサイズと学習率をいじればよいことになります。 それでもニューラルネットワークのパラメータにニューロンの数を含めていないという前提の話となりますが。 普通はニューロンの数もパラメータとしてチューニングします。 なので本当の学習できない原因はAlexNetのパラメータを使ったことです。 さて理想的ではない状況についてですが、 まず一気にAlexNetのニューロンの数をそのまま置くと、6000万を超えるパラメータがあります。このパラメータで過学習しないほどの教師データを作り出すことは容易ではありません。AlexNetでは130万枚の教師データでも過学習すると記されています。 更にAlexNetでは1000クラスの分類を目的にしています。それに対して10クラス分類するように学習しようとしても各パラメータが収束するまで非常に時間がかかります。 どうしてもAlexNetのような大きなCNNを試したいのなら、転移学習について勉強してそちらを試されるのがよいかと思います。
aika_y

2017/11/10 07:15

何から何まで本当にありがとうございます! まだ自分自身理解していないことも多いので、これからも精進していきたいと思います。
guest

0

インデントなしのpythonコードは中身を理解しないと読めません。
読めないと回答者の心が折れてしまうので、回答が得られませんよ。
それに回答のコメントに書いちゃうとコードが折りたためません。
コメントが長すぎるので、新たに回答を作ります。

とりあえず参考のwebページと比較してコードを再現しました。
(最後のコードがそれです。)

それはともかく、かわりにデバッグいたしますと、AlexNetの構造にするために新しく付け加えた部分が怪しく思います。
conv2d_first(x_image, W_conv1 + b_conv1)
ではなく
conv2d_first(x_image, W_conv1) + b_conv1
であるべきです。

そもそも手を加える前では学習できていたのでしょうか?
その情報があれば、どこを見ればよいのかが絞り込めます。

python

1with tf.name_scope('conv1') as scope: 2 W_conv1 = weight_variable([11, 11, 3, 96], IMAGE_SIZE*IMAGE_SIZE) 3 b_conv1 = bias_variable([96]) 4 h_conv1 = tf.nn.relu(conv2d_first(x_image, W_conv1 + b_conv1))

以下、元のコード

python

1import sys 2import cv2 3import math 4import numpy as np 5import tensorflow as tf 6import tensorflow.python.platform 7 8NUM_CLASSES = 10 9IMAGE_SIZE = 224 10IMAGE_PIXELS = IMAGE_SIZE*IMAGE_SIZE*3 11 12flags = tf.app.flags 13FLAGS = flags.FLAGS 14flags.DEFINE_string('train', 'train.txt', 'File name of train data') 15flags.DEFINE_string('test', 'test.txt', 'File name of train data') 16flags.DEFINE_string('train_dir', '/tmp/data', 'Directory to put the training data.') 17flags.DEFINE_integer('max_steps', 200, 'Number of steps to run trainer.') 18flags.DEFINE_integer('batch_size', 100, 'Batch size' 19'Must divide evenly into the dataset sizes.') 20flags.DEFINE_float('learning_rate', 0.007, 'Initial learning rate.') 21 22def inference(images_placeholder, keep_prob): 23 def weight_variable(shape,num): 24 initial = tf.truncated_normal(shape, stddev=0.1/math.sqrt(float(num))) 25 return (tf.Variable(initial).initialized_value()) 26 27 def bias_variable(shape): 28 initial = tf.constant(0.1, shape=shape) 29 return (tf.Variable(initial).initialized_value()) 30 31 def conv2d_first(x, W): 32 return (tf.nn.conv2d(x, W, strides=[1, 4, 4, 1], padding='SAME')) 33 34 def conv2d(x,W): 35 return (tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')) 36 37 def max_pool_3x3(x): 38 return tf.nn.max_pool(x, ksize=[1, 3, 3, 1], 39 strides=[1, 2, 2, 1], padding='SAME') 40 41 x_image = tf.reshape(images_placeholder, [-1, IMAGE_SIZE, IMAGE_SIZE, 3]) 42 43 with tf.name_scope('conv1') as scope: 44 W_conv1 = weight_variable([11, 11, 3, 96], IMAGE_SIZE*IMAGE_SIZE) 45 b_conv1 = bias_variable([96]) 46 h_conv1 = tf.nn.relu(conv2d_first(x_image, W_conv1 + b_conv1)) 47 48 with tf.name_scope('pool1') as scope: 49 h_pool1 = max_pool_3x3(tf.nn.local_response_normalization(h_conv1)) 50 51 with tf.name_scope('conv2') as scope: 52 W_conv2 = weight_variable([5, 5, 96, 256],96) 53 b_conv2 = bias_variable([256]) 54 h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) 55 56 with tf.name_scope('pool2') as scope: 57 h_pool2 = max_pool_3x3(tf.nn.local_response_normalization(h_conv2)) 58 59 with tf.name_scope('conv3') as scope: 60 W_conv3 = weight_variable([3,3,256,384], 256) 61 b_conv3 = bias_variable([384]) 62 h_conv3 = tf.nn.relu(conv2d(h_pool2, W_conv3) + b_conv3) 63 64 with tf.name_scope('conv4') as scope: 65 W_conv4 = weight_variable([3,3,384,384], 384) 66 b_conv4 = bias_variable([384]) 67 h_conv4 = tf.nn.relu(conv2d(h_conv3, W_conv4) + b_conv4) 68 69 with tf.name_scope('conv5') as scope: 70 W_conv5 = weight_variable([3,3,384,256], 384) 71 b_conv5 = bias_variable([256]) 72 h_conv5 = tf.nn.relu(conv2d(h_conv4, W_conv5) + b_conv5) 73 74 with tf.name_scope('pool3') as scope: 75 h_pool3 = max_pool_3x3(h_conv5) 76 77 with tf.name_scope('fc1') as scope: 78 W_fc1 = weight_variable([7*7*256, 4096], (7*7*256)) 79 b_fc1 = bias_variable([4096]) 80 h_pool3_flat = tf.reshape(h_pool3, [-1, 7*7*256]) 81 h_fc1 = tf.nn.relu(tf.matmul(h_pool3_flat, W_fc1) + b_fc1) 82 h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) 83 84 with tf.name_scope('fc2') as scope: 85 w_fc2 = weight_variable([4096,4096], 4096) 86 b_fc2 = bias_variable([4096]) 87 h_fc2 = tf.nn.relu(tf.matmul(h_fc1_drop,w_fc2) + b_fc2) 88 h_fc2_drop = tf.nn.dropout(h_fc2, keep_prob) 89 90 with tf.name_scope('fc3') as scope: 91 W_fc3 = weight_variable([4096, NUM_CLASSES], 4096) 92 b_fc3 = bias_variable([NUM_CLASSES]) 93 y_conv = tf.matmul(h_fc2_drop, W_fc3) + b_fc3 94 95 with tf.name_scope('softmax') as scope: 96 y_conv=tf.nn.softmax(tf.matmul(h_fc2_drop, W_fc3) + b_fc3) 97 98 return y_conv 99 100def loss(logits, labels): 101 cross_entropy = tf.reduce_mean(-tf.reduce_sum(labels*tf.log(tf.clip_by_value(logits,1e-10,1.0)))) 102 103 tf.summary.scalar("cross_entropy", cross_entropy) 104 return cross_entropy 105 106def training(loss, learning_rate): 107 train_step = tf.train.AdamOptimizer(learning_rate).minimize(loss) 108 return train_step 109 110def accuracy(logits, labels): 111 correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(labels, 1)) 112 accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) 113 tf.summary.scalar("accuracy", accuracy) 114 return accuracy 115 116if __name__ == '__main__': 117 f = open(FLAGS.train, 'r') 118 train_image = [] 119 train_label = [] 120 for line in f: 121 line = line.rstrip() 122 l = line.split() 123 img = cv2.imread(l[0]) 124 img = cv2.resize(img, (IMAGE_SIZE, IMAGE_SIZE)) 125 train_image.append(img.flatten().astype(np.float32)/255.0) 126 tmp = np.zeros(NUM_CLASSES) 127 tmp[int(l[1])] = 1 128 train_label.append(tmp) 129 train_image = np.asarray(train_image) 130 train_label = np.asarray(train_label) 131 f.close() 132 133 f = open(FLAGS.test, 'r') 134 test_image = [] 135 test_label = [] 136 for line in f: 137 line = line.rstrip() 138 l = line.split() 139 img = cv2.imread(l[0]) 140 img = cv2.resize(img, (IMAGE_SIZE, IMAGE_SIZE)) 141 test_image.append(img.flatten().astype(np.float32)/255.0) 142 tmp = np.zeros(NUM_CLASSES) 143 tmp[int(l[1])] = 1 144 test_label.append(tmp) 145 test_image = np.asarray(test_image) 146 test_label = np.asarray(test_label) 147 f.close() 148 149 with tf.Graph().as_default(): 150 images_placeholder = tf.placeholder("float32", shape=(None, IMAGE_PIXELS)) 151 labels_placeholder = tf.placeholder("float32", shape=(None, NUM_CLASSES)) 152 keep_prob = tf.placeholder("float") 153 154 logits = inference(images_placeholder, keep_prob) 155 loss_value = loss(logits, labels_placeholder) 156 train_op = training(loss_value, FLAGS.learning_rate) 157 acc = accuracy(logits, labels_placeholder) 158 saver = tf.train.Saver() 159 sess = tf.Session() 160 sess.run(tf.global_variables_initializer()) 161 summary_op = tf.summary.merge_all() 162 summary_writer = tf.summary.FileWriter(FLAGS.train_dir, sess.graph_def) 163 164 for step in range(FLAGS.max_steps): 165 for i in range(len(train_image)//FLAGS.batch_size): 166 batch = FLAGS.batch_size*i 167 point=sess.run(train_op, feed_dict={ 168 images_placeholder: train_image[batch:batch+FLAGS.batch_size], 169 labels_placeholder: train_label[batch:batch+FLAGS.batch_size], 170 keep_prob: 0.5}) 171 172 train_accuracy = sess.run(acc, feed_dict={ 173 images_placeholder: train_image, 174 labels_placeholder: train_label, 175 keep_prob: 1.0}) 176 print ("step %d, training accuracy %g"%(step, train_accuracy)) 177 178 summary_str = sess.run(summary_op, feed_dict={ 179 images_placeholder: train_image, 180 labels_placeholder: train_label, 181 keep_prob: 1.0}) 182 summary_writer.add_summary(summary_str, step) 183 184 print ("test accuracy %g"%sess.run(acc, feed_dict={ 185 images_placeholder: test_image, 186 labels_placeholder: test_label, 187 keep_prob: 1.0})) 188 189 save_path = saver.save(sess, "model.ckpt") 190 191 images_placeholder = tf.placeholder("float32", shape=(None, IMAGE_PIXELS)) 192 labels_placeholder = tf.placeholder("float32", shape=(None, NUM_CLASSES)) 193 keep_prob = tf.placeholder("float32") 194 logits = inference(images_placeholder,keep_prob) 195 sess = tf.InteractiveSession() 196 saver = tf.train.Saver() 197 hoge = sess.run(tf.global_variables_initializer()) 198 saver.restore(sess,"model.ckpt") 199 200 for i in range(len(test_image)): 201 hoge = np.argmax(logits.eval(feed_dict={images_placeholder: [test_image[i]],keep_prob: 1.0 })[0]) 202 print("%s"%hoge) 203 204 exit()

投稿2017/11/08 09:03

mkgrei

総合スコア8562

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

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

0

コードがないので何も言えませんが、何も学習していないことが問題であることは間違いありません。

コードが正しいことを仮定すると、
step0から学習が止まっているのでバッチサイズ、最適化アルゴリズム及びパラメータがよろしくないことが多いと思います。
特に小さいバッチサイズに対して学習率が高いと比較的早い段階から学習しないことが多いです。
(正しくないものを学習しつくして、局所最適解に到達しているというべきでしょうか。)

また別の可能性として、意図していないYのデータや減少すべきでない損失関数も挙げられます。
例えば、lossがbinary_crossentropyなのにクラスが3つあるとか、lossがaccuracyなどが考えられます。

ラベルの推定がすべて0(書いてある限りでは)なのに0.1の正答率しかない偏りの強い(かも知れない)教師データのせいかもしれません。
MNISTでテストしているのでしょうか?

投稿2017/11/08 08:15

mkgrei

総合スコア8562

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

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

aika_y

2017/11/08 08:23

回答ありがとうございます。 テストに関しましては、自分で用意した画像のデータを使用しております。 コードについてなのですが以下のようになっています。 お手数おかけしますが、よろしくお願いいたします。 import sys import cv2 import math import numpy as np import tensorflow as tf import tensorflow.python.platform NUM_CLASSES = 10 IMAGE_SIZE = 224 IMAGE_PIXELS = IMAGE_SIZE*IMAGE_SIZE*3 flags = tf.app.flags FLAGS = flags.FLAGS flags.DEFINE_string('train', 'train.txt', 'File name of train data') flags.DEFINE_string('test', 'test.txt', 'File name of train data') flags.DEFINE_string('train_dir', '/tmp/data', 'Directory to put the training data.') flags.DEFINE_integer('max_steps', 200, 'Number of steps to run trainer.') flags.DEFINE_integer('batch_size', 100, 'Batch size' 'Must divide evenly into the dataset sizes.') flags.DEFINE_float('learning_rate', 0.007, 'Initial learning rate.') def inference(images_placeholder, keep_prob): # 重みを標準偏差0.1の正規分布で初期化 def weight_variable(shape,num): initial = tf.truncated_normal(shape, stddev=0.1/math.sqrt(float(num))) # tf.Variable:計算グラフ上の変数シンボルinitialを定義 return (tf.Variable(initial).initialized_value()) def bias_variable(shape): # 定数のtensorを作る initial = tf.constant(0.1, shape=shape) return (tf.Variable(initial).initialized_value()) # 畳み込み層の作成 def conv2d_first(x, W): return (tf.nn.conv2d(x, W, strides=[1, 4, 4, 1], padding='SAME')) def conv2d(x,W): return (tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')) # プーリング層の作成 def max_pool_3x3(x): return tf.nn.max_pool(x, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1], padding='SAME') # 入力を224x224x3に変形 x_image = tf.reshape(images_placeholder, [-1, IMAGE_SIZE, IMAGE_SIZE, 3]) # 畳み込み層1の作成 with tf.name_scope('conv1') as scope: W_conv1 = weight_variable([11, 11, 3, 96], IMAGE_SIZE*IMAGE_SIZE) b_conv1 = bias_variable([96]) h_conv1 = tf.nn.relu(conv2d_first(x_image, W_conv1 + b_conv1)) # プーリング層1の作成 with tf.name_scope('pool1') as scope: h_pool1 = max_pool_3x3(tf.nn.local_response_normalization(h_conv1)) # 畳み込み層2の作成 with tf.name_scope('conv2') as scope: W_conv2 = weight_variable([5, 5, 96, 256],96) b_conv2 = bias_variable([256]) h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) # プーリング層2の作成 with tf.name_scope('pool2') as scope: h_pool2 = max_pool_3x3(tf.nn.local_response_normalization(h_conv2)) # 畳み込み層3の作成 with tf.name_scope('conv3') as scope: W_conv3 = weight_variable([3,3,256,384], 256) b_conv3 = bias_variable([384]) h_conv3 = tf.nn.relu(conv2d(h_pool2, W_conv3) + b_conv3) # 畳み込み層4の作成 with tf.name_scope('conv4') as scope: W_conv4 = weight_variable([3,3,384,384], 384) b_conv4 = bias_variable([384]) h_conv4 = tf.nn.relu(conv2d(h_conv3, W_conv4) + b_conv4) # 畳み込み層5の作成 with tf.name_scope('conv5') as scope: W_conv5 = weight_variable([3,3,384,256], 384) b_conv5 = bias_variable([256]) h_conv5 = tf.nn.relu(conv2d(h_conv4, W_conv5) + b_conv5) # プーリング層3の作成 with tf.name_scope('pool3') as scope: h_pool3 = max_pool_3x3(h_conv5) # 全結合層1の作成 with tf.name_scope('fc1') as scope: W_fc1 = weight_variable([7*7*256, 4096], (7*7*256)) b_fc1 = bias_variable([4096]) h_pool3_flat = tf.reshape(h_pool3, [-1, 7*7*256]) h_fc1 = tf.nn.relu(tf.matmul(h_pool3_flat, W_fc1) + b_fc1) # dropoutの設定 h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) # 全結合層2の作成 with tf.name_scope('fc2') as scope: w_fc2 = weight_variable([4096,4096], 4096) b_fc2 = bias_variable([4096]) h_fc2 = tf.nn.relu(tf.matmul(h_fc1_drop,w_fc2) + b_fc2) h_fc2_drop = tf.nn.dropout(h_fc2, keep_prob) # 全結合層3の作成 with tf.name_scope('fc3') as scope: W_fc3 = weight_variable([4096, NUM_CLASSES], 4096) b_fc3 = bias_variable([NUM_CLASSES]) y_conv = tf.matmul(h_fc2_drop, W_fc3) + b_fc3 # ソフトマックス関数による正規化 with tf.name_scope('softmax') as scope: y_conv=tf.nn.softmax(tf.matmul(h_fc2_drop, W_fc3) + b_fc3) # 各ラベルの確率のようなものを返す return y_conv def loss(logits, labels): """ lossを計算する関数 引数: logits: ロジットのtensor, float - [batch_size, NUM_CLASSES] labels: ラベルのtensor, int32 - [batch_size, NUM_CLASSES] 返り値: cross_entropy: 交差エントロピーのtensor, float """ # 交差エントロピーの計算 cross_entropy = tf.reduce_mean(-tf.reduce_sum(labels*tf.log(tf.clip_by_value(logits,1e-10,1.0)))) # TensorBoardで表示するよう指定 tf.summary.scalar("cross_entropy", cross_entropy) return cross_entropy def training(loss, learning_rate): train_step = tf.train.AdamOptimizer(learning_rate).minimize(loss) return train_step def accuracy(logits, labels): correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(labels, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) tf.summary.scalar("accuracy", accuracy) return accuracy if __name__ == '__main__': # ファイルを開く f = open(FLAGS.train, 'r') # データを入れる配列 train_image = [] train_label = [] for line in f: # 改行を除いてスペース区切りにする line = line.rstrip() l = line.split() # # データを読み込んでIMAGE_SIZExIMAGE_SIZEに縮小 img = cv2.imread(l[0]) img = cv2.resize(img, (IMAGE_SIZE, IMAGE_SIZE)) # 一列にした後、0-1のfloat値にする train_image.append(img.flatten().astype(np.float32)/255.0) # ラベルを1-of-k方式で用意する tmp = np.zeros(NUM_CLASSES) tmp[int(l[1])] = 1 train_label.append(tmp) # numpy形式に変換 train_image = np.asarray(train_image) train_label = np.asarray(train_label) f.close() f = open(FLAGS.test, 'r') test_image = [] test_label = [] for line in f: line = line.rstrip() l = line.split() img = cv2.imread(l[0]) img = cv2.resize(img, (IMAGE_SIZE, IMAGE_SIZE)) test_image.append(img.flatten().astype(np.float32)/255.0) tmp = np.zeros(NUM_CLASSES) tmp[int(l[1])] = 1 test_label.append(tmp) test_image = np.asarray(test_image) test_label = np.asarray(test_label) f.close() with tf.Graph().as_default(): # 画像を入れる仮のTensor images_placeholder = tf.placeholder("float32", shape=(None, IMAGE_PIXELS)) # ラベルを入れる仮のTensor labels_placeholder = tf.placeholder("float32", shape=(None, NUM_CLASSES)) # dropout率を入れる仮のTensor keep_prob = tf.placeholder("float") # inference()を呼び出してモデルを作る logits = inference(images_placeholder, keep_prob) # loss()を呼び出して損失を計算 loss_value = loss(logits, labels_placeholder) # training()を呼び出して訓練 train_op = training(loss_value, FLAGS.learning_rate) # 精度の計算 acc = accuracy(logits, labels_placeholder) # 保存の準備 saver = tf.train.Saver() # Sessionの作成 sess = tf.Session() # 変数の初期化 sess.run(tf.global_variables_initializer()) # TensorBoardで表示する値の設定 summary_op = tf.summary.merge_all() summary_writer = tf.summary.FileWriter(FLAGS.train_dir, sess.graph_def) # 訓練の実行 for step in range(FLAGS.max_steps): for i in range(len(train_image)//FLAGS.batch_size): # batch_size分の画像に対して訓練の実行 batch = FLAGS.batch_size*i # feed_dictでplaceholderに入れるデータを指定する point=sess.run(train_op, feed_dict={ images_placeholder: train_image[batch:batch+FLAGS.batch_size], labels_placeholder: train_label[batch:batch+FLAGS.batch_size], keep_prob: 0.5}) # 1 step終わるたびに精度を計算する train_accuracy = sess.run(acc, feed_dict={ images_placeholder: train_image, labels_placeholder: train_label, keep_prob: 1.0}) print ("step %d, training accuracy %g"%(step, train_accuracy)) # 1 step終わるたびにTensorBoardに表示する値を追加する summary_str = sess.run(summary_op, feed_dict={ images_placeholder: train_image, labels_placeholder: train_label, keep_prob: 1.0}) summary_writer.add_summary(summary_str, step) # 訓練が終了したらテストデータに対する精度を表示 print ("test accuracy %g"%sess.run(acc, feed_dict={ images_placeholder: test_image, labels_placeholder: test_label, keep_prob: 1.0})) # 最終的なモデルを保存 save_path = saver.save(sess, "model.ckpt") # 画像を入れる仮のTensor images_placeholder = tf.placeholder("float32", shape=(None, IMAGE_PIXELS)) # ラベルを入れる仮のTensor labels_placeholder = tf.placeholder("float32", shape=(None, NUM_CLASSES)) # dropout率を入れる仮のTensor keep_prob = tf.placeholder("float32") logits = inference(images_placeholder,keep_prob) sess = tf.InteractiveSession() saver = tf.train.Saver() hoge = sess.run(tf.global_variables_initializer()) saver.restore(sess,"model.ckpt") for i in range(len(test_image)): #最大の確率のラベルを表示 hoge = np.argmax(logits.eval(feed_dict={images_placeholder: [test_image[i]],keep_prob: 1.0 })[0]) print("%s"%hoge) exit()
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.29%

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

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

質問する

関連した質問