2017-03-23 5 views
0

다음 코드를 사용하여 InceptionV1의 꽃 데이터 집합을 학습합니다. 이 코드는InceptionV4 및 V2는 InceptionV1보다 "꽃 데이터 집합"에 대해 낮은 정확도를 제공합니다.

import os 

from datasets import flowers 
from nets import inception 
from preprocessing import inception_preprocessing 

slim = tf.contrib.slim 
image_size = inception.inception_v1.default_image_size 


def get_init_fn(): 
    """Returns a function run by the chief worker to warm-start the training.""" 
    checkpoint_exclude_scopes=["InceptionV1/Logits", "InceptionV1/AuxLogits"] 

exclusions = [scope.strip() for scope in checkpoint_exclude_scopes] 

variables_to_restore = [] 
for var in slim.get_model_variables(): 
    excluded = False 
    for exclusion in exclusions: 
     if var.op.name.startswith(exclusion): 
      excluded = True 
      break 
    if not excluded: 
     variables_to_restore.append(var) 

return slim.assign_from_checkpoint_fn(
    os.path.join(checkpoints_dir, 'inception_v1.ckpt'), 
    variables_to_restore) 


train_dir = '/tmp/inception_finetuned/' 

with tf.Graph().as_default(): 
    tf.logging.set_verbosity(tf.logging.INFO) 

dataset = flowers.get_split('train', flowers_data_dir) 
images, _, labels = load_batch(dataset, height=image_size, width=image_size) 

# Create the model, use the default arg scope to configure the batch norm parameters. 
with slim.arg_scope(inception.inception_v1_arg_scope()): 
    logits, _ = inception.inception_v1(images, num_classes=dataset.num_classes, is_training=True) 

# Specify the loss function: 
one_hot_labels = slim.one_hot_encoding(labels, dataset.num_classes) 
slim.losses.softmax_cross_entropy(logits, one_hot_labels) 
total_loss = slim.losses.get_total_loss() 

# Create some summaries to visualize the training process: 
tf.scalar_summary('losses/Total Loss', total_loss) 

# Specify the optimizer and create the train op: 
optimizer = tf.train.AdamOptimizer(learning_rate=0.01) 
train_op = slim.learning.create_train_op(total_loss, optimizer) 

# Run the training: 
final_loss = slim.learning.train(
    train_op, 
    logdir=train_dir, 
    init_fn=get_init_fn(), 
    number_of_steps=2) 



print('Finished training. Last batch loss %f' % final_loss) 
나는 다음과 같은 코드를 사용하여 모델을 평가되고 코드에 체크 포인트 및 교육 디렉토리를 구성에서

import numpy as np 
import tensorflow as tf 
from datasets import flowers 
from nets import inception 

slim = tf.contrib.slim 

image_size = inception.inception_v1.default_image_size 
batch_size = 3 

with tf.Graph().as_default(): 
    tf.logging.set_verbosity(tf.logging.INFO) 

    dataset = flowers.get_split('train', flowers_data_dir) 
    images, images_raw, labels = load_batch(dataset, height=image_size, width=image_size) 

# Create the model, use the default arg scope to configure the batch norm parameters. 
with slim.arg_scope(inception.inception_v1_arg_scope()): 
    logits, _ = inception.inception_v1(images, num_classes=dataset.num_classes, is_training=True) 
    predictions = tf.argmax(logits, 1) 


checkpoint_path = tf.train.latest_checkpoint(train_dir) 
init_fn = slim.assign_from_checkpoint_fn(
    checkpoint_path, 
    slim.get_variables_to_restore()) 

names_to_values, names_to_updates = slim.metrics.aggregate_metric_map({ 
    'eval/Accuracy': slim.metrics.streaming_accuracy(predictions, labels), 
    'eval/[email protected]': slim.metrics.streaming_recall_at_k(logits, labels, 5), 
}) 

# Define the streaming summaries to write: 
for metric_name, metric_value in names_to_values.items(): 
    tf.summary.scalar(metric_name, metric_value) 

