FailedPreconditionError:尝试将未初始化的值conv2d_1 / kernel与Tensorflow / Python一起使用

时间:2018-04-26 18:09:12

标签: python tensorflow

我正在尝试借助以下代码创建CNN模型:

import tensorflow as tf

class Create_CNN:
  def _conv(self, input, nChannels, kernelSize, kernelStride):
    conv = tf.layers.conv2d(inputs=input,
                            filters=nChannels,
                            kernel_size=kernelSize,
                            strides=(kernelStride, kernelStride),
                            padding='same',
                            activation=tf.nn.relu
                            )
    return conv

  def create_cnn(self, input, nChannels, kernelSize, kernelStride):
    input = tf.reshape(input, shape=[-1, 500, 530, 3])
    layer1 = Create_CNN()._conv(input, nChannels, kernelSize, kernelStride)
    layer2 = Create_CNN()._conv(layer1, nChannels, kernelSize, kernelStride)
    layer3 = Create_CNN()._conv(layer2, nChannels, kernelSize, kernelStride)
    layer4 = Create_CNN()._conv(layer3, nChannels, kernelSize, kernelStride)
    layer5 = Create_CNN()._conv(layer4, nChannels, kernelSize, kernelStride)
    return layer5

这里,我输入的是500 * 530 * 3尺寸的图像。我正在尝试使用以下代码传递输入和其他参数:

with tf.Session().as_default():
      tf.global_variables_initializer().run()
      i = PlantUtils().create_instance('ara2013_plant001_rgb.png', 'ara2013_plant001_label.png', 500, 530, 100, 106, 1, 1,
                                 1)
      input_image = i[0] # It is a 500 * 530 * 3 tensor
      b = Create_CNN().create_cnn(input=input_image, kernelSize=3, kernelStride=1, nChannels=30)
      x = tf.argmax(input=b, axis=1)
      print x.eval()

当我尝试打印logits(表示x的值)时,我收到以下错误:

FailedPreconditionError (see above for traceback): Attempting to use uninitialized value conv2d_1/kernel

我不确定我做错了什么。我需要看看我的CNN模型生成的logits。我真的需要帮助。

1 个答案:

答案 0 :(得分:2)

这种情况正在发生,因为您正在构建图表之前运行初始化程序 。理想情况下,您应该在创建Graph之前构建Session。试试这个

with tf.Graph().as_default():
  i = PlantUtils().create_instance('ara2013_plant001_rgb.png', 'ara2013_plant001_label.png', 500, 530, 100, 106, 1, 1, 1)
  input_image = i[0] # It is a 500 * 530 * 3 tensor
  b = Create_CNN().create_cnn(input=input_image, kernelSize=3, kernelStride=1, nChannels=30)
  x = tf.argmax(input=b, axis=1)
  with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print sess.run(x)