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

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

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

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

MacOS(OSX)

MacOSとは、Appleの開発していたGUI(グラフィカルユーザーインターフェース)を採用したオペレーションシステム(OS)です。Macintoshと共に、市場に出てGUIの普及に大きく貢献しました。

機械学習

機械学習は、データからパターンを自動的に発見し、そこから知能的な判断を下すためのコンピューターアルゴリズムを指します。人工知能における課題のひとつです。

Q&A

解決済

1回答

1229閲覧

tensorflowでの犬猫判別のaccuracyが0.5から変わらない

vaitarika

総合スコア29

Python 3.x

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

MacOS(OSX)

MacOSとは、Appleの開発していたGUI(グラフィカルユーザーインターフェース)を採用したオペレーションシステム(OS)です。Macintoshと共に、市場に出てGUIの普及に大きく貢献しました。

機械学習

機械学習は、データからパターンを自動的に発見し、そこから知能的な判断を下すためのコンピューターアルゴリズムを指します。人工知能における課題のひとつです。

0グッド

1クリップ

投稿2019/02/13 06:36

編集2019/02/13 06:38

tensorflowを使って犬猫判別をしようとしているのですが、accuracyが0.5から変わらずに困っています。
以下がコードです。

python

1import os 2import cv2 3import numpy as np 4import tensorflow as tf 5 6path=os.getcwd()+'/data/' 7class_count = 0 8folder_list=os.listdir(path) 9 10for folder in folder_list: 11 class_count = class_count+1 12 13NUM_CLASSES = class_count 14IMAGE_SIZE = 56 15IMAGE_PIXELS = IMAGE_SIZE*IMAGE_SIZE*3 16 17print("クラス数:{}".format(NUM_CLASSES)) 18 19flags = tf.app.flags 20FLAGS = flags.FLAGS 21flags.DEFINE_string('label', 'label.txt', 'File name of label') 22flags.DEFINE_string('train_dir', './tmp/data', 'Directory to put the training data.') 23flags.DEFINE_integer('max_steps', 20, 'Number of steps to run trainer.') 24flags.DEFINE_integer('batch_size', 10, 'Batch size' 25 'Must divide evenly into the dataset sizes.') 26tf.app.flags.DEFINE_float('learning_rate', 1e-4, 'Initial learning rate.') 27 28# 予測モデルを作成する関数 29def inference(images_placeholder, keep_prob): 30 # 重みを標準偏差0.1の正規分布で初期化 31 def weight_variable(shape): 32 initial = tf.truncated_normal(shape, stddev=0.1) 33 return tf.Variable(initial) 34 35 # バイアスを標準偏差0.1の正規分布で初期化 36 def bias_variable(shape): 37 initial = tf.constant(0.1, shape=shape) 38 return tf.Variable(initial) 39 40 # 畳み込み層の作成 41 def conv2d(x, W): 42 return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') 43 44 # プーリング層の作成 45 def max_pool_2x2(x): 46 return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], 47 strides=[1, 2, 2, 1], padding='SAME') 48 49 x_image = tf.reshape(images_placeholder, [-1,IMAGE_SIZE,IMAGE_SIZE,3]) 50 print(x_image.shape) 51 52 # 畳み込み層1の作成 53 with tf.name_scope('conv1') as scope: 54 W_conv1 = weight_variable([3, 3, 3, 32]) 55 b_conv1 = bias_variable([32]) 56 h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) 57 58 # プーリング層1の作成 59 with tf.name_scope('pool1') as scope: 60 h_pool1 = max_pool_2x2(h_conv1) 61 print("h_pool1のshape:{}".format(h_pool1.shape)) 62 63 # 畳み込み層2の作成 64 with tf.name_scope('conv2') as scope: 65 W_conv2 = weight_variable([3, 3, 32, 64]) 66 b_conv2 = bias_variable([64]) 67 h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) 68 69 # プーリング層2の作成 70 with tf.name_scope('pool2') as scope: 71 h_pool2 = max_pool_2x2(h_conv2) 72 print("h_pool2のshape:{}".format(h_pool2.shape)) 73 74 # 畳み込み層3の作成 75 with tf.name_scope('conv3') as scope: 76 W_conv3 = weight_variable([3, 3, 64, 128]) 77 b_conv3 = bias_variable([128]) 78 h_conv3 = tf.nn.relu(conv2d(h_pool2, W_conv3) + b_conv3) 79 80 # プーリング層3の作成 81 with tf.name_scope('pool3') as scope: 82 h_pool3 = max_pool_2x2(h_conv3) 83 print("h_pool3のshape:{}".format(h_pool3.shape)) 84 85 # 全結合層1の作成 86 with tf.name_scope('fc1') as scope: 87 W_fc1 = weight_variable([7*7*128, 1024]) 88 b_fc1 = bias_variable([1024]) 89 h_pool3_flat = tf.reshape(h_pool3, [-1, 7*7*128]) 90 h_fc1 = tf.nn.relu(tf.matmul(h_pool3_flat, W_fc1) + b_fc1) 91 # dropoutの設定 92 h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) 93 94 # 全結合層2の作成 95 with tf.name_scope('fc2') as scope: 96 W_fc2 = weight_variable([1024, NUM_CLASSES]) 97 b_fc2 = bias_variable([NUM_CLASSES]) 98 99 # ソフトマックス関数による正規化 100 with tf.name_scope('softmax') as scope: 101 y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2) 102 103 return y_conv 104 105# lossを計算する関数 106def loss(logits, labels): 107 cross_entropy = -tf.reduce_sum(labels*tf.log(logits)) 108 tf.summary.scalar("cross_entropy", cross_entropy) 109 return cross_entropy 110 111# 訓練のOpを定義する関数 112def training(loss, learning_rate): 113 train_step = tf.train.AdamOptimizer(learning_rate).minimize(loss) 114 return train_step 115 116# 正解率(accuracy)を計算する関数 117def accuracy(logits, labels): 118 correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(labels, 1)) 119 accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) 120 tf.summary.scalar("accuracy", accuracy) 121 return accuracy 122 123if __name__ == '__main__': 124 count=0 125 folder_list=os.listdir(path) 126 127 train_image = [] 128 train_label = [] 129 test_image = [] 130 test_label = [] 131 132 f = open(FLAGS.label, 'w') 133 for folder in folder_list: 134 subfolder = os.path.join(path,folder) 135 file_list = os.listdir(subfolder) 136 137 filemax = 0 138 139 for file in file_list: 140 filemax = filemax + 1 141 142 # train : test = 9:1 143 file_rate = int(filemax/10*9) 144 145 i = 0 146 147 for file in file_list: 148 149 img = cv2.imread('./data/' + folder + '/' + file) 150 img = cv2.resize(img, (IMAGE_SIZE, IMAGE_SIZE)) 151 if i <= file_rate: 152 train_image.append(img.flatten().astype(np.float32)/255.0) 153 tmp = np.zeros(NUM_CLASSES) 154 tmp[int(count)] = 1 155 train_label.append(tmp) 156 else: 157 test_image.append(img.flatten().astype(np.float32)/255.0) 158 tmp = np.zeros(NUM_CLASSES) 159 tmp[int(count)] = 1 160 test_label.append(tmp) 161 162 i = i + 1 163 164 label_name = folder + '\n' 165 f.write(label_name) 166 count=count+1 167 f.close() 168 169 train_image = np.asarray(train_image) 170 train_label = np.asarray(train_label) 171 test_image = np.asarray(test_image) 172 test_label = np.asarray(test_label) 173 174 with tf.Graph().as_default(): 175 # 画像を入れる仮のTensor 176 images_placeholder = tf.placeholder("float", shape=(None, IMAGE_PIXELS)) 177 # ラベルを入れる仮のTensor 178 labels_placeholder = tf.placeholder("float", shape=(None, NUM_CLASSES)) 179 # dropout率を入れる仮のTensor 180 keep_prob = tf.placeholder("float") 181 182 # inference()を呼び出してモデルを作る 183 logits = inference(images_placeholder, keep_prob) 184 # loss()を呼び出して損失を計算 185 loss_value = loss(logits, labels_placeholder) 186 # training()を呼び出して訓練 187 train_op = training(loss_value, FLAGS.learning_rate) 188 # 精度の計算 189 acc = accuracy(logits, labels_placeholder) 190 191 # 保存の準備 192 saver = tf.train.Saver() 193 # Sessionの作成 194 sess = tf.Session() 195 # 変数の初期化 196 sess.run(tf.global_variables_initializer()) 197 # TensorBoardで表示する値の設定 198 summary_op = tf.summary.merge_all() 199 summary_writer = tf.summary.FileWriter('./logs', sess.graph) 200 201 202 # 訓練の実行 203 for step in range(FLAGS.max_steps): 204 for i in range(int(len(train_image)/FLAGS.batch_size)): 205 # batch_size分の画像に対して訓練の実行 206 batch = FLAGS.batch_size*i 207 # feed_dictでplaceholderに入れるデータを指定する 208 sess.run(train_op, feed_dict={ 209 images_placeholder: train_image[batch:batch+FLAGS.batch_size], 210 labels_placeholder: train_label[batch:batch+FLAGS.batch_size], 211 keep_prob: 0.5}) 212 213 # 1 step終わるたびに精度を計算する 214 train_accuracy = sess.run(acc, feed_dict={ 215 images_placeholder: train_image, 216 labels_placeholder: train_label, 217 keep_prob: 1.0}) 218 print ("step %d, training accuracy %g"%(step, train_accuracy)) 219 220 # 1 step終わるたびにTensorBoardに表示する値を追加する 221 summary_str = sess.run(summary_op, feed_dict={ 222 images_placeholder: train_image, 223 labels_placeholder: train_label, 224 keep_prob: 1.0}) 225 summary_writer.add_summary(summary_str, step) 226 227 # 訓練が終了したらテストデータに対する精度を表示 228 print ("test accuracy %g"%sess.run(acc, feed_dict={ 229 images_placeholder: test_image, 230 labels_placeholder: test_label, 231 keep_prob: 1.0})) 232 233 # 1 step終わるたびにTensorBoardに表示する値を追加する 234 summary_str = sess.run(summary_op, feed_dict={ 235 images_placeholder: test_image, 236 labels_placeholder: test_label, 237 keep_prob: 1.0}) 238 summary_writer.add_summary(summary_str, step) 239 240 # 最終的なモデルを保存 241 save_path = saver.save(sess, "./model.ckpt") 242

