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

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

新規登録して質問してみよう
ただいま回答率
85.49%
機械学習

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

Q&A

0回答

3331閲覧

TensorFlowで顔認識の再学習させたい

oropatajin

総合スコア8

機械学習

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

0グッド

1クリップ

投稿2016/05/25 12:41

###前提・実現したいこと
現在Tensorflowで顔認識のプログラムをサンプルやネットの情報を元に試しています。
実現したいことは、再学習で認識できる顔の数を増やしていきたいのです。

###発生している問題・エラーメッセージ
具体的に言いますと、1回目の学習でAさん、Bさん、Cさんの顔を学習させることはできたのですが、
2回目の学習でDさんが新たに加わった場合の学習のやり方が分からないです。
そもそもtensorflowのサンプルなどを見るに予め分類する数を指定するところがあるので、始めから3人なら3人の分類しかできないのでしょうか?

###1回目の学習時のソースコード
import cv2
import numpy as np
import tensorflow as tf

NUM_CLASSES = 3
IMAGE_SIZE = 48
IMAGE_NN_SIZE = int(IMAGE_SIZE / 2 / 2)
IMAGE_PIXELS = IMAGE_SIZEIMAGE_SIZE3

flags = tf.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_string('save_model', 'model.ckpt', 'File name of model data')
flags.DEFINE_string('train', 'train.txt', 'File name of train data')
flags.DEFINE_string('test', 'test.txt', 'File name of test data')
flags.DEFINE_string('train_dir', 'summary', 'Directory to put the training data.')
flags.DEFINE_integer('max_steps', 100, 'Number of steps to run trainer.')
flags.DEFINE_integer('batch_size', 256, 'Batch size'
'Must divide evenly into the dataset sizes.')
flags.DEFINE_float('learning_rate', 1e-4, 'Initial learning rate.')

def inference(images_placeholder, keep_prob):
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
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_images = tf.reshape(images_placeholder, [-1, IMAGE_SIZE, IMAGE_SIZE, 3])
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_images, W_conv1) + b_conv1)
with tf.name_scope('pool1') as scope:
h_pool1 = max_pool_2x2(h_conv1)
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)
with tf.name_scope('pool2') as scope:
h_pool2 = max_pool_2x2(h_conv2)
with tf.name_scope('fc1') as scope:
W_fc1 = weight_variable([IMAGE_NN_SIZEIMAGE_NN_SIZE64, 1024])
b_fc1 = bias_variable([1024])
h_pool2_flat = tf.reshape(h_pool2, [-1, IMAGE_NN_SIZEIMAGE_NN_SIZE64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
# dropoutの設定
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
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

def loss(logits, labels):
cross_entropy = -tf.reduce_sum(labels*tf.log(tf.clip_by_value(logits,1e-10,1.0)))
tf.scalar_summary("cross_entropy", cross_entropy)
return cross_entropy

def training(loss, learning_rate):
train_step = tf.train.AdamOptimizer(learning_rate).minimize(loss)
return train_step

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.scalar_summary("accuracy", accuracy)
return accuracy

if name == 'main':
with open(FLAGS.train, 'r') as f: # train.txt
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)
tmp = np.zeros(NUM_CLASSES)
tmp[int(l[1])] = 1
train_label.append(tmp)
train_image = np.asarray(train_image)
train_label = np.asarray(train_label)
train_len = len(train_image)

with open(FLAGS.test, 'r') as f: # test.txt test_image = [] test_label = [] for line in f: line = line.rstrip() l = line.split() print(l[0]) 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) test_len = len(test_image) with tf.Graph().as_default(): images_placeholder = tf.placeholder("float", shape=(None, IMAGE_PIXELS)) labels_placeholder = tf.placeholder("float", shape=(None, NUM_CLASSES)) keep_prob = tf.placeholder("float") logits = inference(images_placeholder, keep_prob) # logits = inference(images_placeholder) loss_value = loss(logits, labels_placeholder) train_op = training(loss_value, FLAGS.learning_rate) acc = accuracy(logits, labels_placeholder) saver = tf.train.Saver() sess = tf.Session() sess.run(tf.initialize_all_variables()) summary_op = tf.merge_all_summaries() summary_writer = tf.train.SummaryWriter(FLAGS.train_dir, sess.graph_def) # 訓練の実行 if train_len % FLAGS.batch_size is 0: train_batch = int(train_len/FLAGS.batch_size) else: train_batch = int((train_len/FLAGS.batch_size)+1) print("train_batch = "+str(train_batch)) for step in range(FLAGS.max_steps): for i in range(train_batch): batch = FLAGS.batch_size*i batch_plus = FLAGS.batch_size*(i+1) if batch_plus > train_len: batch_plus = train_len # feed_dictでplaceholderに入れるデータを指定する sess.run(train_op, feed_dict={ images_placeholder: train_image[batch:batch_plus], labels_placeholder: train_label[batch:batch_plus], keep_prob: 0.5}) if step % 10 == 0: train_accuracy = 0.0 for i in range(train_batch): batch = FLAGS.batch_size*i batch_plus = FLAGS.batch_size*(i+1) if batch_plus > train_len: batch_plus = train_len train_accuracy += sess.run(acc, feed_dict={ images_placeholder: train_image[batch:batch_plus], labels_placeholder: train_label[batch:batch_plus], keep_prob: 1.0}) if i is not 0: train_accuracy /= 2.0 print("step %d, training accuracy %g"%(step, train_accuracy)) if test_len % FLAGS.batch_size is 0: test_batch = int(test_len/FLAGS.batch_size) else: test_batch = int((test_len/FLAGS.batch_size)+1) print("test_batch = "+str(test_batch)) test_accuracy = 0.0 for i in range(test_batch): batch = FLAGS.batch_size*i batch_plus = FLAGS.batch_size*(i+1) if batch_plus > train_len: batch_plus = train_len test_accuracy += sess.run(acc, feed_dict={ images_placeholder: test_image[batch:batch_plus], labels_placeholder: test_label[batch:batch_plus], keep_prob: 1.0}) if i is not 0: test_accuracy /= 2.0 print("test accuracy %g"%(test_accuracy)) save_path = saver.save(sess, FLAGS.save_model)

###補足情報(言語/FW/ツール等のバージョンなど)
言語:pytho3.5
tensorflow:0.8.0

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

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

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

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

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

guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだ回答がついていません

会員登録して回答してみよう

アカウントをお持ちの方は

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

ただいまの回答率
85.49%

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

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

質問する

関連した質問