回答編集履歴
1
動いたコードを追加しました
test
CHANGED
@@ -24,6 +24,588 @@
|
|
24
24
|
|
25
25
|
学習率の部分を1e-4 から1e-5 に小さくしたらそれらしい動きになりました
|
26
26
|
|
27
|
+
|
28
|
+
|
29
|
+
```python
|
30
|
+
|
31
|
+
|
32
|
+
|
33
|
+
# -*- coding: utf-8 -*-
|
34
|
+
|
35
|
+
|
36
|
+
|
37
|
+
import cv2
|
38
|
+
|
39
|
+
import random
|
40
|
+
|
41
|
+
import numpy as np
|
42
|
+
|
43
|
+
import sys, os
|
44
|
+
|
45
|
+
import tensorflow as tf
|
46
|
+
|
47
|
+
import tensorflow.python.platform
|
48
|
+
|
49
|
+
import tensorflow.compat.v1 as tf # FLAGS = tf.app.flags.FLAGSの解決
|
50
|
+
|
51
|
+
|
52
|
+
|
53
|
+
# 識別ラベルの数(今回は京:0,薫:1,Shinya:2なので、3)[自分とその他で2つ(まずは)]
|
54
|
+
|
55
|
+
NUM_CLASSES = 2
|
56
|
+
|
57
|
+
|
58
|
+
|
59
|
+
# 学習する時の画像のサイズ(px) 初期28
|
60
|
+
|
61
|
+
IMAGE_SIZE = 28
|
62
|
+
|
63
|
+
|
64
|
+
|
65
|
+
# 画像の次元数(28* 28*カラー(?))
|
66
|
+
|
67
|
+
IMAGE_PIXELS = IMAGE_SIZE*IMAGE_SIZE*3
|
68
|
+
|
69
|
+
|
70
|
+
|
71
|
+
# 学習に必要なデータのpathや学習の規模を設定
|
72
|
+
|
73
|
+
# パラメタの設定、デフォルト値やヘルプ画面の説明文を登録できるTensorFlow組み込み関数
|
74
|
+
|
75
|
+
#FLAGS = tf.app.flags.FLAGS
|
76
|
+
|
77
|
+
|
78
|
+
|
79
|
+
flags = tf.app.flags
|
80
|
+
|
81
|
+
FLAGS = flags.FLAGS
|
82
|
+
|
83
|
+
|
84
|
+
|
85
|
+
# 学習用データ
|
86
|
+
|
87
|
+
flags.DEFINE_string('train', 'C:/Users/?????/Anaconda3/envs/opencvtest001/workspace2/dir/train/data.txt', 'File name of train data')
|
88
|
+
|
89
|
+
|
90
|
+
|
91
|
+
# 検証用テストデータ
|
92
|
+
|
93
|
+
flags.DEFINE_string('test', 'C:/Users/?????/Anaconda3/envs/opencvtest001/workspace2/dir/test/data.txt', 'File name of test data')
|
94
|
+
|
95
|
+
|
96
|
+
|
97
|
+
# データを置いてあるフォルダ
|
98
|
+
|
99
|
+
flags.DEFINE_string('train_dir', 'C:/Users/?????/Anaconda3/envs/opencvtest001/workspace2/dir/data2', 'Directory to put the training data.')
|
100
|
+
|
101
|
+
|
102
|
+
|
103
|
+
# データ学習訓練の試行回数
|
104
|
+
|
105
|
+
flags.DEFINE_integer('max_steps', 100, 'Number of steps to run trainer.')
|
106
|
+
|
107
|
+
|
108
|
+
|
109
|
+
# 1回の学習で何枚の画像を使うか
|
110
|
+
|
111
|
+
flags.DEFINE_integer('batch_size', 30, 'Batch size Must divide evenly into the dataset sizes.')
|
112
|
+
|
113
|
+
|
114
|
+
|
115
|
+
# 学習率、小さすぎると学習が進まないし、大きすぎても誤差が収束しなかったり発散したりしてダメとか
|
116
|
+
|
117
|
+
flags.DEFINE_float('learning_keep_prob', 1e-5, 'Initial learning keep_prob.') #学習率を小さくしても変化なし
|
118
|
+
|
119
|
+
|
120
|
+
|
121
|
+
|
122
|
+
|
123
|
+
####
|
124
|
+
|
125
|
+
### ここに学習モデル処理を追記します
|
126
|
+
|
127
|
+
|
128
|
+
|
129
|
+
def inference(images_placeholder, keep_prob):
|
130
|
+
|
131
|
+
# 重みを標準偏差0.1の正規分布で初期化する
|
132
|
+
|
133
|
+
def weight_variable(shape):
|
134
|
+
|
135
|
+
initial = tf.truncated_normal(shape, stddev=0.1)
|
136
|
+
|
137
|
+
return tf.Variable(initial)
|
138
|
+
|
139
|
+
|
140
|
+
|
141
|
+
# バイアスを標準偏差0.1の正規分布で初期化する
|
142
|
+
|
143
|
+
def bias_variable(shape):
|
144
|
+
|
145
|
+
initial = tf.constant(0.1, shape=shape)
|
146
|
+
|
147
|
+
return tf.Variable(initial)
|
148
|
+
|
149
|
+
|
150
|
+
|
151
|
+
# 畳み込み層を作成する
|
152
|
+
|
153
|
+
def conv2d(x, W):
|
154
|
+
|
155
|
+
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
|
156
|
+
|
157
|
+
|
158
|
+
|
159
|
+
# プーリング層を作成する
|
160
|
+
|
161
|
+
def max_pool_2x2(x):
|
162
|
+
|
163
|
+
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
|
164
|
+
|
165
|
+
strides=[1, 2, 2, 1], padding='SAME')
|
166
|
+
|
167
|
+
# ベクトル形式で入力されてきた画像データを28px * 28pxの画像に戻す(?)。
|
168
|
+
|
169
|
+
|
170
|
+
|
171
|
+
# 今回はカラー画像なので3(モノクロだと1)
|
172
|
+
|
173
|
+
x_image = tf.reshape(images_placeholder, [-1, IMAGE_SIZE, IMAGE_SIZE, 3])
|
174
|
+
|
175
|
+
|
176
|
+
|
177
|
+
# 畳み込み層第1レイヤーを作成
|
178
|
+
|
179
|
+
with tf.name_scope('conv1') as scope:
|
180
|
+
|
181
|
+
|
182
|
+
|
183
|
+
W_conv1 = weight_variable([5, 5, 3, 32])
|
184
|
+
|
185
|
+
|
186
|
+
|
187
|
+
# バイアスの数値を代入
|
188
|
+
|
189
|
+
b_conv1 = bias_variable([32])
|
190
|
+
|
191
|
+
|
192
|
+
|
193
|
+
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
|
194
|
+
|
195
|
+
|
196
|
+
|
197
|
+
# プーリング層1の作成
|
198
|
+
|
199
|
+
|
200
|
+
|
201
|
+
with tf.name_scope('pool1') as scope:
|
202
|
+
|
203
|
+
h_pool1 = max_pool_2x2(h_conv1)
|
204
|
+
|
205
|
+
|
206
|
+
|
207
|
+
# 畳み込み層第2レイヤーの作成
|
208
|
+
|
209
|
+
with tf.name_scope('conv2') as scope:
|
210
|
+
|
211
|
+
# 第一レイヤーでの出力を第2レイヤー入力にしてもう一度フィルタリング実施。
|
212
|
+
|
213
|
+
# 64個の特徴を検出する。inputが32なのはなんで?(教えて欲しい)
|
214
|
+
|
215
|
+
W_conv2 = weight_variable([5, 5, 32, 64])
|
216
|
+
|
217
|
+
|
218
|
+
|
219
|
+
# バイアスの数値を代入(第一レイヤーと同じ)
|
220
|
+
|
221
|
+
b_conv2 = bias_variable([64])
|
222
|
+
|
223
|
+
|
224
|
+
|
225
|
+
# 検出した特徴の整理(第一レイヤーと同じ)
|
226
|
+
|
227
|
+
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
|
228
|
+
|
229
|
+
|
230
|
+
|
231
|
+
# プーリング層2の作成(ブーリング層1と同じ)
|
232
|
+
|
233
|
+
with tf.name_scope('pool2') as scope:
|
234
|
+
|
235
|
+
h_pool2 = max_pool_2x2(h_conv2)
|
236
|
+
|
237
|
+
|
238
|
+
|
239
|
+
# 全結合層1の作成
|
240
|
+
|
241
|
+
with tf.name_scope('fc1') as scope:
|
242
|
+
|
243
|
+
W_fc1 = weight_variable([7*7*64, 1024])
|
244
|
+
|
245
|
+
b_fc1 = bias_variable([1024])
|
246
|
+
|
247
|
+
# 画像の解析を結果をベクトルへ変換
|
248
|
+
|
249
|
+
h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
|
250
|
+
|
251
|
+
|
252
|
+
|
253
|
+
# 第一、第二と同じく、検出した特徴を活性化させている
|
254
|
+
|
255
|
+
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
|
256
|
+
|
257
|
+
|
258
|
+
|
259
|
+
# dropoutの設定
|
260
|
+
|
261
|
+
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
|
262
|
+
|
263
|
+
|
264
|
+
|
265
|
+
# 全結合層2の作成(読み出しレイヤー)
|
266
|
+
|
267
|
+
with tf.name_scope('fc2') as scope:
|
268
|
+
|
269
|
+
W_fc2 = weight_variable([1024, NUM_CLASSES])
|
270
|
+
|
271
|
+
b_fc2 = bias_variable([NUM_CLASSES])
|
272
|
+
|
273
|
+
|
274
|
+
|
275
|
+
# ソフトマックス関数による正規化(活性化関数)
|
276
|
+
|
277
|
+
#変更してシグモイド関数
|
278
|
+
|
279
|
+
# ここまでのニューラルネットワークの出力を各ラベルの確率へ変換する
|
280
|
+
|
281
|
+
|
282
|
+
|
283
|
+
with tf.name_scope('sigmoid') as scope:
|
284
|
+
|
285
|
+
y_conv=tf.nn.sigmoid(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
|
286
|
+
|
287
|
+
|
288
|
+
|
289
|
+
# 各ラベルの確率(のようなもの?)を返す
|
290
|
+
|
291
|
+
return y_conv
|
292
|
+
|
293
|
+
|
294
|
+
|
295
|
+
# 予測結果と正解にどれくらい「誤差」があったかを算出する
|
296
|
+
|
297
|
+
# logitsは計算結果: float - [batch_size, NUM_CLASSES]
|
298
|
+
|
299
|
+
# labelsは正解ラベル: int32 - [batch_size, NUM_CLASSES]
|
300
|
+
|
301
|
+
def loss(logits, labels):
|
302
|
+
|
303
|
+
# 交差エントロピーの計算
|
304
|
+
|
305
|
+
cross_entropy = -tf.reduce_sum(labels*tf.log(tf.clip_by_value(logits,1e-10,1.0)))
|
306
|
+
|
307
|
+
|
308
|
+
|
309
|
+
# TensorBoardで表示するよう指定
|
310
|
+
|
311
|
+
tf.summary.scalar("cross_entropy", cross_entropy)
|
312
|
+
|
313
|
+
|
314
|
+
|
315
|
+
# 誤差の率の値(cross_entropy)を返す
|
316
|
+
|
317
|
+
return cross_entropy
|
318
|
+
|
319
|
+
|
320
|
+
|
321
|
+
# 誤差(loss)を元に誤差逆伝播を用いて設計した学習モデルを訓練する
|
322
|
+
|
323
|
+
|
324
|
+
|
325
|
+
def training(loss, learning_keep_prob):
|
326
|
+
|
327
|
+
#この関数がその当たりの全てをやってくれる様
|
328
|
+
|
329
|
+
train_step = tf.train.AdamOptimizer(learning_keep_prob).minimize(loss)
|
330
|
+
|
331
|
+
return train_step
|
332
|
+
|
333
|
+
|
334
|
+
|
335
|
+
# inferenceで学習モデルが出した予測結果の正解率を算出する
|
336
|
+
|
337
|
+
def accuracy(logits, labels):
|
338
|
+
|
339
|
+
# 予測ラベルと正解ラベルが等しいか比べる。同じ値であればTrueが返される
|
340
|
+
|
341
|
+
|
342
|
+
|
343
|
+
correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(labels, 1))
|
344
|
+
|
345
|
+
|
346
|
+
|
347
|
+
# booleanのcorrect_predictionをfloatに直して正解率の算出
|
348
|
+
|
349
|
+
# false:0,true:1に変換して計算する
|
350
|
+
|
351
|
+
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
|
352
|
+
|
353
|
+
|
354
|
+
|
355
|
+
# TensorBoardで表示する様設定
|
356
|
+
|
357
|
+
tf.summary.scalar("accuracy", accuracy)
|
358
|
+
|
359
|
+
return accuracy
|
360
|
+
|
361
|
+
|
362
|
+
|
363
|
+
####
|
364
|
+
|
365
|
+
if __name__ == '__main__':
|
366
|
+
|
367
|
+
|
368
|
+
|
369
|
+
f = open(FLAGS.train, 'r')
|
370
|
+
|
371
|
+
# データを入れる配列
|
372
|
+
|
373
|
+
train_image = []
|
374
|
+
|
375
|
+
train_label = []
|
376
|
+
|
377
|
+
|
378
|
+
|
379
|
+
for line in f:
|
380
|
+
|
381
|
+
# 改行を除いてスペース区切りにする
|
382
|
+
|
383
|
+
line = line.rstrip()
|
384
|
+
|
385
|
+
l = line.split()
|
386
|
+
|
387
|
+
|
388
|
+
|
389
|
+
# データを読み込んで28x28に縮小
|
390
|
+
|
391
|
+
# img_path = "C:/Users/hogehoge/Desktop/"
|
392
|
+
|
393
|
+
img = cv2.imread(l[0])
|
394
|
+
|
395
|
+
img = cv2.resize(img, (IMAGE_SIZE, IMAGE_SIZE))
|
396
|
+
|
397
|
+
|
398
|
+
|
399
|
+
# 一列にした後、0-1のfloat値にする
|
400
|
+
|
401
|
+
train_image.append(img.flatten().astype(np.float32)/255.0)
|
402
|
+
|
403
|
+
|
404
|
+
|
405
|
+
# ラベルを1-of-k方式で用意する
|
406
|
+
|
407
|
+
tmp = np.zeros(NUM_CLASSES)
|
408
|
+
|
409
|
+
tmp[int(l[1])] = 1
|
410
|
+
|
411
|
+
train_label.append(tmp)
|
412
|
+
|
413
|
+
|
414
|
+
|
415
|
+
# numpy形式に変換
|
416
|
+
|
417
|
+
train_image = np.asarray(train_image)
|
418
|
+
|
419
|
+
train_label = np.asarray(train_label)
|
420
|
+
|
421
|
+
f.close()
|
422
|
+
|
423
|
+
|
424
|
+
|
425
|
+
f = open(FLAGS.test, 'r')
|
426
|
+
|
427
|
+
test_image = []
|
428
|
+
|
429
|
+
test_label = []
|
430
|
+
|
431
|
+
for line in f:
|
432
|
+
|
433
|
+
line = line.rstrip()
|
434
|
+
|
435
|
+
l = line.split()
|
436
|
+
|
437
|
+
img = cv2.imread(l[0])
|
438
|
+
|
439
|
+
img = cv2.resize(img, (IMAGE_SIZE, IMAGE_SIZE))
|
440
|
+
|
441
|
+
test_image.append(img.flatten().astype(np.float32)/255.0)
|
442
|
+
|
443
|
+
tmp = np.zeros(NUM_CLASSES)
|
444
|
+
|
445
|
+
tmp[int(l[1])] = 1
|
446
|
+
|
447
|
+
test_label.append(tmp)
|
448
|
+
|
449
|
+
test_image = np.asarray(test_image)
|
450
|
+
|
451
|
+
test_label = np.asarray(test_label)
|
452
|
+
|
453
|
+
f.close()
|
454
|
+
|
455
|
+
|
456
|
+
|
457
|
+
#TensorBoardのグラフに出力するスコープを指定
|
458
|
+
|
459
|
+
with tf.Graph().as_default():
|
460
|
+
|
461
|
+
# 画像を入れるためのTensor(28*28*3(IMAGE_PIXELS)次元の画像が任意の枚数(None)分はいる)
|
462
|
+
|
463
|
+
images_placeholder = tf.placeholder("float", shape=(None, IMAGE_PIXELS))
|
464
|
+
|
465
|
+
|
466
|
+
|
467
|
+
# ラベルを入れるためのTensor(3(NUM_CLASSES)次元のラベルが任意の枚数(None)分入る)
|
468
|
+
|
469
|
+
labels_placeholder = tf.placeholder("float", shape=(None, NUM_CLASSES))
|
470
|
+
|
471
|
+
|
472
|
+
|
473
|
+
# dropout率を入れる仮のTensor
|
474
|
+
|
475
|
+
keep_prob = tf.placeholder("float")
|
476
|
+
|
477
|
+
|
478
|
+
|
479
|
+
# inference()を呼び出してモデルを作る
|
480
|
+
|
481
|
+
logits = inference(images_placeholder, keep_prob)
|
482
|
+
|
483
|
+
|
484
|
+
|
485
|
+
# loss()を呼び出して損失を計算
|
486
|
+
|
487
|
+
loss_value = loss(logits, labels_placeholder)
|
488
|
+
|
489
|
+
|
490
|
+
|
491
|
+
# training()を呼び出して訓練して学習モデルのパラメーターを調整する
|
492
|
+
|
493
|
+
train_op = training(loss_value, FLAGS.learning_keep_prob)
|
494
|
+
|
495
|
+
|
496
|
+
|
497
|
+
# 精度の計算
|
498
|
+
|
499
|
+
acc = accuracy(logits, labels_placeholder)
|
500
|
+
|
501
|
+
|
502
|
+
|
503
|
+
# 保存の準備
|
504
|
+
|
505
|
+
saver = tf.train.Saver()
|
506
|
+
|
507
|
+
|
508
|
+
|
509
|
+
# Sessionの作成(TensorFlowの計算は絶対Sessionの中でやらなきゃだめ)
|
510
|
+
|
511
|
+
sess = tf.Session()
|
512
|
+
|
513
|
+
|
514
|
+
|
515
|
+
# 変数の初期化(Sessionを開始したらまず初期化)
|
516
|
+
|
517
|
+
sess.run(tf.global_variables_initializer())
|
518
|
+
|
519
|
+
|
520
|
+
|
521
|
+
# TensorBoard表示の設定(TensorBoardの宣言的な?)
|
522
|
+
|
523
|
+
summary_op = tf.summary.merge_all()
|
524
|
+
|
525
|
+
|
526
|
+
|
527
|
+
# train_dirでTensorBoardログを出力するpathを指定
|
528
|
+
|
529
|
+
summary_writer = tf.summary.FileWriter(FLAGS.train_dir, sess.graph)
|
530
|
+
|
531
|
+
|
532
|
+
|
533
|
+
# 実際にmax_stepの回数だけ訓練の実行していく
|
534
|
+
|
535
|
+
for step in range(FLAGS.max_steps):
|
536
|
+
|
537
|
+
for i in range(len(train_image)//FLAGS.batch_size):
|
538
|
+
|
539
|
+
# batch_size分の画像に対して訓練の実行
|
540
|
+
|
541
|
+
batch = FLAGS.batch_size*i
|
542
|
+
|
543
|
+
|
544
|
+
|
545
|
+
# feed_dictでplaceholderに入れるデータを指定する
|
546
|
+
|
547
|
+
sess.run(train_op, feed_dict={
|
548
|
+
|
549
|
+
images_placeholder: train_image[batch:batch+FLAGS.batch_size],
|
550
|
+
|
551
|
+
labels_placeholder: train_label[batch:batch+FLAGS.batch_size],
|
552
|
+
|
553
|
+
keep_prob: 0.5})
|
554
|
+
|
555
|
+
|
556
|
+
|
557
|
+
# 1step終わるたびに精度を計算する
|
558
|
+
|
559
|
+
train_accuracy = sess.run(acc, feed_dict={
|
560
|
+
|
561
|
+
images_placeholder: train_image,
|
562
|
+
|
563
|
+
labels_placeholder: train_label,
|
564
|
+
|
565
|
+
keep_prob: 1.0})
|
566
|
+
|
567
|
+
print("step %d, training accuracy %g" %(step, train_accuracy))
|
568
|
+
|
569
|
+
|
570
|
+
|
571
|
+
# 1step終わるたびにTensorBoardに表示する値を追加する
|
572
|
+
|
573
|
+
summary_str = sess.run(summary_op, feed_dict={
|
574
|
+
|
575
|
+
images_placeholder: train_image,
|
576
|
+
|
577
|
+
labels_placeholder: train_label,
|
578
|
+
|
579
|
+
keep_prob: 1.0})
|
580
|
+
|
581
|
+
summary_writer.add_summary(summary_str, step)
|
582
|
+
|
583
|
+
|
584
|
+
|
585
|
+
# 訓練が終了したらテストデータに対する精度を表示する
|
586
|
+
|
587
|
+
print("test accuracy %g" %(sess.run(acc, feed_dict={
|
588
|
+
|
589
|
+
images_placeholder: test_image,
|
590
|
+
|
591
|
+
labels_placeholder: test_label,
|
592
|
+
|
593
|
+
keep_prob: 1.0})))
|
594
|
+
|
595
|
+
|
596
|
+
|
597
|
+
# データを学習して最終的に出来上がったモデルを保存
|
598
|
+
|
599
|
+
# "model.ckpt"は出力されるファイル名
|
600
|
+
|
601
|
+
save_path = saver.save(sess, "model3.ckpt")
|
602
|
+
|
603
|
+
```
|
604
|
+
|
605
|
+
|
606
|
+
|
607
|
+
|
608
|
+
|
27
609
|
```result
|
28
610
|
|
29
611
|
step 0, training accuracy 0.7
|