张量()不是此图的元素

时间:2019-01-28 11:13:00

标签: python tensorflow deep-learning

我是tensorflow的新手,我正在尝试通过在jupyter笔记本中使用此示例来实现GAN。

Example here

我没有使用本示例中使用的MNIST数据集,而是尝试使用自己的数据集。我正在创建一个输入管道,以读取TFRecords文件并生成随机批图像。为了将对象与随机选择的一批图像相关联,我正在使用此函数tf.train.shuffle_batch()。但是,一旦我开始训练并运行sess.run([image_batch])以获取随机的一批图像,就会出现此错误。

“ ValueError:无法将获取参数解释为张量。(张量Tensor(“ shuffle_batch:0”,shape =(100,4096),dtype = float32)不是该图的元素。)“

此错误是因为我分别编写了get_image()函数吗?

这是完整的代码:

# imports 
# Paths to DIRs


IMAGE_WIDTH = 64
IMAGE_HEIGHT = 64

def get_image(files, num_classes):
 # Convert filenames to a queue for an input pipeline.
 file_queue = tf.train.string_input_producer(files)
 # Create object to read TFRecords.
 reader = tf.TFRecordReader()
 # Read the full set of features for a single example.
 key, example = reader.read(file_queue)

 # Parse the example to get a dict mapping feature keys to tensors.
 # image/class/label: integer denoting the index in a classification layer.
 # image/encoded: string containing JPEG encoded image
 features = tf.parse_single_example(
    example,
    features={
        'image/class/label': tf.FixedLenFeature([], tf.int64),
        'image/encoded': tf.FixedLenFeature([], dtype=tf.string,
                                            default_value='')
    })

 label = features['image/class/label']
 image_encoded = features['image/encoded']

 # Decode the JPEG.
 image = tf.image.decode_jpeg(image_encoded, channels=1)
 image = tf.image.convert_image_dtype(image, dtype=tf.float32)
 image = tf.reshape(image, [IMAGE_WIDTH*IMAGE_HEIGHT])

 # Represent the label as a one hot vector.
 label = tf.stack(tf.one_hot(label, num_classes))
 return image

labels = io.open(DEFAULT_LABEL_FILE, 'r', encoding='utf-8').read().splitlines()
num_classes = len(labels)

print('Processing data...')

tf_record_pattern = os.path.join(DEFAULT_TFRECORDS_DIR, '%s-*' % 'train')
train_data_files = tf.gfile.Glob(tf_record_pattern)
image = get_image(train_data_files, num_classes)

# Associate objects with a randomly selected batch of labels and images.
image_batch = tf.train.shuffle_batch(
[image], batch_size=100,
capacity=2000,
min_after_dequeue=1000)

def model_inputs(real_dim, z_dim):
 inputs_real = tf.placeholder(tf.float32, (None, real_dim), name='input_real') 
 inputs_z = tf.placeholder(tf.float32, (None, z_dim), name='input_z')

 return inputs_real, inputs_z

def generator(z, out_dim, n_units=128, reuse=False, alpha=0.01):
.
.
# return output

def discriminator(x, n_units=128, reuse=False, alpha=0.01):
.
.
# return output

# Size of input image to discriminator
input_size = 4096
# Size of latent vector to generator
z_size = 100
# Sizes of hidden layers in generator and discriminator
g_hidden_size = 128
d_hidden_size = 128
# Leak factor for leaky ReLU
alpha = 0.01  
# Smoothing 
smooth = 0.1

tf.reset_default_graph()

# Create our input placeholders
input_real, input_z = model_inputs(input_size, z_size)

# Build the model
g_model = generator(input_z, input_size, n_units=g_hidden_size, alpha=alpha)
# g_model is the generator output

d_model_real, d_logits_real = discriminator(input_real, n_units=d_hidden_size, alpha=alpha)
d_model_fake, d_logits_fake = discriminator(g_model, reuse=True, n_units=d_hidden_size, alpha=alpha)

# Calculate losses 

# Optimizers
learning_rate = 0.002

# Get the trainable_variables, split into G and D parts
t_vars = tf.trainable_variables()
g_vars = [var for var in t_vars if var.name.startswith('generator')]
d_vars = [var for var in t_vars if var.name.startswith('discriminator')]

d_train_opt = tf.train.AdamOptimizer(learning_rate).minimize(d_loss, var_list=d_vars)
g_train_opt = tf.train.AdamOptimizer(learning_rate).minimize(g_loss, var_list=g_vars)

batch_size = 100
epochs = 100
samples = []
losses = []
# Only save generator variables
saver = tf.train.Saver(var_list=g_vars)
with tf.Session() as sess:
 sess.run(tf.global_variables_initializer())

 # Initialize the queue threads.
 coord = tf.train.Coordinator()
 threads = tf.train.start_queue_runners(coord=coord)
 for e in range(epochs):
    for ii in range(391510//batch_size): # training_images//batchsize
        # Get a random batch of images.
        batch = sess.run([image_batch])

        # Get images, reshape and rescale to pass to D
        batch_images = batch[0].reshape((batch_size, 4096))
        batch_images = batch_images*2 - 1
        # Sample random noise for G
        batch_z = np.random.uniform(-1, 1, size=(batch_size, z_size))

        # Run optimizers
        _ = sess.run(d_train_opt, feed_dict={input_real: batch_images, input_z: batch_z})
        _ = sess.run(g_train_opt, feed_dict={input_z: batch_z})

    # At the end of each epoch, get the losses and print them out
    train_loss_d = sess.run(d_loss, {input_z: batch_z, input_real: batch_images})
    train_loss_g = g_loss.eval({input_z: batch_z})

# calculate accuracy
# Save training generator samples
with open('train_samples.pkl', 'wb') as f:
 pkl.dump(samples, f)

# Stop queue threads and close session.
coord.request_stop()
coord.join(threads)
sess.close()           

1 个答案:

答案 0 :(得分:0)

在代码中,创建image_batch张量后,您将使用“ tf.reset_default_graph()”来重置图形。

因此,将重置图,并且在重置图之前创建的所有张量不再是新图的元素,因此,您将收到此错误。

重置图形并检查后,创建所有需要的张量。应该可以。