Bird
Raised Fist0
TensorFlowml~20 mins

Image generation basics in TensorFlow - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Image Generation Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Model Choice
intermediate
2:00remaining
Which model is best suited for generating new images from random noise?

You want to create a model that generates new images by starting from random noise vectors. Which model type is most appropriate for this task?

AA Generative Adversarial Network (GAN) with a generator and discriminator
BA Convolutional Neural Network (CNN) classifier trained on labeled images
CA Recurrent Neural Network (RNN) for sequence prediction
DA Linear Regression model predicting pixel values
Attempts:
2 left
💡 Hint

Think about models designed to create new data rather than classify or predict sequences.

❓ Predict Output
intermediate
2:00remaining
What is the shape of the generated image tensor?

Given the following TensorFlow code snippet that generates an image from a noise vector using a simple generator model, what is the shape of the output tensor?

TensorFlow
import tensorflow as tf
import numpy as np

noise_dim = 100
batch_size = 16

def simple_generator():
    model = tf.keras.Sequential([
        tf.keras.layers.Dense(7*7*64, use_bias=False, input_shape=(noise_dim,)),
        tf.keras.layers.BatchNormalization(),
        tf.keras.layers.LeakyReLU(),
        tf.keras.layers.Reshape((7, 7, 64)),
        tf.keras.layers.Conv2DTranspose(32, (5,5), strides=(2,2), padding='same', use_bias=False),
        tf.keras.layers.BatchNormalization(),
        tf.keras.layers.LeakyReLU(),
        tf.keras.layers.Conv2DTranspose(1, (5,5), strides=(2,2), padding='same', use_bias=False, activation='tanh')
    ])
    return model

model = simple_generator()
noise = tf.random.normal([batch_size, noise_dim])
generated_images = model(noise)
output_shape = generated_images.shape
A(16, 28, 28, 1)
B(100, 28, 28, 1)
C(16, 7, 7, 64)
D(16, 14, 14, 32)
Attempts:
2 left
💡 Hint

Look at the final Conv2DTranspose layer's stride and output channels.

❓ Metrics
advanced
2:00remaining
Which metric best evaluates the quality of generated images?

You have trained an image generator model. You want to measure how realistic the generated images are compared to real images. Which metric is most suitable for this?

AAccuracy of a classifier on generated images
BMean Squared Error (MSE) between generated and real images
CCross-entropy loss of the generator during training
DInception Score (IS) measuring image quality and diversity
Attempts:
2 left
💡 Hint

Consider metrics that capture both quality and variety of generated images.

🔧 Debug
advanced
2:00remaining
Why does this image generator model fail to train properly?

Consider this TensorFlow generator model code snippet. The training loss does not improve and generated images look like noise. What is the likely cause?

TensorFlow
import tensorflow as tf

def bad_generator():
    model = tf.keras.Sequential([
        tf.keras.layers.Dense(7*7*64, input_shape=(100,)),
        tf.keras.layers.BatchNormalization(),
        tf.keras.layers.ReLU(),
        tf.keras.layers.Reshape((7,7,64)),
        tf.keras.layers.Conv2DTranspose(32, (5,5), strides=(2,2), padding='same'),
        tf.keras.layers.BatchNormalization(),
        tf.keras.layers.ReLU(),
        tf.keras.layers.Conv2DTranspose(1, (5,5), strides=(2,2), padding='same', activation='sigmoid')
    ])
    return model
AInput shape should be (None, 100) instead of (100,)
BMissing 'use_bias=False' in Conv2DTranspose layers causes training failure
CUsing 'sigmoid' activation in the last layer instead of 'tanh' causes poor output scaling
DBatchNormalization layers should be removed for better training
Attempts:
2 left
💡 Hint

Think about the typical pixel value range for generated images and activation functions.

🧠 Conceptual
expert
2:00remaining
What is the role of the discriminator in a GAN during training?

In a Generative Adversarial Network (GAN), what is the main purpose of the discriminator model during training?

ATo reduce the dimensionality of input images for faster training
BTo classify images as real or generated, providing feedback to the generator
CTo generate new images from random noise vectors
DTo optimize the generator's weights directly using gradient descent
Attempts:
2 left
💡 Hint

Consider how the discriminator helps the generator improve.

Practice

(1/5)
1. What is the main role of a generator model in image generation using TensorFlow?
easy
A. To classify images into categories
B. To label images with tags
C. To reduce the size of images
D. To create new images from random noise inputs

Solution

  1. Step 1: Understand the generator's purpose

    The generator model takes random noise as input and learns to produce new images that look like real data.
  2. Step 2: Differentiate from other models

    Unlike classifiers or reducers, the generator's job is to create images, not to label or compress them.
  3. Final Answer:

    To create new images from random noise inputs -> Option D
  4. Quick Check:

    Generator creates images = B [OK]
Hint: Generator turns noise into images step-by-step [OK]
Common Mistakes:
  • Confusing generator with classifier
  • Thinking generator compresses images
  • Assuming generator labels images
