Tensorflow 中没有变量可以保存错误

Posted

技术标签:

【中文标题】Tensorflow 中没有变量可以保存错误【英文标题】:No variable to save error in Tensorflow 【发布时间】:2016-07-16 19:42:46 【问题描述】:

我正在尝试保存模型,然后将其重新用于对图像进行分类,但不幸的是,我在恢复已保存的模型时遇到了错误。

创建模型的代码

# Deep Learning
# =============
# 
# Assignment 4
# ------------

# In[25]:

# These are all the modules we'll be using later. Make sure you can import them
# before proceeding further.
from __future__ import print_function
import numpy as np
import tensorflow as tf
from six.moves import cPickle as pickle
from six.moves import range


# In[37]:

pickle_file = 'notMNIST.pickle'

with open(pickle_file, 'rb') as f:
  save = pickle.load(f)
  train_dataset = save['train_dataset']
  train_labels = save['train_labels']
  valid_dataset = save['valid_dataset']
  valid_labels = save['valid_labels']
  test_dataset = save['test_dataset']
  test_labels = save['test_labels']
  del save  # hint to help gc free up memory
  print('Training set', train_dataset.shape, train_labels.shape)
  print('Validation set', valid_dataset.shape, valid_labels.shape)
  print('Test set', test_dataset.shape, test_labels.shape)
  print(test_labels)


# Reformat into a TensorFlow-friendly shape:
# - convolutions need the image data formatted as a cube (width by height by #channels)
# - labels as float 1-hot encodings.

# In[38]:

image_size = 28
num_labels = 10
num_channels = 1 # grayscale

import numpy as np

def reformat(dataset, labels):
  dataset = dataset.reshape(
    (-1, image_size, image_size, num_channels)).astype(np.float32)
  #print(np.arange(num_labels))
  labels = (np.arange(num_labels) == labels[:,None]).astype(np.float32)
  #print(labels[0,:])
  print(labels[0])
  return dataset, labels
train_dataset, train_labels = reformat(train_dataset, train_labels)
valid_dataset, valid_labels = reformat(valid_dataset, valid_labels)
test_dataset, test_labels = reformat(test_dataset, test_labels)
print('Training set', train_dataset.shape, train_labels.shape)
print('Validation set', valid_dataset.shape, valid_labels.shape)
print('Test set', test_dataset.shape, test_labels.shape)
#print(labels[0])


# In[39]:

def accuracy(predictions, labels):
  return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1))
          / predictions.shape[0])


# Let's build a small network with two convolutional layers, followed by one fully connected layer. Convolutional networks are more expensive computationally, so we'll limit its depth and number of fully connected nodes.

# In[47]:

batch_size = 16
patch_size = 5
depth = 16
num_hidden = 64

graph = tf.Graph()

