Tensorflow程序陷入无限训练循环

时间:2019-06-25 20:14:40

标签: python tensorflow

我正在使用GAN教程中的代码在Tensorflow中生成MNIST数字。

(此处链接:https://www.tensorflow.org/beta/tutorials/generative/dcgan

当前,程序陷入了无限的训练循环。我将训练数据集设置为仅一张图像,并设置epoch =1。我在循环中插入了打印语句。在train()函数中,它仅打印a和b,但不打印c,这意味着它在第二个for循环中陷入了无限循环。

我在这里加载,随机播放和批处理数据(训练数据集仅是用于测试目的的一张图像)

(train_images, train_labels), (_, _) = tf.keras.datasets.mnist.load_data()
train_images = train_images.reshape(train_images.shape[0], 28, 28, 1).astype('float32')
train_images = (train_images - 127.5) / 127.5 # Normalize the images to [-1, 1]
train_images = train_images[0:1,:,:,:]
print(train_images.shape)

BUFFER_SIZE = 1
BATCH_SIZE = 1

# Batch and shuffle the data
train_dataset = tf.data.Dataset.from_tensor_slices(train_images).shuffle(BUFFER_SIZE).batch(BATCH_SIZE)
print(train_dataset)

这些是定义生成器和鉴别器模型损耗的函数

def make_generator_model():
    ...
    return model

generator = make_generator_model()
noise = np.random.normal(size=(1, 100))
generated_image = generator.predict(noise)

def make_discriminator_model():
    ...
    return model

discriminator = make_discriminator_model()
decision = discriminator.predict(generated_image)

cross_entropy = tf.keras.losses.BinaryCrossentropy(from_logits=True)

def discriminator_loss(real_output, fake_output):
    ...
    return total_loss

def generator_loss(fake_output):
    return cross_entropy(tf.ones_like(fake_output), fake_output)

generator_optimizer = tf.keras.optimizers.Adam(1e-4)
discriminator_optimizer = tf.keras.optimizers.Adam(1e-4)

这些是训练功能:

EPOCHS = 1
noise_dim = 100
seed = tf.random.normal([num_examples_to_generate, noise_dim])

def train_step(images):
    noise = tf.random.normal([BATCH_SIZE, noise_dim])

    with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape:
      generated_images = generator(noise, training=True)
      print(images.shape)
      real_output = discriminator(images, training=True)
      fake_output = discriminator(generated_images, training=True)

      gen_loss = generator_loss(fake_output)
      disc_loss = discriminator_loss(real_output, fake_output)

    gradients_of_generator = gen_tape.gradient(gen_loss, generator.trainable_variables)
    gradients_of_discriminator = disc_tape.gradient(disc_loss, discriminator.trainable_variables)

    generator_optimizer.apply_gradients(zip(gradients_of_generator, generator.trainable_variables))
    discriminator_optimizer.apply_gradients(zip(gradients_of_discriminator, discriminator.trainable_variables))

def train(dataset, epochs):
    for epoch in range(epochs):
        start = time.time()

        for image_batch in dataset: #stuck in an infinite loop
            print('a')
            train_step(image_batch)
            print('b')

        print('c')
        # Produce images for the GIF as we go
        display.clear_output(wait=True)
        generate_and_save_images(generator,epoch + 1,seed)
        print('d')

        # Save the model every 1 epochs
        if (epoch + 1) % 1 == 0:
            checkpoint.save(file_prefix = checkpoint_prefix)

        print ('Time for epoch {} is {} sec'.format(epoch + 1, time.time()-start))

    # Generate after the final epoch
    display.clear_output(wait=True)
    generate_and_save_images(generator,epochs,seed)

def generate_and_save_images(model, epoch, test_input):
  ...

train(train_dataset, EPOCHS)

2 个答案:

答案 0 :(得分:0)

解决了。原来我使用的是tensorflow 1.14,但是代码是用tensorflow 2.0编写的。在tf 1.x中,我需要一个迭代器来摆脱无限循环。

答案 1 :(得分:0)

您需要手动中断循环,否则它将无限期运行。来自documentation

for e in range(epochs):
    print('Epoch', e)
    batches = 0
    for x_batch, y_batch in datagen.flow(x_train, y_train, batch_size=32):
        model.fit(x_batch, y_batch)
        batches += 1
        if batches >= len(x_train) / 32:  # break loop here
            # we need to break the loop by hand because
            # the generator loops indefinitely
            break