print('Running evaluation Loop...') 
# Load the most recent checkpoint of variables saved 
checkpoint_path = tf.train.latest_checkpoint(train_dir) 
# Evaluates the model at the given checkpoint path 
metric_values = slim.evaluation.evaluate_once(
    master='', 
    checkpoint_path=checkpoint_path, 
    logdir=train_dir, 
    num_evals=100, 
    eval_op=list(names_to_updates.values()), 
    final_op=list(names_to_values.values()), 
    summary_op=tf.summary.merge_all()) 

names_to_values = dict(zip(names_to_values.keys(), metric_values)) 
for name in names_to_values: 
    print('%s: %f' % (name, names_to_values[name])) 

그렇다, 난 단지 "V1"을 대체를 58.34 %의 정확성을 가지고

Here을 제공한다 "V2"와 "V4"모델을 훈련 시켰습니다.

첫 번째로 100 회 반복 모두에 대해 "V2"및 "V4"둘 다에 대해 교육 손실이 약 4 %입니다. 둘째, "V2"와 "V4"모두 평가 정확도가 약 25 %입니다.

저는 TF가 처음이므로 뭔가 잘못되었습니다. 잘못되었습니다.

+0

꽃 사진 데이터 세트에서 사전 습득 V3로 이전 학습을 한 번하고 최대 정확도가 약 94 %에 도달 할 수 있는데 왜 정확도가 내 것보다 훨씬 낮습니까? –

+1

@ Jie.Zhou 코드를 공유해 주시겠습니까? 나는 왜 그런 일이 일어나고 있는지, 나는 무엇인가 놓치고 있어야한다는 것을 정확히 알지 못한다. – Asad

답변

1

Inception V3과 같이 상당히 큰 길쌈 네트워크를 미세 조정할 때 여러 가지가 발생할 수 있습니다.

  • 위에 게시 한 훈련 코드는 tf.Graph에로드되는 것을 InceptionV1/LogitsInceptionV1/AuxLogits 제외 : 여기에 귀하의 모델을 개선하기 위해 당신이 들여다 수있는 몇 가지 포인터입니다. 이 텐서는 컨볼 루션베이스 위에 완전히 연결된 레이어입니다. 본질적으로 이것은 자신의 InceptionV1/LogitsInceptionV1/AuxLogits을 훈련시킬 수 있습니다. 그러나이 코드는 컨볼 루션 기반을 "동결"시키지 않습니다. 이는 컨벌루션 필터가 학습 가능하다는 것을 의미합니다. 무작위로 초기화 된 완전히 연결된 레이어에서 흐르는 큰 그라디언트가 컨볼 루션 기반에서 학습 된 가중치를 망칠 수 있기 때문에 이것은 나쁜 아이디어입니다. 이것은 더 큰 네트워크에 더 치명적인 영향을 미치며 V2와 V4가 V1보다 왜 더 나쁜지 설명 할 수 있습니다. 미세 조정 네트워크에 대한 자세한 내용은 here을 참조하십시오.
  • 0.01의 학습률은 네트워크 미세 조정을 위해 예외적으로 높게 나타납니다. 일반적으로 사전 훈련 된 모델은 선 및 가장자리 감지와 같은 하위 수준 필터를 배웠으므로 가중치를 많이 변경하지 않으려 고합니다. 학습 속도는 < = 0.001이면 충분합니다.
  • 그러나 설명했듯이 모델은 100 회의 반복에 대해 0.04로 고정되어 있지 않으므로 수렴하지 않는 것처럼 보이므로 학습 속도를 높일 수 있습니다. 나는 아직도 이것에 대해 확신 할 수 없다. 아마도 코드는 단지 예일 뿐이며 다른 모델에 적용되지 않을 것입니다.

Tensorflow에는 다른 모델의 미세 조정에 대한 문서화 된 섹션이 있습니다. here. 또한 Tensorflow의보다 사용자 친화적이고 간결한 래퍼 인 slim을 사용합니다. 아마 당신은 그것을 시도해 볼 수 있습니다. 행운을 빕니다.