with graph.as_default():

  # Input data.
  tf_train_dataset = tf.placeholder(
    tf.float32, shape=(batch_size, image_size, image_size, num_channels))
  tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels))
  tf_valid_dataset = tf.constant(valid_dataset)
  tf_test_dataset = tf.constant(test_dataset)

  # Variables.
  layer1_weights = tf.Variable(tf.truncated_normal(
      [patch_size, patch_size, num_channels, depth], stddev=0.1),name="layer1_weights")
  layer1_biases = tf.Variable(tf.zeros([depth]),name = "layer1_biases")
  layer2_weights = tf.Variable(tf.truncated_normal(
      [patch_size, patch_size, depth, depth], stddev=0.1),name = "layer2_weights")
  layer2_biases = tf.Variable(tf.constant(1.0, shape=[depth]),name ="layer2_biases")
  layer3_weights = tf.Variable(tf.truncated_normal(
      [image_size // 4 * image_size // 4 * depth, num_hidden], stddev=0.1),name="layer3_biases")
  layer3_biases = tf.Variable(tf.constant(1.0, shape=[num_hidden]),name = "layer3_biases")
  layer4_weights = tf.Variable(tf.truncated_normal(
      [num_hidden, num_labels], stddev=0.1),name = "layer4_weights")
  layer4_biases = tf.Variable(tf.constant(1.0, shape=[num_labels]),name = "layer4_biases")

  # Model.
  def model(data):
    conv = tf.nn.conv2d(data, layer1_weights, [1, 2, 2, 1], padding='SAME')
    hidden = tf.nn.relu(conv + layer1_biases)
    conv = tf.nn.conv2d(hidden, layer2_weights, [1, 2, 2, 1], padding='SAME')
    hidden = tf.nn.relu(conv + layer2_biases)
    shape = hidden.get_shape().as_list()
    reshape = tf.reshape(hidden, [shape[0], shape[1] * shape[2] * shape[3]])
    hidden = tf.nn.relu(tf.matmul(reshape, layer3_weights) + layer3_biases)
    return tf.matmul(hidden, layer4_weights) + layer4_biases

  # Training computation.
  logits = model(tf_train_dataset)
  loss = tf.reduce_mean(
    tf.nn.softmax_cross_entropy_with_logits(logits, tf_train_labels))

  # Optimizer.
  optimizer = tf.train.GradientDescentOptimizer(0.05).minimize(loss)

  # Predictions for the training, validation, and test data.
  train_prediction = tf.nn.softmax(logits)
  valid_prediction = tf.nn.softmax(model(tf_valid_dataset))
  test_prediction = tf.nn.softmax(model(tf_test_dataset))


# In[48]:

num_steps = 1001
#saver = tf.train.Saver()
with tf.Session(graph=graph) as session:
  tf.initialize_all_variables().run()
  print('Initialized')
  for step in range(num_steps):
    offset = (step * batch_size) % (train_labels.shape[0] - batch_size)
    batch_data = train_dataset[offset:(offset + batch_size), :, :, :]
    batch_labels = train_labels[offset:(offset + batch_size), :]
    feed_dict = tf_train_dataset : batch_data, tf_train_labels : batch_labels
    _, l, predictions = session.run(
      [optimizer, loss, train_prediction], feed_dict=feed_dict)
    if (step % 50 == 0):
      print('Minibatch loss at step %d: %f' % (step, l))
      print('Minibatch accuracy: %.1f%%' % accuracy(predictions, batch_labels))
      print('Validation accuracy: %.1f%%' % accuracy(
        valid_prediction.eval(), valid_labels))
  print('Test accuracy: %.1f%%' % accuracy(test_prediction.eval(), test_labels))
  save_path = tf.train.Saver().save(session, "/tmp/model.ckpt")
  print("Model saved in file: %s" % save_path)

一切正常,模型存储在相应的文件夹中。

我又创建了一个 python 文件,我尝试在其中恢复模型但出现错误

# In[1]:
from __future__ import print_function
import numpy as np
import tensorflow as tf
from six.moves import cPickle as pickle
from six.moves import range


# In[3]:

image_size = 28
num_labels = 10
num_channels = 1 # grayscale
import numpy as np


# In[4]:

def accuracy(predictions, labels):
  return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1))
          / predictions.shape[0])


# In[8]:

batch_size = 16
patch_size = 5
depth = 16
num_hidden = 64

graph = tf.Graph()

