How can Tensorflow be used with the flower dataset to compile and fit the model?

The flower dataset can be compiled and fit to a model using TensorFlow's compile() and fit() methods. The compile() method configures the model with optimizer, loss function, and metrics, while fit() trains the model using training and validation datasets over a specified number of epochs.

Read More: What is TensorFlow and how Keras work with TensorFlow to create Neural Networks?

We will be using the flowers dataset, which contains images of several thousands of flowers organized into 5 sub-directories, with one sub-directory for each flower class.

Compiling the Model

The first step is to compile the model by specifying the optimizer, loss function, and evaluation metrics ?

import tensorflow as tf

print("The model is being compiled")
model.compile(
    optimizer='adam',
    loss=tf.losses.SparseCategoricalCrossentropy(from_logits=True),
    metrics=['accuracy']
)

Fitting the Model

Once compiled, we fit the model to the training data with validation monitoring ?

print("The model is being fit to the data")
history = model.fit(
    train_ds,
    validation_data=val_ds,
    epochs=3
)

Code credit: https://www.tensorflow.org/tutorials/load_data/images

Output

The model is being compiled
The model is being fit to the data
Epoch 1/3
92/92 [==============================] - 107s 1s/step - loss: 1.3570 - accuracy: 0.4183 - val_loss: 1.0730 - val_accuracy: 0.5913
Epoch 2/3
92/92 [==============================] - 101s 1s/step - loss: 1.0185 - accuracy: 0.5927 - val_loss: 1.0041 - val_accuracy: 0.6199
Epoch 3/3
92/92 [==============================] - 95s 1s/step - loss: 0.8691 - accuracy: 0.6529 - val_loss: 0.9985 - val_accuracy: 0.6281
<tensorflow.python.keras.callbacks.History at 0x7f2cdcbbba90>

Key Parameters

  • optimizer='adam': Adam optimizer adapts learning rates for each parameter
  • loss function: SparseCategoricalCrossentropy for multi-class classification
  • metrics: Accuracy to monitor model performance
  • epochs=3: Number of complete passes through the training data

Model Performance Analysis

Examining the training results reveals important insights about model behavior ?

  • Training accuracy improves from 41.8% to 65.3% over 3 epochs
  • Validation accuracy increases from 59.1% to 62.8%
  • The gap between training and validation accuracy indicates potential overfitting
  • Loss decreases consistently for both training and validation sets

Conclusion

TensorFlow's compile() and fit() methods provide a straightforward approach to training neural networks on the flower dataset. While the model shows learning progress, the accuracy gap suggests implementing regularization techniques to reduce overfitting.

Updated on: 2026-03-25T15:59:02+05:30

245 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements