CS663 | computer vision
  • outline
  • projects
  • syllabus
  • links

Tensorflow 2+ with Keras Images and CNN

https://www.tensorflow.org/tutorials/images/cnn

#============================================
#STEP 1 Import TEnsroflow and keras
import tensorflow as tf

from tensorflow.keras import datasets, layers, models
import matplotlib.pyplot as plt #============================================ #STEP 2: Load DataSet (here a preset one) (train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()

# Normalize pixel values to be between 0 and 1
train_images, test_images = train_images / 255.0, test_images / 255.0 #plot the first 25 images from the training set and display the class name below each image. # these images are 32x32 rgb images class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer',
               'dog', 'frog', 'horse', 'ship', 'truck']

plt.figure(figsize=(10,10))
for i in range(25):
    plt.subplot(5,5,i+1)
    plt.xticks([])
    plt.yticks([])
    plt.grid(False)
    plt.imshow(train_images[i], cmap=plt.cm.binary)
    # The CIFAR labels happen to be arrays,
    # which is why you need the extra index
    plt.xlabel(class_names[train_labels[i][0]])
plt.show() #============================================================ #STEP 3 - start creating CNN model with setup of convolution layers #Create the CNN model- Conv2D(32 3x3) filters, MaxPooling, Conv2D(64 3x3 filters), MaxPooling, Conv23(64) model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu')) #print a summary of our model model.summary()
#note: CIFAR images are 32x32 pixels and 3 channels -rgb #======================================================= #STEP 4 - complete CNN layers to add fully connected layers leading to final decision layer # note CIFAR has 10 output classes # input to first fully connect layer is the output from
# convolutional base (of shape (3, 3, 64)) # #These are called "Dense Layers" in TensorFLow model.add(layers.Flatten())
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(10, activation='softmax')) #lets look at model architecture now model.summary() #================================================================ #STEP 5- setup optimizer &loss & accuracy AND Train the model model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

history = model.fit(train_images, train_labels, epochs=10,
                    validation_data=(test_images, test_labels))

OUTPUT


Train on 50000 samples, validate on 10000 samples Epo ch 1/10 50000/50000 [==============================] - 11s 222us/sample - loss: 1.5684 - accuracy: 0.4266 - val_loss: 1.2367 - val_accuracy: 0.5543 Epoch 2/10 50000/50000 [==============================] - 7s 130us/sample - loss: 1.1648 - accuracy: 0.5879 - val_loss: 1.1616 - val_accuracy: 0.5853 Epoch 3/10 50000/50000 [==============================] - 6s 130us/sample - loss: 1.0314 - accuracy: 0.6379 - val_loss: 1.0190 - val_accuracy: 0.6374 Epoch 4/10 50000/50000 [==============================] - 6s 129us/sample - loss: 0.9382 - accuracy: 0.6711 - val_loss: 0.9656 - val_accuracy: 0.6617 Epoch 5/10 50000/50000 [==============================] - 6s 129us/sample - loss: 0.8650 - accuracy: 0.6970 - val_loss: 0.9005 - val_accuracy: 0.6870 Epoch 6/10 50000/50000 [==============================] - 6s 129us/sample - loss: 0.8054 - accuracy: 0.7183 - val_loss: 0.9217 - val_accuracy: 0.6748 Epoch 7/10 50000/50000 [==============================] - 7s 131us/sample - loss: 0.7557 - accuracy: 0.7356 - val_loss: 0.9336 - val_accuracy: 0.6858 Epoch 8/10 50000/50000 [==============================] - 7s 132us/sample - loss: 0.7145 - accuracy: 0.7514 - val_loss: 0.9107 - val_accuracy: 0.6906 Epoch 9/10 50000/50000 [==============================] - 7s 134us/sample - loss: 0.6758 - accuracy: 0.7647 - val_loss: 0.8696 - val_accuracy: 0.7077 Epoch 10/10 50000/50000 [==============================] - 6s 130us/sample - loss: 0.6410 - ac curacy: 0.7757 - val_loss: 0.8684 - val_accuracy: 0.7076


#===============================================================
#STEP 6-  plot the accuracy
plt.plot(history.history['accuracy'], label='accuracy')
plt.plot(history.history['val_accuracy'], label = 'val_accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.ylim([0.5, 1])
plt.legend(loc='lower right')

test_loss, test_acc = model.evaluate(test_images,  test_labels, verbose=2) print(test_acc)

 

 

 

cs663:computer vision

  • home
  • outline
  • projects
  • syllabus
  • links