前提・実現したいこと
https://qiita.com/neriai/items/6a662a49054bc544806d
[TensorFlowを使ってDir en greyの顔分類器を作ってみた - ⑥学習プログラム編]
を参考に顔分類器を作成しています。(参考場所は分類が3種類だが自分は2種類)
発生している問題・エラーメッセージ
プログラムは問題なく動きますが、途中の学習精度が変化しないままプログラムが動いてしまいます。
result
1step 0, training accuracy 0.7 2step 1, training accuracy 0.7 3step 2, training accuracy 0.7 4step 3, training accuracy 0.7 5 ~~~~~~~~~~~~~~~~~~~~ 6 7step 98, training accuracy 0.7 8step 99, training accuracy 0.7 9test accuracy 0.7
該当のソースコード
?????は自分のユーザーネームなので伏せています
python
1# -*- coding: utf-8 -*- 2 3import cv2 4import random 5import numpy as np 6import sys, os 7import tensorflow as tf 8import tensorflow.python.platform 9import tensorflow.compat.v1 as tf # FLAGS = tf.app.flags.FLAGSの解決 10 11# 識別ラベルの数(今回は京:0,薫:1,Shinya:2なので、3)[自分とその他で2つ(まずは)] 12NUM_CLASSES = 2 13 14# 学習する時の画像のサイズ(px) 初期28 15IMAGE_SIZE = 28 16 17# 画像の次元数(28* 28*カラー(?)) 18IMAGE_PIXELS = IMAGE_SIZE*IMAGE_SIZE*3 19 20# 学習に必要なデータのpathや学習の規模を設定 21# パラメタの設定、デフォルト値やヘルプ画面の説明文を登録できるTensorFlow組み込み関数 22#FLAGS = tf.app.flags.FLAGS 23 24flags = tf.app.flags 25FLAGS = flags.FLAGS 26 27# 学習用データ 28flags.DEFINE_string('train', 'C:/Users/?????/Anaconda3/envs/opencvtest001/workspace2/dir/train/data.txt', 'File name of train data') 29 30# 検証用テストデータ 31flags.DEFINE_string('test', 'C:/Users/?????/Anaconda3/envs/opencvtest001/workspace2/dir/test/data.txt', 'File name of test data') 32 33# データを置いてあるフォルダ 34flags.DEFINE_string('train_dir', 'C:/Users/?????/Anaconda3/envs/opencvtest001/workspace2/dir/data', 'Directory to put the training data.') 35 36# データ学習訓練の試行回数 37flags.DEFINE_integer('max_steps', 100, 'Number of steps to run trainer.') 38 39# 1回の学習で何枚の画像を使うか 40flags.DEFINE_integer('batch_size', 30, 'Batch size Must divide evenly into the dataset sizes.') 41 42# 学習率、小さすぎると学習が進まないし、大きすぎても誤差が収束しなかったり発散したりしてダメとか 43flags.DEFINE_float('learning_rate', 1e-4, 'Initial learning rate.') 44 45# AIの学習モデル部分(ニューラルネットワーク)を作成する 46# images_placeholder: 画像のplaceholder, keep_prob: dropout率のplace_holderが引数になり 47# 入力画像に対して、各ラベルの確率を出力して返す 48 49#### 50### ここに学習モデル処理を追記します 51 52def inference(images_placeholder, keep_prob): 53 # 重みを標準偏差0.1の正規分布で初期化する 54 def weight_variable(shape): 55 initial = tf.truncated_normal(shape, stddev=0.1) 56 return tf.Variable(initial) 57 58 # バイアスを標準偏差0.1の正規分布で初期化する 59 def bias_variable(shape): 60 initial = tf.constant(0.1, shape=shape) 61 return tf.Variable(initial) 62 63 # 畳み込み層を作成する 64 def conv2d(x, W): 65 return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') 66 67 # プーリング層を作成する 68 def max_pool_2x2(x): 69 return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], 70 strides=[1, 2, 2, 1], padding='SAME') 71 # ベクトル形式で入力されてきた画像データを28px * 28pxの画像に戻す(?)。 72 73 # 今回はカラー画像なので3(モノクロだと1) 74 x_image = tf.reshape(images_placeholder, [-1, IMAGE_SIZE, IMAGE_SIZE, 3]) 75 76 # 畳み込み層第1レイヤーを作成 77 with tf.name_scope('conv1') as scope: 78 # 引数は[width, height, input, filters]。 79 # 5px*5pxの範囲で画像をフィルターしている。今回はカラー画像なのでinputは3? 80 # 32個の特徴を検出する 81 W_conv1 = weight_variable([5, 5, 3, 32]) 82 83 # バイアスの数値を代入 84 b_conv1 = bias_variable([32]) 85 86 # 特徴として検出した有用そうな部分は残し、特徴として使えなさそうな部分は 87 # 0として、特徴として扱わないようにしているという理解(Relu関数) 88 h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) 89 90 # プーリング層1の作成 91 # 2*2の枠を作り、その枠内の特徴を1*1分にいい感じに圧縮させている。 92 # その枠を2*2ずつスライドさせて画像全体に対して圧縮作業を適用するという理解 93 # ざっくり理解で細分化された特徴たちをもうちょっといい感じに大まかにまとめる(圧縮する) 94 with tf.name_scope('pool1') as scope: 95 h_pool1 = max_pool_2x2(h_conv1) 96 97 # 畳み込み層第2レイヤーの作成 98 with tf.name_scope('conv2') as scope: 99 # 第一レイヤーでの出力を第2レイヤー入力にしてもう一度フィルタリング実施。 100 # 64個の特徴を検出する。inputが32なのはなんで?(教えて欲しい) 101 W_conv2 = weight_variable([5, 5, 32, 64]) 102 103 # バイアスの数値を代入(第一レイヤーと同じ) 104 b_conv2 = bias_variable([64]) 105 106 # 検出した特徴の整理(第一レイヤーと同じ) 107 h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) 108 109 # プーリング層2の作成(ブーリング層1と同じ) 110 with tf.name_scope('pool2') as scope: 111 h_pool2 = max_pool_2x2(h_conv2) 112 113 # 全結合層1の作成 114 with tf.name_scope('fc1') as scope: 115 W_fc1 = weight_variable([7*7*64, 1024]) 116 b_fc1 = bias_variable([1024]) 117 # 画像の解析を結果をベクトルへ変換 118 h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64]) 119 120 # 第一、第二と同じく、検出した特徴を活性化させている 121 h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) 122 123 # dropoutの設定 124 # 訓練用データだけに最適化して、実際にあまり使えないような 125 # AIになってしまう「過学習」を防止の役割を果たすらしい 126 h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) 127 128 # 全結合層2の作成(読み出しレイヤー) 129 with tf.name_scope('fc2') as scope: 130 W_fc2 = weight_variable([1024, NUM_CLASSES]) 131 b_fc2 = bias_variable([NUM_CLASSES]) 132 133 # ソフトマックス関数による正規化 134 # ここまでのニューラルネットワークの出力を各ラベルの確率へ変換する 135 with tf.name_scope('softmax') as scope: 136 y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2) 137 138 # 各ラベルの確率(のようなもの?)を返す 139 return y_conv 140 141# 予測結果と正解にどれくらい「誤差」があったかを算出する 142# logitsは計算結果: float - [batch_size, NUM_CLASSES] 143# labelsは正解ラベル: int32 - [batch_size, NUM_CLASSES] 144def loss(logits, labels): 145 # 交差エントロピーの計算 146 cross_entropy = -tf.reduce_sum(labels*tf.log(logits)) 147 148 # TensorBoardで表示するよう指定 149 tf.summary.scalar("cross_entropy", cross_entropy) 150 151 # 誤差の率の値(cross_entropy)を返す 152 return cross_entropy 153 154# 誤差(loss)を元に誤差逆伝播を用いて設計した学習モデルを訓練する 155# 裏側何が起きているのかよくわかってないが、学習モデルの各層の重み(w)などを 156# 誤差を元に最適化して調整しているという理解(?) 157# (誤差逆伝播は「人工知能は人間を超えるか」書籍の説明が神) 158def training(loss, learning_rate): 159 #この関数がその当たりの全てをやってくれる様 160 train_step = tf.train.AdamOptimizer(learning_rate).minimize(loss) 161 return train_step 162 163# inferenceで学習モデルが出した予測結果の正解率を算出する 164def accuracy(logits, labels): 165 # 予測ラベルと正解ラベルが等しいか比べる。同じ値であればTrueが返される 166 # argmaxは配列の中で一番値の大きい箇所のindex(=一番正解だと思われるラベルの番号)を返す 167 correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(labels, 1)) 168 169 # booleanのcorrect_predictionをfloatに直して正解率の算出 170 # false:0,true:1に変換して計算する 171 accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) 172 173 # TensorBoardで表示する様設定 174 tf.summary.scalar("accuracy", accuracy) 175 return accuracy 176 177#### 178if __name__ == '__main__': 179 180 f = open(FLAGS.train, 'r') 181 # データを入れる配列 182 train_image = [] 183 train_label = [] 184 185 for line in f: 186 # 改行を除いてスペース区切りにする 187 line = line.rstrip() 188 l = line.split() 189 190 # データを読み込んで28x28に縮小 191 # img_path = "C:/Users/hogehoge/Desktop/" 192 img = cv2.imread(l[0]) 193 img = cv2.resize(img, (IMAGE_SIZE, IMAGE_SIZE)) 194 195 # 一列にした後、0-1のfloat値にする 196 train_image.append(img.flatten().astype(np.float32)/255.0) 197 198 # ラベルを1-of-k方式で用意する 199 tmp = np.zeros(NUM_CLASSES) 200 tmp[int(l[1])] = 1 201 train_label.append(tmp) 202 203 # numpy形式に変換 204train_image = np.asarray(train_image) 205train_label = np.asarray(train_label) 206f.close() 207 208f = open(FLAGS.test, 'r') 209test_image = [] 210test_label = [] 211for line in f: 212 line = line.rstrip() 213 l = line.split() 214 img = cv2.imread(l[0]) 215 img = cv2.resize(img, (IMAGE_SIZE, IMAGE_SIZE)) 216 test_image.append(img.flatten().astype(np.float32)/255.0) 217 tmp = np.zeros(NUM_CLASSES) 218 tmp[int(l[1])] = 1 219 test_label.append(tmp) 220test_image = np.asarray(test_image) 221test_label = np.asarray(test_label) 222f.close() 223 224#TensorBoardのグラフに出力するスコープを指定 225with tf.Graph().as_default(): 226# 画像を入れるためのTensor(28*28*3(IMAGE_PIXELS)次元の画像が任意の枚数(None)分はいる) 227 images_placeholder = tf.placeholder("float", shape=(None, IMAGE_PIXELS)) 228 229 # ラベルを入れるためのTensor(3(NUM_CLASSES)次元のラベルが任意の枚数(None)分入る) 230 labels_placeholder = tf.placeholder("float", shape=(None, NUM_CLASSES)) 231 232 # dropout率を入れる仮のTensor 233 keep_prob = tf.placeholder("float") 234 235 # inference()を呼び出してモデルを作る 236 logits = inference(images_placeholder, keep_prob) 237 238 # loss()を呼び出して損失を計算 239 loss_value = loss(logits, labels_placeholder) 240 241 # training()を呼び出して訓練して学習モデルのパラメーターを調整する 242 train_op = training(loss_value, FLAGS.learning_rate) 243 244 # 精度の計算 245 acc = accuracy(logits, labels_placeholder) 246 247 # 保存の準備 248 saver = tf.train.Saver() 249 250 # Sessionの作成(TensorFlowの計算は絶対Sessionの中でやらなきゃだめ) 251 sess = tf.Session() 252 253 # 変数の初期化(Sessionを開始したらまず初期化) 254 sess.run(tf.global_variables_initializer()) 255 256 # TensorBoard表示の設定(TensorBoardの宣言的な?) 257 summary_op = tf.summary.merge_all() 258 259 # train_dirでTensorBoardログを出力するpathを指定 260 summary_writer = tf.summary.FileWriter(FLAGS.train_dir, sess.graph) 261 262 # 実際にmax_stepの回数だけ訓練の実行していく 263 for step in range(FLAGS.max_steps): 264 for i in range(len(train_image)//FLAGS.batch_size): 265 # batch_size分の画像に対して訓練の実行 266 batch = FLAGS.batch_size*i 267 268 # feed_dictでplaceholderに入れるデータを指定する 269 sess.run(train_op, feed_dict={ 270 images_placeholder: train_image[batch:batch+FLAGS.batch_size], 271 labels_placeholder: train_label[batch:batch+FLAGS.batch_size], 272 keep_prob: 0.5}) 273 274 # 1step終わるたびに精度を計算する 275 train_accuracy = sess.run(acc, feed_dict={ 276 images_placeholder: train_image, 277 labels_placeholder: train_label, 278 keep_prob: 1.0}) 279 print("step %d, training accuracy %g" %(step, train_accuracy)) 280 281 # 1step終わるたびにTensorBoardに表示する値を追加する 282 summary_str = sess.run(summary_op, feed_dict={ 283 images_placeholder: train_image, 284 labels_placeholder: train_label, 285 keep_prob: 1.0}) 286 summary_writer.add_summary(summary_str, step) 287 288 # 訓練が終了したらテストデータに対する精度を表示する 289 print("test accuracy %g" %(sess.run(acc, feed_dict={ 290 images_placeholder: test_image, 291 labels_placeholder: test_label, 292 keep_prob: 1.0}))) 293 294 # データを学習して最終的に出来上がったモデルを保存 295 # "model.ckpt"は出力されるファイル名 296 save_path = saver.save(sess, "model2.ckpt") 297
## 追記
130行目あたりの出力層の正規化に使う関数をソフトマックス関数からシグモイド関数に変更しても変化ありませんでした。(シグモイド関数の書き方を間違っている可能性もありますが)
with tf.name_scope('softmax') as scope: y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2) ↓ with tf.name_scope('sigmoid') as scope: y_conv=tf.nn.sigmoid(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
補足情報(FW/ツールのバージョンなど)
tensorflow 2.0.0
python 3.7.5
windows10

回答1件
あなたの回答
tips
プレビュー