Project: Flower Classifier with Transfer Learning

Deep Learning with Keras and TensorFlow 14 min min read Updated: Nov 16, 2026 Advanced
Project: Flower Classifier with Transfer Learning
Advanced Topic 6 of 7

Project Goal

Classify photos of flowers into five classes: daisy, dandelion, roses, sunflowers and tulips. The popular flower_photos dataset has about 3,600 images. We use transfer learning so that a small dataset is enough.

Step 1: Download Data

python import keras import tensorflow as tf url = "https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz" data_dir = keras.utils.get_file("flower_photos", origin=url, untar=True) print(data_dir)
If the download is blocked: Download the dataset manually and place it in folders named by class, as you learned in the image dataset lesson.

Step 2: Create Datasets

python IMG = (224, 224) common = dict(validation_split=0.2, seed=7, image_size=IMG, batch_size=32) train_ds = keras.utils.image_dataset_from_directory(data_dir, subset="training", **common) val_ds = keras.utils.image_dataset_from_directory(data_dir, subset="validation", **common) class_names = train_ds.class_names print(class_names) AUTOTUNE = tf.data.AUTOTUNE train_ds = train_ds.cache().shuffle(1000).prefetch(AUTOTUNE) val_ds = val_ds.cache().prefetch(AUTOTUNE)

Step 3: Build the Model

python from keras import layers base = keras.applications.EfficientNetB0( include_top=False, weights="imagenet", input_shape=IMG + (3,)) base.trainable = False inputs = keras.Input(shape=IMG + (3,)) x = layers.RandomFlip("horizontal")(inputs) x = layers.RandomRotation(0.1)(x) x = layers.RandomZoom(0.1)(x) x = base(x, training=False) # EfficientNet has its own scaling inside x = layers.GlobalAveragePooling2D()(x) x = layers.Dropout(0.3)(x) outputs = layers.Dense(len(class_names), activation="softmax")(x) model = keras.Model(inputs, outputs) model.compile(optimizer=keras.optimizers.Adam(1e-3), loss="sparse_categorical_crossentropy", metrics=["accuracy"])
Good to know: Keras EfficientNet models expect pixel values from 0 to 255 and handle the scaling internally, so do not divide by 255 here.

Step 4: Train the Head

python cb = [keras.callbacks.EarlyStopping(patience=3, restore_best_weights=True)] model.fit(train_ds, validation_data=val_ds, epochs=10, callbacks=cb)

Step 5: Fine-Tune

python base.trainable = True for layer in base.layers[:-30]: layer.trainable = False # unfreeze only the last 30 layers model.compile(optimizer=keras.optimizers.Adam(1e-5), loss="sparse_categorical_crossentropy", metrics=["accuracy"]) model.fit(train_ds, validation_data=val_ds, epochs=5, callbacks=cb)

Step 6: Evaluate and Inspect Errors

python import numpy as np from sklearn.metrics import classification_report y_true, y_pred = [], [] for images, labels in val_ds: y_true.extend(labels.numpy()) y_pred.extend(model.predict(images, verbose=0).argmax(axis=1)) print(classification_report(y_true, y_pred, target_names=class_names))

A good result is around 90 to 95 percent validation accuracy.

Step 7: Save and Predict

python model.save("flowers.keras") img = keras.utils.load_img("my_flower.jpg", target_size=IMG) x = np.expand_dims(keras.utils.img_to_array(img), 0) probs = model.predict(x)[0] print(class_names[probs.argmax()], f"{probs.max():.0%}")

Make It Portfolio-Ready

  • Add a Streamlit app for uploads
  • Write a README with accuracy and example images
  • Convert the model to TFLite for a mobile demo

Conclusion

You combined data loading, augmentation, transfer learning, fine-tuning and evaluation in one project. This workflow works for most image problems.

Quick Summary: Load folders, augment, freeze EfficientNet, train a head, fine-tune the top layers and evaluate per class.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators