<jupyter_start><jupyter_text>Tf-Flower - Image Classification ProblemClassifying different types of flowers using a ``CNN`` with ``tensorflow`` and ``keras``  Imports<jupyter_code>import tensorflow_datasets as tfds
import tensorflow as tf
import numpy as np
from matplotlib import pyplot as plt
import math, cv2
tfds.list_builders()[:]<jupyter_output><empty_output><jupyter_text>Data Preperation<jupyter_code>ds = tfds.load(name='tf_flowers', split="train")<jupyter_output>[1mDownloading and preparing dataset tf_flowers/3.0.1 (download: 218.21 MiB, generated: 221.83 MiB, total: 440.05 MiB) to /root/tensorflow_datasets/tf_flowers/3.0.1...[0m<jupyter_text>Class Names<jupyter_code>class_names =np.array(['dandelion', 'daisy', 'tulips', 'sunflowers', 'roses'])<jupyter_output><empty_output><jupyter_text>Iterating over the ``dataset``<jupyter_code>flowers =[data for data in ds]

# for data in ds:
#   print(data['image'], data['label'])
#   break<jupyter_output><empty_output><jupyter_text>Separating `images` and `labels`<jupyter_code>y =tf.constant([data['label'].numpy() for data in ds])
X_images =[]
for data in ds:
  image = cv2.resize(data['image'].numpy()/255, (200, 200))
  X_images.append(image)
X = tf.constant(X_images)
X.shape
X.shape, X[0]<jupyter_output><empty_output><jupyter_text>Showing some sample Images<jupyter_code>def display_images(images_and_classes, labels, cols=5):
  rows = 3
  fig = plt.figure()
  fig.set_size_inches(cols * 2, rows * 2)
  for i, (image, label) in enumerate(zip(images_and_classes, labels)):
    plt.subplot(rows, cols, i + 1)
    plt.axis('off')
    plt.imshow(image)
    plt.title(class_names[label])

display_images(X[:15], y)<jupyter_output><empty_output><jupyter_text>Model Creation<jupyter_code>input_shape = X[0].shape
input_shape
model = tf.keras.Sequential([
    tf.keras.layers.Conv2D(128, (3, 3), strides=1, input_shape=input_shape, activation='relu') ,
    tf.keras.layers.MaxPooling2D(2, 2),
    tf.keras.layers.Conv2D(64, (2, 2), activation='relu'), 
    tf.keras.layers.MaxPooling2D(2, 2),
    tf.keras.layers.Conv2D(64, (2, 2), activation='relu'),   
    tf.keras.layers.MaxPooling2D(2, 2),
    tf.keras.layers.Conv2D(32, (2, 2), activation='relu'),  
    tf.keras.layers.MaxPooling2D(2, 2),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(32, activation='relu'),
    tf.keras.layers.Dense(16, activation='relu'),
    tf.keras.layers.Dense(5, activation='softmax')
], name="flowers_classifier")

model.compile(
    optimizer = tf.keras.optimizers.Adam(lr=0.001),
    metrics=['accuracy'],
    loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
)
VAL_SPLIT = .2
BATCH_SIZE = 32
VERBOSE = 1
EPOCHS = 2

history = model.fit(X, y, batch_size=BATCH_SIZE, epochs=EPOCHS, verbose=VERBOSE, validation_split=VAL_SPLIT)<jupyter_output>Epoch 1/2
92/92 [==============================] - 353s 4s/step - loss: 1.4041 - accuracy: 0.3614 - val_loss: 1.3379 - val_accuracy: 0.3787
Epoch 2/2
92/92 [==============================] - 342s 4s/step - loss: 1.2494 - accuracy: 0.4724 - val_loss: 1.1918 - val_accuracy: 0.5150<jupyter_text>The model is undetrained, if we increase number of epochs this can result in an increase in the model accuracy as weel.  Making predictions<jupyter_code>X[0].numpy()
class_names[model.predict(X[:1]).argmax()]
history.history<jupyter_output><empty_output>
StarcoderdataJupyterStructuredCleanDedup