Tensorflowで人の顔を見分ける(3)
目的
Tensorflowで人の顔を分類したい!
参考リンク
TensorFlowでアニメゆるゆりの制作会社を識別する - kivantium活動日記
動作環境
Python3.5.3 (過去ログご参考)
やりかた
全体の流れ
1.それぞれの人の顔の画像を複数集める
2.画像から人の顔だけを切出す
3.切出した顔をチェックして不要なものを削除
4.学習用データと検証用データに分ける
5.学習する
6.学習結果をみる
7.見分ける
この投稿では5項
5.学習する
参考リンクのプログラムを使わせて頂いた。ブログ主さんに感謝。
1)Pythonで以下を実行
# -*- coding: utf-8 -*-
import os
import sys
import cv2
import numpy as np
import tensorflow as tf
import tensorflow.python.platform
NUM_CLASSES = 2
IMAGE_SIZE = 28
IMAGE_PIXELS = IMAGE_SIZE*IMAGE_SIZE*3
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string('train', 'train.txt', '') # 学習用データファイル名
tf.app.flags.DEFINE_string('test', 'test.txt', '') # テスト用データファイル名
tf.app.flags.DEFINE_string('train_dir', '.', '') # TensorBoard表示用データのフォルダ
tf.app.flags.DEFINE_integer('max_steps', 200, '') # 学習ステップ数
tf.app.flags.DEFINE_integer('batch_size', 10, '') # 1回に学習する画像数(train/batch_sizeが割切れること)
tf.app.flags.DEFINE_float('learning_rate', 1e-4, '') # 学習係数
#---------------------------------------------------------------
# 予測モデルの作成関数
# 引数 images_placeholder : 画像のplaceholder
# keep_prob : dropout率のplace_holder
# 返り値 y_conv : 各クラスの確率のようなもの
#---------------------------------------------------------------
def inference(images_placeholder, keep_prob):
# 重みを標準偏差0.1の正規分布で初期化する関数
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
# バイアスを標準偏差0.1の正規分布で初期化する関数
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)
# 畳み込み層を作成する関数
def conv2d(x, W):
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
# プーリング層を作成する関数
def max_pool_2x2(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
# 入力画像の整形
x_image = tf.reshape(images_placeholder, [-1, IMAGE_SIZE, IMAGE_SIZE, 3])
# 畳み込み層1の作成
with tf.name_scope('conv1') as scope:
W_conv1 = weight_variable([5, 5, 3, 32])
b_conv1 = bias_variable([32])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
# プーリング層1の作成
with tf.name_scope('pool1') as scope:
h_pool1 = max_pool_2x2(h_conv1)
# 畳み込み層2の作成
with tf.name_scope('conv2') as scope:
W_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
# プーリング層2の作成
with tf.name_scope('pool2') as scope:
h_pool2 = max_pool_2x2(h_conv2)
# 全結合層1の作成
with tf.name_scope('fc1') as scope:
W_fc1 = weight_variable([7*7*64, 1024])
b_fc1 = bias_variable([1024])
h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
# 全結合層2の作成
with tf.name_scope('fc2') as scope:
W_fc2 = weight_variable([1024, NUM_CLASSES])
b_fc2 = bias_variable([NUM_CLASSES])
# ソフトマックス関数による正規化
with tf.name_scope('softmax') as scope:
y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
# 各ラベルの確率のようなものを返す
return y_conv
#---------------------------------------------------------------
# ロスを計算する関数
# 引数 logits : ロジット のtensor, float - [batch_size, NUM_CLASSES]
# labels : ラベル のtensor, int32 - [batch_size, NUM_CLASSES]
# 返り値 cross_entropy : 交差エントロピーのtensor, float
#---------------------------------------------------------------
def loss(logits, labels):
cross_entropy = -tf.reduce_sum(labels*tf.log(logits))
tf.summary.scalar("cross_entropy", cross_entropy)
return cross_entropy
#---------------------------------------------------------------
# 学習を定義する関数
# 引数 loss : 損失のtensor, loss()の結果
# learning_rate : 学習係数
# 返り値 train_step : 学習結果
#---------------------------------------------------------------
def training(loss, learning_rate):
train_step = tf.train.AdamOptimizer(learning_rate).minimize(loss)
return train_step
#---------------------------------------------------------------
# 正解率を計算する関数
# 引数 logits : inference()の結果
# labels : ラベルのtensor, int32 - [batch_size, NUM_CLASSES]
# 返り値 accuracy : 正解率(float)
#---------------------------------------------------------------
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() # スペースを区切り文字にリスト化
img = cv2.imread(l[0]) # 画像データ読込み
img = cv2.resize(img, (IMAGE_SIZE, IMAGE_SIZE)) # 画像データのリサイズ
train_image.append(img.flatten().astype(np.float32)/255.0) # 画像データを1列にし0~255を0~1のfloat値へ
tmp = np.zeros(NUM_CLASSES) # クラス数個のゼロを持つ配列
tmp[int(l[1])] = 1 # 正解の配列番号に1を
train_label.append(tmp)
train_image = np.asarray(train_image) # numpy形式に変換
train_label = np.asarray(train_label) # numpy形式に変換
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():
images_placeholder = tf.placeholder("float", shape=(None, IMAGE_PIXELS)) # 画像 を入れる仮のTensor
labels_placeholder = tf.placeholder("float", shape=(None, NUM_CLASSES)) # ラベル を入れる仮のTensor
keep_prob = tf.placeholder("float") # dropout率を入れる仮のTensor
logits = inference(images_placeholder, keep_prob) # inference()を呼出しモデルを作成
loss_value = loss(logits, labels_placeholder) # loss() を呼出し損失を計算
train_op = training(loss_value, FLAGS.learning_rate) # training() を呼出し学習
acc = accuracy(logits, labels_placeholder) # accuracy() を呼出し精度の計算
saver = tf.train.Saver() # 保存の準備
sess = tf.Session() # Sessionの作成
sess.run(tf.global_variables_initializer()) # 変数の初期化
summary_op = tf.summary.merge_all() # TensorBoardで表示する値の設定
summary_writer = tf.summary.FileWriter(FLAGS.train_dir, sess.graph) # TensorBoardで表示する値の設定
# 学習
for step in range(FLAGS.max_steps): # ステップ回数分学習
for i in range(int(len(train_image)/FLAGS.batch_size)): # 1回にbatch_size分の画像に対して学習
batch = FLAGS.batch_size*i
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ステップ終わるたび精度を計算
train_accuracy = sess.run(acc, feed_dict={
images_placeholder : train_image,
labels_placeholder : train_label,
keep_prob : 1.0})
print("step {0}, training accuracy {1}".format(step, train_accuracy))
# 1ステップ終わるたび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 {0}".format(sess.run(acc, feed_dict={
images_placeholder: test_image,
labels_placeholder: test_label,
keep_prob: 1.0})))
# 最終的なモデルを保存
cwd = os.getcwd()
save_path = saver.save(sess, cwd + "/model.ckpt")
Good Luck !!!