質問編集履歴
1
コード追加
test
CHANGED
File without changes
|
test
CHANGED
@@ -35,3 +35,393 @@
|
|
35
35
|
記述の仕方がわかりません。
|
36
36
|
|
37
37
|
どういった方法がありますか?
|
38
|
+
|
39
|
+
|
40
|
+
|
41
|
+
|
42
|
+
|
43
|
+
```python
|
44
|
+
|
45
|
+
#!/usr/bin/env python
|
46
|
+
|
47
|
+
# -*- coding: utf-8 -*-
|
48
|
+
|
49
|
+
import sys
|
50
|
+
|
51
|
+
import cv2
|
52
|
+
|
53
|
+
import random
|
54
|
+
|
55
|
+
import numpy as np
|
56
|
+
|
57
|
+
import tensorflow as tf
|
58
|
+
|
59
|
+
import tensorflow.python.platform
|
60
|
+
|
61
|
+
import struct
|
62
|
+
|
63
|
+
|
64
|
+
|
65
|
+
# AIの学習モデル部分(ニューラルネットワーク)を作成する
|
66
|
+
|
67
|
+
def inference(images_placeholder, keep_prob):
|
68
|
+
|
69
|
+
|
70
|
+
|
71
|
+
# 重みを標準偏差0.1の正規分布で初期化する
|
72
|
+
|
73
|
+
def weight_variable(shape):
|
74
|
+
|
75
|
+
initial = tf.truncated_normal(shape, stddev=0.1)
|
76
|
+
|
77
|
+
return tf.Variable(initial)
|
78
|
+
|
79
|
+
|
80
|
+
|
81
|
+
# バイアスを標準偏差0.1の正規分布で初期化する
|
82
|
+
|
83
|
+
def bias_variable(shape):
|
84
|
+
|
85
|
+
initial = tf.constant(0.1, shape=shape)
|
86
|
+
|
87
|
+
return tf.Variable(initial)
|
88
|
+
|
89
|
+
|
90
|
+
|
91
|
+
# 畳み込み層を作成する
|
92
|
+
|
93
|
+
def conv2d(x, W):
|
94
|
+
|
95
|
+
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
|
96
|
+
|
97
|
+
|
98
|
+
|
99
|
+
# プーリング層を作成する
|
100
|
+
|
101
|
+
def max_pool_2x2(x):
|
102
|
+
|
103
|
+
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],strides=[1, 2, 2, 1], padding='SAME')
|
104
|
+
|
105
|
+
|
106
|
+
|
107
|
+
x_image = tf.reshape(images_placeholder, [-1, IMAGE_SIZE, IMAGE_SIZE, 3])
|
108
|
+
|
109
|
+
|
110
|
+
|
111
|
+
# 畳み込み層第1レイヤーを作成
|
112
|
+
|
113
|
+
with tf.name_scope('conv1') as scope:
|
114
|
+
|
115
|
+
W_conv1 = weight_variable([5, 5, 3, 32])
|
116
|
+
|
117
|
+
# バイアスの数値を代入
|
118
|
+
|
119
|
+
b_conv1 = bias_variable([32])
|
120
|
+
|
121
|
+
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
|
122
|
+
|
123
|
+
|
124
|
+
|
125
|
+
# プーリング層1の作成
|
126
|
+
|
127
|
+
with tf.name_scope('pool1') as scope:h_pool1 = max_pool_2x2(h_conv1)
|
128
|
+
|
129
|
+
|
130
|
+
|
131
|
+
# 畳み込み層第2レイヤーの作成
|
132
|
+
|
133
|
+
with tf.name_scope('conv2') as scope:
|
134
|
+
|
135
|
+
# 第一レイヤーでの出力を第2レイヤー入力にしてもう一度フィルタリング実施。
|
136
|
+
|
137
|
+
# 64個の特徴を検出する。inputが32なのはなんで?(教えて欲しい)
|
138
|
+
|
139
|
+
W_conv2 = weight_variable([5, 5, 32, 64])
|
140
|
+
|
141
|
+
# バイアスの数値を代入(第一レイヤーと同じ)
|
142
|
+
|
143
|
+
b_conv2 = bias_variable([64])
|
144
|
+
|
145
|
+
# 検出した特徴の整理(第一レイヤーと同じ)
|
146
|
+
|
147
|
+
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
|
148
|
+
|
149
|
+
|
150
|
+
|
151
|
+
# プーリング層2の作成(ブーリング層1と同じ)
|
152
|
+
|
153
|
+
with tf.name_scope('pool2') as scope:h_pool2 = max_pool_2x2(h_conv2)
|
154
|
+
|
155
|
+
|
156
|
+
|
157
|
+
# 全結合層1の作成
|
158
|
+
|
159
|
+
with tf.name_scope('fc1') as scope:
|
160
|
+
|
161
|
+
W_fc1 = weight_variable([7*7*64, 1024])
|
162
|
+
|
163
|
+
b_fc1 = bias_variable([1024])
|
164
|
+
|
165
|
+
# 画像の解析を結果をベクトルへ変換
|
166
|
+
|
167
|
+
h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
|
168
|
+
|
169
|
+
# 第一、第二と同じく、検出した特徴を活性化させている
|
170
|
+
|
171
|
+
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
|
172
|
+
|
173
|
+
# dropoutの設定
|
174
|
+
|
175
|
+
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
|
176
|
+
|
177
|
+
|
178
|
+
|
179
|
+
# 全結合層2の作成(読み出しレイヤー)
|
180
|
+
|
181
|
+
with tf.name_scope('fc2') as scope:
|
182
|
+
|
183
|
+
W_fc2 = weight_variable([1024, NUM_CLASSES])
|
184
|
+
|
185
|
+
b_fc2 = bias_variable([NUM_CLASSES])
|
186
|
+
|
187
|
+
|
188
|
+
|
189
|
+
with tf.name_scope('softmax') as scope:
|
190
|
+
|
191
|
+
y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
|
192
|
+
|
193
|
+
|
194
|
+
|
195
|
+
# 各ラベルの確率(のようなもの?)を返す
|
196
|
+
|
197
|
+
return y_conv
|
198
|
+
|
199
|
+
|
200
|
+
|
201
|
+
def loss(logits, labels):
|
202
|
+
|
203
|
+
# 交差エントロピーの計算
|
204
|
+
|
205
|
+
cross_entropy = -tf.reduce_sum(labels*tf.log(logits))
|
206
|
+
|
207
|
+
# TensorBoardで表示するよう指定
|
208
|
+
|
209
|
+
tf.summary.scalar("cross_entropy", cross_entropy)
|
210
|
+
|
211
|
+
# 誤差の率の値(cross_entropy)を返す
|
212
|
+
|
213
|
+
return cross_entropy
|
214
|
+
|
215
|
+
def training(loss, learning_rate):
|
216
|
+
|
217
|
+
#この関数がその当たりの全てをやってくれる様
|
218
|
+
|
219
|
+
train_step = tf.train.AdamOptimizer(learning_rate).minimize(loss)
|
220
|
+
|
221
|
+
return train_step
|
222
|
+
|
223
|
+
|
224
|
+
|
225
|
+
# inferenceで学習モデルが出した予測結果の正解率を算出する
|
226
|
+
|
227
|
+
def accuracy(logits, labels):
|
228
|
+
|
229
|
+
correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(labels, 1))
|
230
|
+
|
231
|
+
# booleanのcorrect_predictionをfloatに直して正解率の算出
|
232
|
+
|
233
|
+
# false:0,true:1に変換して計算する
|
234
|
+
|
235
|
+
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
|
236
|
+
|
237
|
+
# TensorBoardで表示する様設定
|
238
|
+
|
239
|
+
tf.summary.scalar("accuracy", accuracy)
|
240
|
+
|
241
|
+
return accuracy
|
242
|
+
|
243
|
+
|
244
|
+
|
245
|
+
if __name__ == '__main__':
|
246
|
+
|
247
|
+
# ファイルを開く
|
248
|
+
|
249
|
+
f = open(FLAGS.train, 'r')
|
250
|
+
|
251
|
+
# データを入れる配列
|
252
|
+
|
253
|
+
train_image = []
|
254
|
+
|
255
|
+
train_label = []
|
256
|
+
|
257
|
+
# numpy形式に変換
|
258
|
+
|
259
|
+
train_image = np.asarray(train_image)
|
260
|
+
|
261
|
+
train_label = np.asarray(train_label)
|
262
|
+
|
263
|
+
f.close()
|
264
|
+
|
265
|
+
|
266
|
+
|
267
|
+
f = open(FLAGS.test, 'r')
|
268
|
+
|
269
|
+
test_image = []
|
270
|
+
|
271
|
+
test_label = []
|
272
|
+
|
273
|
+
for line in f:
|
274
|
+
|
275
|
+
line = line.rstrip()
|
276
|
+
|
277
|
+
l = line.split()
|
278
|
+
|
279
|
+
img = cv2.imread(l[0])
|
280
|
+
|
281
|
+
img = cv2.resize(img, (IMAGE_SIZE, IMAGE_SIZE))
|
282
|
+
|
283
|
+
test_image.append(img.flatten().astype(np.float32)/255.0)
|
284
|
+
|
285
|
+
tmp = np.zeros(NUM_CLASSES)
|
286
|
+
|
287
|
+
tmp[int(l[1])] = 1
|
288
|
+
|
289
|
+
test_label.append(tmp)
|
290
|
+
|
291
|
+
test_image = np.asarray(test_image)
|
292
|
+
|
293
|
+
test_label = np.asarray(test_label)
|
294
|
+
|
295
|
+
f.close()
|
296
|
+
|
297
|
+
|
298
|
+
|
299
|
+
#TensorBoardのグラフに出力するスコープを指定
|
300
|
+
|
301
|
+
with tf.Graph().as_default():
|
302
|
+
|
303
|
+
# 画像を入れるためのTensor(28*28*3(IMAGE_PIXELS)次元の画像が任意の枚数(None)分はいる)
|
304
|
+
|
305
|
+
images_placeholder = tf.placeholder("float", shape=(None, IMAGE_PIXELS))
|
306
|
+
|
307
|
+
# ラベルを入れるためのTensor(3(NUM_CLASSES)次元のラベルが任意の枚数(None)分入る)
|
308
|
+
|
309
|
+
labels_placeholder = tf.placeholder("float", shape=(None, NUM_CLASSES))
|
310
|
+
|
311
|
+
# dropout率を入れる仮のTensor
|
312
|
+
|
313
|
+
keep_prob = tf.placeholder("float")
|
314
|
+
|
315
|
+
|
316
|
+
|
317
|
+
# inference()を呼び出してモデルを作る
|
318
|
+
|
319
|
+
logits = inference(images_placeholder, keep_prob)
|
320
|
+
|
321
|
+
# loss()を呼び出して損失を計算
|
322
|
+
|
323
|
+
loss_value = loss(logits, labels_placeholder)
|
324
|
+
|
325
|
+
# training()を呼び出して訓練して学習モデルのパラメーターを調整する
|
326
|
+
|
327
|
+
train_op = training(loss_value, FLAGS.learning_rate)
|
328
|
+
|
329
|
+
# 精度の計算
|
330
|
+
|
331
|
+
acc = accuracy(logits, labels_placeholder)
|
332
|
+
|
333
|
+
|
334
|
+
|
335
|
+
# 保存の準備
|
336
|
+
|
337
|
+
saver = tf.train.Saver()
|
338
|
+
|
339
|
+
# Sessionの作成(TensorFlowの計算は絶対Sessionの中でやらなきゃだめ)
|
340
|
+
|
341
|
+
sess = tf.Session()
|
342
|
+
|
343
|
+
# 変数の初期化(Sessionを開始したらまず初期化)
|
344
|
+
|
345
|
+
sess.run(tf.initialize_all_variables())
|
346
|
+
|
347
|
+
# TensorBoard表示の設定(TensorBoardの宣言的な?)
|
348
|
+
|
349
|
+
summary_op = tf.summary.merge_all()
|
350
|
+
|
351
|
+
# train_dirでTensorBoardログを出力するpathを指定
|
352
|
+
|
353
|
+
summary_writer = tf.summary.FileWriter(FLAGS.train_dir, sess.graph_def)
|
354
|
+
|
355
|
+
|
356
|
+
|
357
|
+
|
358
|
+
|
359
|
+
# 実際にmax_stepの回数だけ訓練の実行していく
|
360
|
+
|
361
|
+
for step in range(FLAGS.max_steps):
|
362
|
+
|
363
|
+
for i in range(int(len(train_image)/FLAGS.batch_size)):
|
364
|
+
|
365
|
+
# batch_size分の画像に対して訓練の実行
|
366
|
+
|
367
|
+
batch = FLAGS.batch_size*i
|
368
|
+
|
369
|
+
# feed_dictでplaceholderに入れるデータを指定する
|
370
|
+
|
371
|
+
sess.run(train_op, feed_dict={
|
372
|
+
|
373
|
+
images_placeholder: train_image[batch:batch+FLAGS.batch_size],
|
374
|
+
|
375
|
+
labels_placeholder: train_label[batch:batch+FLAGS.batch_size],
|
376
|
+
|
377
|
+
keep_prob: 0.5})
|
378
|
+
|
379
|
+
|
380
|
+
|
381
|
+
# 1step終わるたびに精度を計算する
|
382
|
+
|
383
|
+
train_accuracy = sess.run(acc, feed_dict={
|
384
|
+
|
385
|
+
images_placeholder: train_image,
|
386
|
+
|
387
|
+
labels_placeholder: train_label,
|
388
|
+
|
389
|
+
keep_prob: 1.0})
|
390
|
+
|
391
|
+
print ("step %d, training accuracy %g"%(step, train_accuracy))
|
392
|
+
|
393
|
+
|
394
|
+
|
395
|
+
# 1step終わるたびにTensorBoardに表示する値を追加する
|
396
|
+
|
397
|
+
summary_str = sess.run(summary_op, feed_dict={
|
398
|
+
|
399
|
+
images_placeholder: train_image,
|
400
|
+
|
401
|
+
labels_placeholder: train_label,
|
402
|
+
|
403
|
+
keep_prob: 1.0})
|
404
|
+
|
405
|
+
summary_writer.add_summary(summary_str, step)
|
406
|
+
|
407
|
+
|
408
|
+
|
409
|
+
# 訓練が終了したらテストデータに対する精度を表示する
|
410
|
+
|
411
|
+
print ("test accuracy %g"%sess.run(acc, feed_dict={
|
412
|
+
|
413
|
+
images_placeholder: test_image,
|
414
|
+
|
415
|
+
labels_placeholder: test_label,
|
416
|
+
|
417
|
+
keep_prob: 1.0}))
|
418
|
+
|
419
|
+
|
420
|
+
|
421
|
+
# データを学習して最終的に出来上がったモデルを保存
|
422
|
+
|
423
|
+
# "model.ckpt"は出力されるファイル名
|
424
|
+
|
425
|
+
save_path = saver.save(sess, "model2.ckpt")
|
426
|
+
|
427
|
+
```
|