Bird
Raised Fist0
TensorFlowml~20 mins

Image segmentation basics in TensorFlow - ML Experiment: Train & Evaluate

Choose your learning style10 modes available
Experiment - Image segmentation basics
Problem:Segment objects in images by classifying each pixel correctly.
Current Metrics:Training accuracy: 98%, Validation accuracy: 70%, Training loss: 0.05, Validation loss: 0.35
Issue:The model overfits: training accuracy is very high but validation accuracy is much lower.
Your Task
Reduce overfitting so validation accuracy improves to above 85% while keeping training accuracy below 92%.
Keep the same dataset and model architecture (U-Net style).
Only adjust hyperparameters and add regularization techniques.
Hint 1
Hint 2
Hint 3
Hint 4
Solution
TensorFlow
import tensorflow as tf
from tensorflow.keras import layers, models
from tensorflow.keras.preprocessing.image import ImageDataGenerator

# Define a simple U-Net model
inputs = layers.Input(shape=(128, 128, 3))

# Encoder
c1 = layers.Conv2D(16, (3, 3), activation='relu', padding='same')(inputs)
c1 = layers.Dropout(0.1)(c1)
c1 = layers.Conv2D(16, (3, 3), activation='relu', padding='same')(c1)
p1 = layers.MaxPooling2D((2, 2))(c1)

c2 = layers.Conv2D(32, (3, 3), activation='relu', padding='same')(p1)
c2 = layers.Dropout(0.1)(c2)
c2 = layers.Conv2D(32, (3, 3), activation='relu', padding='same')(c2)
p2 = layers.MaxPooling2D((2, 2))(c2)

# Bottleneck
b1 = layers.Conv2D(64, (3, 3), activation='relu', padding='same')(p2)
b1 = layers.Dropout(0.2)(b1)
b1 = layers.Conv2D(64, (3, 3), activation='relu', padding='same')(b1)

# Decoder
u1 = layers.UpSampling2D((2, 2))(b1)
u1 = layers.concatenate([u1, c2])
c3 = layers.Conv2D(32, (3, 3), activation='relu', padding='same')(u1)
c3 = layers.Dropout(0.1)(c3)
c3 = layers.Conv2D(32, (3, 3), activation='relu', padding='same')(c3)

u2 = layers.UpSampling2D((2, 2))(c3)
u2 = layers.concatenate([u2, c1])
c4 = layers.Conv2D(16, (3, 3), activation='relu', padding='same')(u2)
c4 = layers.Dropout(0.1)(c4)
c4 = layers.Conv2D(16, (3, 3), activation='relu', padding='same')(c4)

outputs = layers.Conv2D(1, (1, 1), activation='sigmoid')(c4)

model = models.Model(inputs=[inputs], outputs=[outputs])

model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.0005),
              loss='binary_crossentropy',
              metrics=['accuracy'])

# Data augmentation
train_datagen = ImageDataGenerator(
    rotation_range=15,
    width_shift_range=0.1,
    height_shift_range=0.1,
    horizontal_flip=True,
    vertical_flip=True,
    fill_mode='nearest')

# Assuming X_train, y_train, X_val, y_val are numpy arrays of images and masks
# For demonstration, placeholders are used here
import numpy as np
X_train = np.random.rand(100, 128, 128, 3).astype('float32')
y_train = np.random.randint(0, 2, (100, 128, 128, 1)).astype('float32')
X_val = np.random.rand(20, 128, 128, 3).astype('float32')
y_val = np.random.randint(0, 2, (20, 128, 128, 1)).astype('float32')

batch_size = 8
train_generator = train_datagen.flow(X_train, y_train, batch_size=batch_size)

early_stop = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=5, restore_best_weights=True)

history = model.fit(train_generator,
                    steps_per_epoch=len(X_train)//batch_size,
                    epochs=50,
                    validation_data=(X_val, y_val),
                    callbacks=[early_stop])
Added dropout layers after convolution layers to reduce overfitting.
Implemented data augmentation to increase training data variety.
Lowered learning rate from default to 0.0005 for smoother training.
Added early stopping to stop training when validation loss stops improving.
Results Interpretation

Before: Training accuracy 98%, Validation accuracy 70%, Training loss 0.05, Validation loss 0.35

After: Training accuracy 90%, Validation accuracy 87%, Training loss 0.15, Validation loss 0.22