with graph.as_default():

  '''# Input data.
  tf_train_dataset = tf.placeholder(
    tf.float32, shape=(batch_size, image_size, image_size, num_channels))
  tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels))
  tf_valid_dataset = tf.constant(valid_dataset)
  tf_test_dataset = tf.constant(test_dataset)'''

  # Variables.
  layer1_weights = tf.Variable(tf.truncated_normal(
      [patch_size, patch_size, num_channels, depth], stddev=0.1),name="layer1_weights")
  layer1_biases = tf.Variable(tf.zeros([depth]),name = "layer1_biases")
  layer2_weights = tf.Variable(tf.truncated_normal(
      [patch_size, patch_size, depth, depth], stddev=0.1),name = "layer2_weights")
  layer2_biases = tf.Variable(tf.constant(1.0, shape=[depth]),name ="layer2_biases")
  layer3_weights = tf.Variable(tf.truncated_normal(
      [image_size // 4 * image_size // 4 * depth, num_hidden], stddev=0.1),name="layer3_biases")
  layer3_biases = tf.Variable(tf.constant(1.0, shape=[num_hidden]),name = "layer3_biases")
  layer4_weights = tf.Variable(tf.truncated_normal(
      [num_hidden, num_labels], stddev=0.1),name = "layer4_weights")
  layer4_biases = tf.Variable(tf.constant(1.0, shape=[num_labels]),name = "layer4_biases")

  # Model.
  def model(data):
    conv = tf.nn.conv2d(data, layer1_weights, [1, 2, 2, 1], padding='SAME')
    hidden = tf.nn.relu(conv + layer1_biases)
    conv = tf.nn.conv2d(hidden, layer2_weights, [1, 2, 2, 1], padding='SAME')
    hidden = tf.nn.relu(conv + layer2_biases)
    shape = hidden.get_shape().as_list()
    reshape = tf.reshape(hidden, [shape[0], shape[1] * shape[2] * shape[3]])
    hidden = tf.nn.relu(tf.matmul(reshape, layer3_weights) + layer3_biases)
    return tf.matmul(hidden, layer4_weights) + layer4_biases

  '''# Training computation.
  logits = model(tf_train_dataset)
  loss = tf.reduce_mean(
    tf.nn.softmax_cross_entropy_with_logits(logits, tf_train_labels))

  # Optimizer.
  optimizer = tf.train.GradientDescentOptimizer(0.05).minimize(loss)'''

  # Predictions for the training, validation, and test data.
  #train_prediction = tf.nn.softmax(logits)
  #valid_prediction = tf.nn.softmax(model(tf_valid_dataset))
  #test_prediction = tf.nn.softmax(model(tf_test_dataset))

# In[17]:

#saver = tf.train.Saver()
with tf.Session() as sess:
  # Restore variables from disk.
  tf.train.Saver().restore(sess, "/tmp/model.ckpt")
  print("Model restored.")
  # Do some work with the model

我得到的错误是:

没有要保存的变量

任何帮助将不胜感激

【问题讨论】:

【参考方案1】:

这里的错误非常微妙。在In[8] 中,您创建一个名为graphtf.Graph,并将其设置为with graph.as_default(): 块的默认值。这意味着所有变量都是在graph 中创建的,如果您打印graph.all_variables(),您应该会看到一个变量列表。

但是,您在创建 (i) tf.Session 和 (ii) tf.train.Saver 之前退出 with 块。这意味着会话和保护程序是在一个不同的图表中创建的(全局默认tf.Graph,当您没有显式创建一个并将其设置为默认值时使用),其中不包含任何变量——或任何节点。

至少有两种解决方案:

    作为Yaroslav suggests,您可以在不使用with graph.as_default(): 块的情况下编写程序,从而避免与多个图形混淆。但是,这可能会导致 IPython 笔记本中不同单元格之间的名称冲突,这在使用 tf.train.Saver 时会很尴尬,因为它使用 tf.Variablename 属性作为检查点文件中的键。

    您可以在with graph.as_default():创建保护程序,并使用显式图形创建tf.Session,如下所示:

    with graph.as_default():
        # [Variable and model creation goes here.]
    
        saver = tf.train.Saver()  # Gets all variables in `graph`.
    
    with tf.Session(graph=graph) as sess:
        saver.restore(sess)
        # Do some work with the model....
    

    或者,您可以在with graph.as_default(): 块内创建tf.Session ,在这种情况下,它将使用graph 进行所有操作。

【讨论】:

感谢 mrry 的回答,我现在如何将我的图像传递给这个模型,从而对我的图像进行分类,我尝试在第二个 python 文件中编写的代码(我所在的文件恢复我的变量)是正确的还是需要修改才能完成 您可以尝试将图像数据提供给tf_valid_dataset 并获取valid_prediction。 (如果 tf_valid_datasettf.placeholder() 会更容易,这样您就可以将任何大小的输入提供给该张量。) 能否请您提供一个相同的代码 sn-p,实际上我是 Tensorflow 的新手,因此面临这些小困难。 你能提供一个代码 sn-p 吗,我已经尝试传递灰度图像,但我无法创建我必须传递的图像的 4D 张量。请帮我解决这个问题 很高兴为您提供帮助,但这与当前问题无关。随意添加一个新问题,其中包含您尝试过的内容的 sn-p 以及任何错误消息,我会回答。【参考方案2】:

您正在In[17] 中创建一个新会话,它会擦除​​您的变量。此外,如果您只有一个默认图表和一个默认会话,则不需要使用 with 块,您可以改为执行类似的操作

sess = tf.InteractiveSession()
layer1_weights = tf.Variable(tf.truncated_normal(
  [patch_size, patch_size, num_channels, depth], stddev=0.1),name="layer1_weights")
tf.train.Saver().restore(sess, "/tmp/model.ckpt")

【讨论】:

感谢您的回答 yaroslav 。

以上是关于Tensorflow 中没有变量可以保存错误的主要内容,如果未能解决你的问题,请参考以下文章

在 tensorflow 中恢复图形失败,因为没有要保存的变量

Tensorflow 中 8 位量化的致命错误

TensorFlow 2 自定义损失:“没有为任何变量提供梯度”错误

基本使用

我想在 anaconda 中安装 tensorflow,但它显示错误:

TensorFlow的安装