データはhttps://www.kaggle.com/c/dogs-vs-cats-redux-kernels-edition/dataのデータを解凍して使っています。
上記に示したコードと同じディレクトリに[data]フォルダーを作成し、その中にkaggleからダウンロードした犬猫のtrainのデータを犬と猫にわけ、[cat],[dog]と二つのファイルを作りました。
画像枚数は12500枚ずつです。
調べて見たところ、学習率や、バッチの数を変えるとよいとあったので学習率を1e-5,1e-3に変えたり、バッチ数を画像データ数で割り切れる数に変えたりしてみたのですが、効果はありませんでした。

他のコードで層の数やハイパーパラメータを同じにして試して見たところ、そちらでは89%ほどの精度で分類することができました。
また同じコードを同じようなやり方で他の画像にかけて見たところそちらではできました。

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

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

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

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

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

guest

回答1

0

ベストアンサー

この情報だけで具体的な回答は難しいです。
まずはLoss関数がどのように動いているのか、そもそも動いていないのか、という観点で確認するほうが良いと思います。
TensorBoadというツールを使えば、簡単にわかるようになります。
https://www.tensorflow.org/guide/summaries_and_tensorboard

Loss関数が振動していたり、試行回数が少ないうちに収束しているのであれば過学習の可能性がありますし、逆にまったく動いていないのであれば、学習率を上げて様子を見る必要があると思います。

投稿2019/02/14 07:20

mackerel6.023

総合スコア317

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

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

vaitarika

2019/02/14 08:45

回答ありがとうございます。 TensorBoardを使用して見たところ、cross_entropyのsmoothed,value共にNaNとなっており、全く動いていませんでした。この場合何が原因なのでしょうか。
mackerel6.023

2019/02/14 09:17 編集

実際に動かしたときに標準出力に何が出ているかを確認してみて、何か警告やエラーのようなものは出ていませんか? また、回答というよりも、アドバイスのようなものになりますが、損失関数が正しく出てないということは何かしらのコーディングミスか環境の不備があると思われます。 よって、まずは層を減らしてシンプルに全結合層1つだけでやってみて、損失関数が算出されてTensorBoadで確認できるという段階に持って行くほうが良いと思われます。 その後、層を足したり、ユニット数を変えるのは比較的簡単なので。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.50%

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

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

質問する

関連した質問