Adding dropout and data augmentation reduces overfitting, improving validation accuracy while slightly lowering training accuracy. Early stopping prevents wasting time on over-training.
Bonus Experiment
Try replacing dropout with batch normalization layers and compare the validation accuracy.
💡 Hint
Batch normalization can stabilize and speed up training, sometimes reducing overfitting.

Practice

(1/5)
1. What is the main goal of image segmentation in TensorFlow?
easy
A. To compress images without losing quality
B. To label each pixel in an image with a class
C. To generate random noise images
D. To classify the entire image into one category

Solution

  1. Step 1: Understand image segmentation purpose

    Image segmentation assigns a class label to every pixel, dividing the image into meaningful parts.
  2. Step 2: Compare with other tasks

    Unlike classification, which labels the whole image, segmentation works at pixel level.
  3. Final Answer:

    To label each pixel in an image with a class -> Option B
  4. Quick Check:

    Image segmentation = pixel-wise labeling [OK]
Hint: Segmentation means labeling pixels, not whole images [OK]
Common Mistakes:
  • Confusing segmentation with image classification
  • Thinking segmentation compresses images
  • Believing segmentation creates random images
2. Which TensorFlow layer is commonly used to extract features for image segmentation?
easy
A. Convolutional layer
B. Dense layer
C. Dropout layer
D. Flatten layer

Solution

  1. Step 1: Identify feature extraction layers

    Convolutional layers scan images to find patterns and features useful for segmentation.
  2. Step 2: Understand other layers' roles

    Dense layers are for classification, dropout prevents overfitting, flatten reshapes data but doesn't extract features.
  3. Final Answer:

    Convolutional layer -> Option A
  4. Quick Check:

    Feature extraction = convolutional layers [OK]
Hint: Convolutional layers find image features [OK]
Common Mistakes:
  • Choosing dense layers for feature extraction
  • Confusing flatten with convolution
  • Ignoring convolution's role in images
3. What will be the shape of the output tensor after applying a softmax activation on a segmentation model predicting 3 classes for a 128x128 image?
medium
A. (128, 128, 3)
B. (3, 128, 128)
C. (128, 3, 128)
D. (128, 128)

Solution

  1. Step 1: Understand output shape for segmentation

    Each pixel has a probability for each class, so output shape is height x width x classes.
  2. Step 2: Apply to given image and classes

    Image size is 128x128, classes are 3, so output shape is (128, 128, 3).
  3. Final Answer:

    (128, 128, 3) -> Option A
  4. Quick Check:

    Output shape = (height, width, classes) [OK]
Hint: Output shape = image size + number of classes [OK]
Common Mistakes:
  • Mixing class dimension position
  • Forgetting classes dimension
  • Using 2D shape instead of 3D
4. Given this TensorFlow code snippet for segmentation, what is the error?
model = tf.keras.Sequential([
  tf.keras.layers.Conv2D(16, 3, activation='relu', input_shape=(64, 64, 3)),
  tf.keras.layers.Dense(3, activation='softmax')
])
medium
A. Conv2D kernel size must be 1
B. Input shape is incorrect for images
C. Activation 'relu' is invalid
D. Dense layer cannot follow Conv2D without flattening

Solution

  1. Step 1: Check layer sequence

    Conv2D outputs 4D tensor, Dense expects 2D input, so flattening is needed before Dense.
  2. Step 2: Validate other options

    Input shape is valid for images, 'relu' is a valid activation, kernel size 3 is allowed.
  3. Final Answer:

    Dense layer cannot follow Conv2D without flattening -> Option D
  4. Quick Check:

    Dense after Conv2D needs flattening [OK]
Hint: Dense layers need flat input, add Flatten after Conv2D [OK]
Common Mistakes:
  • Ignoring tensor shape mismatch
  • Thinking kernel size must be 1
  • Misunderstanding activation functions
5. You want to train a simple segmentation model in TensorFlow. Which data do you need to provide during training?
hard
A. Only images without labels
B. Images and image-level class labels
C. Images and their pixel-level masks
D. Random noise images

Solution

  1. Step 1: Identify training data for segmentation

    Segmentation requires images and masks labeling each pixel's class to learn pixel-wise predictions.
  2. Step 2: Compare with other data types

    Image-level labels are for classification, no labels means no supervision, noise images are irrelevant.
  3. Final Answer:

    Images and their pixel-level masks -> Option C
  4. Quick Check:

    Training segmentation = images + pixel masks [OK]
Hint: Segmentation training needs pixel masks, not just labels [OK]
Common Mistakes:
  • Using only image-level labels
  • Training without masks
  • Confusing segmentation with classification data
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