错误溢出Tensorflow模型

时间:2019-05-03 13:25:59

标签: python tensorflow model

我正在关注此存储库[deep-diver / CIFAR10-img-classification-tensorflow] [1]。为CIFAR-10数据集建立神经网络。

import pickle

将numpy导入为np 导入matplotlib.pyplot作为plt 从sklearn.preprocessing导入LabelBinarizer

def batch_features_labels(功能,标签,batch_size):     “”     将特征和标签分成批次     “”     对于范围(0,len(features),batch_size)的开始:         结束=分钟(开始+ batch_size,len(特征))         产量特征[开始:结束],标签[开始:结束]

def display_image_predictions(功能,标签,预测,top_n_predictions):     n_classes = 10     label_names = load_label_names()     label_binarizer = LabelBinarizer()     label_binarizer.fit(range(n_classes))     label_ids = label_binarizer.inverse_transform(np.array(labels))

fig, axies = plt.subplots(nrows=top_n_predictions, ncols=2, figsize=(20, 10))
fig.tight_layout()
fig.suptitle('Softmax Predictions', fontsize=20, y=1.1)

n_predictions = 3
margin = 0.05
ind = np.arange(n_predictions)
width = (1. - 2. * margin) / n_predictions

for image_i, (feature, label_id, pred_indicies, pred_values) in enumerate(zip(features, label_ids, predictions.indices, predictions.values)):
    if (image_i < top_n_predictions):
        pred_names = [label_names[pred_i] for pred_i in pred_indicies]
        correct_name = label_names[label_id]

        axies[image_i][0].imshow((feature*255).astype(np.int32, copy=False))
        axies[image_i][0].set_title(correct_name)
        axies[image_i][0].set_axis_off()

        axies[image_i][1].barh(ind + margin, pred_values[:3], width)
        axies[image_i][1].set_yticks(ind + margin)
        axies[image_i][1].set_yticklabels(pred_names[::-1])
        axies[image_i][1].set_xticks([0, 0.5, 1.0])

%matplotlib内联 %config InlineBackend.figure_format ='视网膜'

将tensorflow导入为tf 进口泡菜 随机导入

save_model_path ='final_model' batch_size = 64 n_samples = 10 top_n_predictions = 5

def test_model():     test_features,test_labels = pickle.load(open('preprocess_training.p',mode ='rb'))     loading_graph = tf.Graph()

with tf.Session(graph=loaded_graph) as sess:
    # Load model
    loader = tf.train.import_meta_graph(save_model_path + '.meta')
    loader.restore(sess, save_model_path)

    # Get Tensors from loaded model
    loaded_x = loaded_graph.get_tensor_by_name('input_x:0')
    loaded_y = loaded_graph.get_tensor_by_name('output_y:0')
    loaded_keep_prob = loaded_graph.get_tensor_by_name('keep_prob:0')
    loaded_logits = loaded_graph.get_tensor_by_name('logits:0')
    loaded_acc = loaded_graph.get_tensor_by_name('accuracy:0')

    # Get accuracy in batches for memory limitations
    test_batch_acc_total = 0
    test_batch_count = 0

    for train_feature_batch, train_label_batch in batch_features_labels(test_features, test_labels, batch_size):
        test_batch_acc_total += sess.run(
            loaded_acc,
            feed_dict={loaded_x: train_feature_batch, loaded_y: train_label_batch, loaded_keep_prob: 1.0})
        test_batch_count += 1

    print('Testing Accuracy: {}\n'.format(test_batch_acc_total/test_batch_count))

    # Print Random Samples
    random_test_features, random_test_labels = tuple(zip(*random.sample(list(zip(test_features, test_labels)), n_samples)))
    random_test_predictions = sess.run(
        tf.nn.top_k(tf.nn.softmax(loaded_logits), top_n_predictions),
        feed_dict={loaded_x: random_test_features, loaded_y: random_test_labels, loaded_keep_prob: 1.0})
    display_image_predictions(random_test_features, random_test_labels, random_test_predictions, top_n_predictions)

test_model()

训练部分进行得很好,但是在测试模型时出现以下错误

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-3-dfa44b9162e3> in <module>()
     90 
     91 
---> 92 test_model()

<ipython-input-3-dfa44b9162e3> in test_model()
     67         loaded_y = loaded_graph.get_tensor_by_name('output_y:0')
     68         loaded_keep_prob = loaded_graph.get_tensor_by_name('keep_prob:0')
---> 69         loaded_logits = loaded_graph.get_tensor_by_name('logits:0')
     70         loaded_acc = loaded_graph.get_tensor_by_name('accuracy:0')
     71 

/home/sherry/.local/lib/python3.6/site-packages/tensorflow/python/framework/ops.py in get_tensor_by_name(self, name)
   3652       raise TypeError("Tensor names are strings (or similar), not %s." %
   3653                       type(name).__name__)
-> 3654     return self.as_graph_element(name, allow_tensor=True, allow_operation=False)
   3655 
   3656   def _get_tensor_by_tf_output(self, tf_output):

/home/sherry/.local/lib/python3.6/site-packages/tensorflow/python/framework/ops.py in as_graph_element(self, obj, allow_tensor, allow_operation)
   3476 
   3477     with self._lock:
-> 3478       return self._as_graph_element_locked(obj, allow_tensor, allow_operation)
   3479 
   3480   def _as_graph_element_locked(self, obj, allow_tensor, allow_operation):

/home/sherry/.local/lib/python3.6/site-packages/tensorflow/python/framework/ops.py in _as_graph_element_locked(self, obj, allow_tensor, allow_operation)
   3518           raise KeyError("The name %s refers to a Tensor which does not "
   3519                          "exist. The operation, %s, does not exist in the "
-> 3520                          "graph." % (repr(name), repr(op_name)))
   3521         try:
   3522           return op.outputs[out_n]

KeyError: "The name 'logits:0' refers to a Tensor which does not exist. The operation, 'logits', does not exist in the graph."
  [1]: https://github.com/deep-diver/CIFAR10-img-classification-tensorflow/blob/master/CIFAR10_image_classification.ipynb```

0 个答案:

没有答案