2017-04-30 7 views
2

私は最近TensorFlowを学んでいます。明らかに私は初心者です。しかし、私はこの質問で多くの方法を試しましたが、私はモデルを訓練するためにこのコードを書いて、model.ckptファイルがすでに存在する場合には、代わりにそれを直接訓練します。しかし、電車の後、私のテスト精度は約90%ですが、正確に約10%の精度で直接復元すれば、私のモデルを復元することができなくなったからです。私はちょうどこれが私のメインの部分のコードで、weightsbiasesという名前の2つの変数を持っている:TensorFlow:モデルは正常に保存されましたが、復元に失敗しました。どこが間違っていますか?

def train(bottleneck_tensor, jpeg_data_tensor): 
image_lists = create_image_lists(TEST_PERCENTAGE, VALIDATION_PERCENTAGE) 
n_classes = len(image_lists.keys()) 

# input 
bottleneck_input = tf.placeholder(tf.float32, [None, BOTTLENECK_TENSOR_SIZE], 
            name='BottleneckInputPlaceholder') 
ground_truth_input = tf.placeholder(tf.float32, [None, n_classes], name='GroundTruthInput') 

# this is the new_layer code 
# with tf.name_scope('final_training_ops'): 
#  weights = tf.Variable(tf.truncated_normal([BOTTLENECK_TENSOR_SIZE, n_classes], stddev=0.001)) 
#  biases = tf.Variable(tf.zeros([n_classes])) 
#  logits = tf.matmul(bottleneck_input, weights) + biases 
logits=transfer_new_layer.new_layer(bottleneck_input,n_classes) 
final_tensor = tf.nn.softmax(logits) 

# losses 
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=ground_truth_input) 
cross_entropy_mean = tf.reduce_mean(cross_entropy) 
train_step = tf.train.GradientDescentOptimizer(LEARNING_RATE).minimize(cross_entropy_mean) 

# calculate the accurancy 
with tf.name_scope('evaluation'): 
    correct_prediction = tf.equal(tf.argmax(final_tensor, 1), tf.argmax(ground_truth_input, 1)) 
    evaluation_step = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) 

image_order_step = tf.arg_max(final_tensor, 1) 

saver = tf.train.Saver(tf.global_variables(), write_version=tf.train.SaverDef.V1) 

with tf.Session() as sess: 
    init = tf.global_variables_initializer() 
    sess.run(init) 
    if os.path.exists('F:/_pythonWS/imageClassifier/ckpt/imagesClassFilter.ckpt'): 
     saver.restore(sess,"F:/_pythonWS/imageClassifier/ckpt/imagesClassFilter.ckpt") 
     reader = tf.train.NewCheckpointReader('F:/_pythonWS/imageClassifier/ckpt/imagesClassFilter.ckpt') 
     all_variables = reader.get_variable_to_shape_map() 
     for each in all_variables: 
      print(each, all_variables[each]) 
      print(reader.get_tensor(each)) 
    else: 
     print("retrain model") 
     for i in range(STEPS): 
      train_bottlenecks, train_ground_truth = get_random_cached_bottlenecks(
       sess, n_classes, image_lists, BATCH, 'training', jpeg_data_tensor, bottleneck_tensor) 
      sess.run(train_step, 
        feed_dict={bottleneck_input: train_bottlenecks, ground_truth_input: train_ground_truth}) 
      # 在验证数据上测试正确率 
      if i % 100 == 0 or i + 1 == STEPS: 
       validation_bottlenecks, validation_ground_truth = get_random_cached_bottlenecks(
        sess, n_classes, image_lists, BATCH, 'validation', jpeg_data_tensor, bottleneck_tensor) 
       validation_accuracy = sess.run(evaluation_step, feed_dict={ 
        bottleneck_input: validation_bottlenecks, ground_truth_input: validation_ground_truth}) 
       print('Step %d: Validation accuracy on random sampled %d examples = %.1f%%' % (
       i, BATCH, validation_accuracy * 100)) 
     saver.save(sess, 'F:/_pythonWS/imageClassifier/ckpt/imagesClassFilter.ckpt') 
     print(tf.get_session_tensor("final_training_ops/Variable",dtype=float)) 
     print(tf.get_session_tensor("final_training_ops/Variable_1",dtype=float)) 
    print('Beginning Test') 
    # test 
    test_bottlenecks, test_ground_truth = get_tst_bottlenecks(sess, image_lists, n_classes, 
                      jpeg_data_tensor, 
                      bottleneck_tensor) 
    # saver.restore(sess, 'F:/_pythonWS/imageClassifier/ckpt/imagesClassFilter.ckpt') 
    test_accuracy = sess.run(evaluation_step, feed_dict={ 
     bottleneck_input: test_bottlenecks, ground_truth_input: test_ground_truth}) 
    print('Final test accuracy = %.1f%%' % (test_accuracy * 100)) 

    label_name_list = list(image_lists.keys()) 
    for label_index, label_name in enumerate(label_name_list): 
     category = 'testing' 
     for index, unused_base_name in enumerate(image_lists[label_name][category]): 
      bottlenecks = [] 
      ground_truths = [] 
      print("real lable%s:" % label_name) 
      # print(unused_base_name) 
      bottleneck = get_or_create_bottleneck(sess, image_lists, label_name, index, category, 
                   jpeg_data_tensor, bottleneck_tensor) 
      # saver.restore(sess, 'F:/_pythonWS/imageClassifier/ckpt/imagesClassFilter.ckpt') 
      ground_truth = np.zeros(n_classes, dtype=np.float32) 
      ground_truth[label_index] = 1.0 
      bottlenecks.append(bottleneck) 
      ground_truths.append(ground_truth) 
      image_kind = sess.run(image_order_step, feed_dict={ 
       bottleneck_input: bottlenecks, ground_truth_input: ground_truths}) 
      image_kind_order = int(image_kind[0]) 
      print("pre_lable%s:" % label_name_list[image_kind_order]) 

答えて

0

私はどこに間違いがあるのか​​知っています...実際にモデルを正常に復元していますが、私はいつもrandで結果リストを作成するので、image_order_step = tf.arg_max(final_tensor, 1)を使ってテスト画像の種類を計算すると、次回にコードを実行すると、lablesの順序が変更されますが、ウェイトとbiaeseは前回と同じです。たとえば、最初のリストは[A1、A2、A3、A4、A5、 A6]、および後のimage_order_step = tf.arg_max(final_tensor, 1)結果は3であるので、結果はA4、次回[A5、A3、A1、A6、A2、A4]にlableリストの変更が、image_order_step = tf.arg_max(final_tensor, 1)結果、まだ3、その予測されます計算結果はA6になりますので、正確さは毎回randによって完全に変わります。 この質問は細部に注意してください、あるいは小さなエラーがあなたに長い時間を混乱させるでしょう私。オーバー!テストデータは、毎回の試験精度に影響を与える変更場合

0

は保存して復元するには、この方法を試してみてください:

saver = tf.train.Saver() 
with tf.Session() as sess: 
sess.run(initVar) 

# restore saved model 
new_saver = tf.train.import_meta_graph('my-model.meta') 
new_saver.restore(sess, tf.train.latest_checkpoint('./')) 


# save model weights, after training process 
saver.save(sess, 'my-model') 

は、セッション外tf.train.Saverを定義します。トレーニングを終えたら、saver.save(sess, 'my-model')で体重を保存してください。そして、上記のような体重を回復させてください。

+0

助けてくれてありがとう、私はそれはまだ私が疑問に言ったようにeither.The結果を動作しません教えて申し訳ありません、私は(、テストを知りませんデータは前回のトレーニングデータであってもよい)。結果に少し影響があると思いますが、精度を90%から10%以下に変更してはいけません。これはすべて私のコードです。あなたが自由な時間を持っているなら、私はそれを確認してくれるでしょうか?[TensorFlow transfer-learning](https://github.com/VoidBug/TensorFlow) – VoidBug

関連する問題