2. Which of the following TensorFlow code snippets correctly defines a simple generator model layer that upsamples noise to a 7x7x128 feature map?
easy
A. tf.keras.layers.MaxPooling2D((2,2))
B. tf.keras.layers.Dense(7*7*128, use_bias=False, input_shape=(100,))
C. tf.keras.layers.Conv2D(128, (3,3), activation='relu')
D. tf.keras.layers.Flatten()

Solution

  1. Step 1: Identify the layer that creates a 7x7x128 feature map from noise

    The Dense layer with units 7*7*128 reshapes noise vector into a flat feature map for upsampling.
  2. Step 2: Check other options

    Conv2D applies convolution but does not reshape noise directly; MaxPooling2D reduces size; Flatten converts to 1D.
  3. Final Answer:

    tf.keras.layers.Dense(7*7*128, use_bias=False, input_shape=(100,)) -> Option B
  4. Quick Check:

    Dense layer reshapes noise = C [OK]
Hint: Dense layer with units = 7*7*128 reshapes noise [OK]
Common Mistakes:
  • Using Conv2D before reshaping noise
  • Choosing pooling layers for upsampling
  • Flattening noise vector instead of reshaping
3. Given the following TensorFlow code snippet for generating an image, what will be the shape of the output image tensor?
noise = tf.random.normal([1, 100])
generated_image = generator(noise, training=False)

Assume the generator outputs images of shape (28, 28, 1).
medium
A. (1, 28, 28, 1)
B. (28, 28, 1)
C. (100, 28, 28, 1)
D. (1, 100)

Solution

  1. Step 1: Understand input noise shape

    The noise tensor has shape (1, 100), where 1 is batch size and 100 is noise dimension.
  2. Step 2: Check generator output shape

    The generator outputs images shaped (28, 28, 1) per input sample, so output shape includes batch size: (1, 28, 28, 1).
  3. Final Answer:

    (1, 28, 28, 1) -> Option A
  4. Quick Check:

    Batch size + image shape = (1, 28, 28, 1) [OK]
Hint: Output shape includes batch size from input noise [OK]
Common Mistakes:
  • Ignoring batch size dimension
  • Confusing noise dimension with image size
  • Assuming output shape matches noise shape
4. You wrote this TensorFlow code to generate images but get an error:
noise = tf.random.normal([100])
generated_image = generator(noise, training=False)

What is the likely cause of the error?
medium
A. Noise input is missing batch dimension
B. Generator model is not compiled
C. Noise tensor has wrong data type
D. Training flag must be True for generation

Solution

  1. Step 1: Check noise input shape

    The noise tensor shape is (100,), missing batch dimension which should be (1, 100) or more.
  2. Step 2: Understand generator input requirements

    Generator expects batch dimension to process inputs; missing it causes shape mismatch error.
  3. Final Answer:

    Noise input is missing batch dimension -> Option A
  4. Quick Check:

    Batch dimension required in noise input = A [OK]
Hint: Add batch size dimension to noise input shape [OK]
Common Mistakes:
  • Passing 1D noise without batch size
  • Assuming training flag affects input shape
  • Ignoring model compilation errors
5. You want to generate 5 new images using a trained TensorFlow generator model. Which code snippet correctly generates and displays these images using matplotlib?
hard
A. noise = tf.random.normal([5, 100]) generated_images = generator(noise) plt.imshow(generated_images, cmap='gray') plt.show()
B. noise = tf.random.normal([1, 100]) generated_images = generator(noise, training=False) plt.imshow(generated_images, cmap='gray') plt.show()
C. noise = tf.random.normal([5, 100]) generated_images = generator(noise, training=False) for i in range(5): plt.subplot(1, 5, i+1) plt.imshow(generated_images[i, :, :, 0], cmap='gray') plt.axis('off') plt.show()
D. noise = tf.random.normal([5]) generated_images = generator(noise, training=True) plt.imshow(generated_images[0], cmap='gray') plt.show()

Solution

  1. Step 1: Generate noise for 5 images

    Noise shape [5, 100] creates batch of 5 inputs for generator.
  2. Step 2: Generate images and plot each

    Loop over generated_images to plot each image separately with plt.subplot and plt.imshow.
  3. Step 3: Check other options

    noise = tf.random.normal([1, 100]) generated_images = generator(noise, training=False) plt.imshow(generated_images, cmap='gray') plt.show() generates only 1 image; another misses training=False and plots batch incorrectly; another has wrong noise shape and training mode.
  4. Final Answer:

    noise = tf.random.normal([5, 100]) generated_images = generator(noise, training=False) for i in range(5): plt.subplot(1, 5, i+1) plt.imshow(generated_images[i, :, :, 0], cmap='gray') plt.axis('off') plt.show() -> Option C
  5. Quick Check:

    Batch noise + loop display = A [OK]
Hint: Use batch noise and loop to display images with matplotlib [OK]
Common Mistakes:
  • Using wrong noise shape for batch
  • Not looping to display each image
  • Forgetting training=False during generation
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard