How to Project Object Recognition in Photographs

A difficult problem where traditional neural networks fall down is called object recognition. It is where a model is able to identify objects in images. In this lesson you will discover how to develop and evaluate deep learning models for object recognition in Keras. After completing this step-by-step tutorial, you will know:

  • About the CIFAR-10 object recognition dataset and how to load and use it in Keras.
  • How to create a simple Convolutional Neural Network for object recognition.
  • How to lift performance by creating deeper Convolutional Neural Networks

Note: You may want to speed up the computation for this tutorial by using GPU rather than CPU hardware, such as the process described in Chapter 5. This is a suggestion, not a requirement. The tutorial will work just fine on the CPU 

 1.1 Photograph Object Recognition Dataset

 The problem of automatically identifying objects in photographs is difficult because of the near infinite number of permutations of objects,positions,lighting and so on. It's a really hard problem.This is a well studied problem in computer vision and more recently an important demonstration of the capbility of deep learning. A standard computer vision and deep learning dataset for this problem was developed by the Canadian Institute for Advanced Research(CIFAR)

The CIFAR-10 dataset consists of 60,000 photos divided into 10 classes (hence the name CIFAR-10)1. Classes include common objects such as airplanes, automobiles, birds, cats and so on. The dataset is split in a standard way, where 50,000 images are used for training a model and the remaining 10,000 for evaluating its performance. The photos are in color with red, green and blue channels, but are small measuring 32X32 pixel squares.

        State-of-the-art results can be achieved using very large convolutional neural networks. You can learn about state-of-the-art results on CIFAR-10 on Rodrigo Benenson’s webpage2. Model performance is reported in classification accuracy, with very good performance above 90% with human performance on the problem at 94% and state-of-the-art results at 96% at the time of writing.

1.2 Loading The CIFAR-10 Dataset in Keras

 The CIFAR-10 dataset can easily be loaded in Keras. Keras has the facility to automatically download standard datasets like CIFAR-10 and store them in the ~/.keras/datasets directory using the cifar10.load_data() function. This dataset is large at 163 megabytes, so it may take a few minutes to download. Once downloaded, subsequent calls to the function will load the dataset ready for use.

        The dataset is stored as Python pickled training and test sets, ready for use in Keras. Each image is represented as a three dimensional matrix, with dimensions for red, green, blue, width and height. We can plot images directly using the Matplotlib Python plotting library.

# Load  And Plot Sample CIFAR-10 Images

# Plot ad hoc CIFAR-10 instances
from keras.datasets import cifar10
from matplotlib import pyplot
from PIL import Image

# load data
(X_train, y_train),(X_test, y_test) = cifar10.load_data()

# create a grid of 3 x 3 images
for i in range(0, 9):
    pyplot.subplot(330 + 1 + i)
    pyplot.imshow(Image.fromarray(X_train[i]))
# show the plot
pyplot.show()

Running the code create a 3 X 3 plot of photographs. The images have been scaled up from their small 32 X 32 size, but you can clearly see trucks horses and cars. You can also see some distortion in the images that have been forced to the square aspect ratio.

1.3  Simple CNN for CIFAR-10

The CIFAR-10 problem is best solved using a convolutional neural network (CNN). We can quickly start off by importing all of the classes and functions we will need in this example.

# Load Classes and Functions

#Simple CNN model for CIFAR-10
import numpy as np
from keras.datasets import cifar10
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import Flatten
from keras.constraints import maxnorm
from tensorflow.keras.optimizers import SGD
from keras.layers.convolutional import Convolution2D
from keras.layers.convolutional import MaxPooling2D
from keras.utils import np_utils
from keras import backend as K
K.set_image_data_format('channels_first')

As is good practice, we next initialize the random number seed with a constant to ensure the results are reproducible.

# Initialize Random Number Generator

# fix ranodm seed for reproducibility
seed = 7
np.random.seed(seed)

Next we can load the CIFAR-10 dataset.

# Load the CIFAR-10 Dataset
# load data
(X_train, y_train),(X_test,y_test) = cifar10.load_data()

The pixel values are in the range of 0 to 255 for each of the red, green and blue channels. It is good practice to work with normalized data. Because the input values are well understood, we can easily normalize to the range 0 to 1 by dividing each value by the maximum observation which is 255. Note, the data is loaded as integers, so we must cast it to floating point values in order to perform the division.

# Normalize the CIFAR-10 Dataset
# normalize inputs from 0-255 to 0.0 - 1.0
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train = X_train / 255.0
X_test = X_test / 255.0

The output variables are defined as a vector of integers from 0 to 1 for each class. We can use a one hot encoding to transform them into a binary matrix in order to best model the classification problem. We know there are 10 classes for this problem, so we can expect the binary matrix to have a width of 10.

# One hot Encode The Output Variable
# one hot encode outputs
y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)
num_classes = y_test.shape[1]

Let’s start off by defining a simple CNN structure as a baseline and evaluate how well it performs on the problem. We will use a structure with two convolutional layers followed by max pooling and a flattening out of the network to fully connected layers to make predictions. Our baseline network structure can be summarized as follows:

1. Convolutional input layer, 32 feature maps with a size of 3 x 3, a rectifier activation function and a weight constraint of max norm set to 3.

2. Dropout set to 20%.

3. Convolutional layer, 32 feature maps with a size of 3 x 3, a rectifier activation function and a weight constraint of max norm set to 3.

4. Max Pool layer with the size 2 x 2.

5. Flatten layer.

6. Fully connected layer with 512 units and a rectifier activation function

7. Dropout set to 50%.

8. Fully connected output layer with 10 units and a softmax activation function.

A logarithmic loss function is used with the stochastic gradient descent optimization algorithm configured with a large momentum and weight decay, starting with a learning rate of 0.01. A visualization of the network structure is provided below.

 

#Simple CNN model for CIFAR-10
import numpy as np
from keras.datasets import cifar10
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import Flatten
from keras.constraints import maxnorm
from tensorflow.keras.optimizers import SGD
from keras.layers.convolutional import Convolution2D
from keras.layers.convolutional import MaxPooling2D
from keras.utils import np_utils
from keras import backend as K
K.set_image_data_format('channels_first')

# Define and Compile the CNN Model
# Create the model
model = Sequential()
model.add(Convolution2D(32, 3, 3, input_shape=(3, 32, 32), padding='same',activation='relu',kernel_constraint=maxnorm(3)))
model.add(Dropout(0.2))
model.add(Convolution2D(32, 3, 3, activation='relu',padding='same',kernel_constraint=maxnorm(3)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(512, activation='relu',kernel_constraint=maxnorm(3)))
model.add(Dropout(0.5))
model.add(Dense(num_classes,activation='softmax'))
# Compile model
epochs = 25
lrate = 0.01
decay = lrate/epochs
sgd = SGD(lr=lrate, momentum=0.9, decay=decay, nesterov=False)
model.compile(loss='categorical_crossentropy',optimizer=sgd,metrics=['accuracy'])
print(model.summary())

We fit this model with 25 epochs and a batch size of 32. A small number of epochs was chosen to help keep this tutorial moving. Normally the number of epochs would be one or two orders of magnitude larger for this problem. Once the model is fit, we evaluate it on the test dataset and print out the classification accuracy.

# Evaluate the Accuracy of the CNN Model
# Fit the model
model.fit(X_train, y_train,validation_data=(X_test, y_test),epochs=epochs, batch_size=32,verbose=2)

# Final evaluation of the model
scores = model.evaluate(X_test, y_test, verbose=0)
print("Accuracy: %.2f%%" % (scores[1]*100))

The full code listing is provided below for completeness.

#Simple CNN model for CIFAR-10
import numpy as np
from keras.datasets import cifar10
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import Flatten
from keras.constraints import maxnorm
from tensorflow.keras.optimizers import SGD
from keras.layers.convolutional import Convolution2D
from keras.layers.convolutional import MaxPooling2D
from keras.utils import np_utils
from keras import backend as K
K.set_image_data_format('channels_first')

# Initialize Random Number Generator

# fix ranodm seed for reproducibility
seed = 7
np.random.seed(seed)

# Load the CIFAR-10 Dataset
# load data
(X_train, y_train),(X_test,y_test) = cifar10.load_data()


# Normalize the CIFAR-10 Dataset
# normalize inputs from 0-255 to 0.0 - 1.0
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train = X_train / 255.0
X_test = X_test / 255.0


# One hot Encode The Output Variable
# one hot encode outputs
y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)
num_classes = y_test.shape[1]


# Define and Compile the CNN Model
# Create the model
model = Sequential()
model.add(Convolution2D(32, 3, 3, input_shape=(3, 32, 32), padding='same',activation='relu',kernel_constraint=maxnorm(3)))
model.add(Dropout(0.2))
model.add(Convolution2D(32, 3, 3, activation='relu',padding='same',kernel_constraint=maxnorm(3)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(512, activation='relu',kernel_constraint=maxnorm(3)))
model.add(Dropout(0.5))
model.add(Dense(num_classes,activation='softmax'))
# Compile model
epochs = 25
lrate = 0.01
decay = lrate/epochs
sgd = SGD(lr=lrate, momentum=0.9, decay=decay, nesterov=False)
model.compile(loss='categorical_crossentropy',optimizer=sgd,metrics=['accuracy'])
print(model.summary())

# Evaluate the Accuracy of the CNN Model
# Fit the model
model.fit(X_train, y_train,validation_data=(X_test, y_test),epochs=epochs, batch_size=32,verbose=2)

# Final evaluation of the model
scores = model.evaluate(X_test, y_test, verbose=0)
print("Accuracy: %.2f%%" % (scores[1]*100))

1.4 Larger CNN for CIFAR-10

We have seen that a simple CNN performs poorly on this complex problem. In this section we look at scaling up the size and complexity of our model. Let’s design a deep version of the simple CNN above. We can introduce an additional round of convolutions with many more feature maps. We will use the same pattern of Convolutional, Dropout, Convolutional and Max Pooling layers.

        This pattern will be repeated 3 times with 32, 64, and 128 feature maps. The e↵ect will be an increasing number of feature maps with a smaller and smaller size given the max pooling layers. Finally an additional and larger Dense layer will be used at the output end of the network in an attempt to better translate the large number feature maps to class values. We can summarize a new network architecture as follows:

1. Convolutional input layer, 32 feature maps with a size of 3 ⇥ 3 and a rectifier activation function. 2. Dropout layer at 20%. 3. Convolutional layer, 32 feature maps with a size of 3 ⇥ 3 and a rectifier activation function. 4. Max Pool layer with size 2 ⇥ 2. 5. Convolutional layer, 64 feature maps with a size of 3 ⇥ 3 and a rectifier activation function. 6. Dropout layer at 20%. 7. Convolutional layer, 64 feature maps with a size of 3 ⇥ 3 and a rectifier activation function. 8. Max Pool layer with size 2 ⇥ 2. 9. Convolutional layer, 128 feature maps with a size of 3⇥3 and a rectifier activation function. 10. Dropout layer at 20%. 11. Convolutional layer, 128 feature maps with a size of 3⇥3 and a rectifier activation function. 12. Max Pool layer with size 2 ⇥ 2. 13. Flatten layer. 14. Dropout layer at 20%. 15. Fully connected layer with 1,024 units and a rectifier activation function. 16. Dropout layer at 20%. 17. Fully connected layer with 512 units and a rectifier activation function. 18. Dropout layer at 20%. 19. Fully connected output layer with 10 units and a softmax activation function.

This is a larger network and a bit unwieldy to visualize. We can fit and evaluate this model using the same procedure above and the same number of epochs but a larger batch size of 64, found through some minor experimentation.

# Large CNN Model for CIFAR-10 Problem

# Large CNN model for the CIFAR-10 Dataset
import numpy as np
from keras.datasets import cifar10
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import Flatten
from keras.constraints import maxnorm
from tensorflow.keras.optimizers import SGD
from keras.layers.convolutional import Convolution2D
from keras.layers.convolutional import MaxPooling2D
from keras.utils import np_utils
from keras import backend as K
K.set_image_data_format('channels_first')

# fix random seed for reproducibility
seed = 7
np.random.seed(seed)

# load data
(X_train,y_train),(X_test,y_test) = cifar10.load_data()
# normalize inputs from 0-255 to 0.0 - 1.0
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train = X_train / 255.0
X_test = X_test / 255.0

# one hot encode outputs
y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)
num_classes = y_test.shape[1]
# Create the model
model = Sequential()
model.add(Convolution2D(32, 3, 3, input_shape=(3, 32, 32), activation='relu',padding='same'))
model.add(Dropout(0.2))
model.add(Convolution2D(32, 3, 3, activation='relu',padding='same'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Convolution2D(64, 3, 3, input_shape=(3, 32, 32), activation='relu',padding='same'))
model.add(Dropout(0.2))
model.add(Convolution2D(64, 3, 3, input_shape=(3, 32, 32), activation='relu',padding='same'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Convolution2D(128, 3, 3, input_shape=(3, 32, 32), activation='relu',padding='same'))
model.add(Dropout(0.2))
model.add(Convolution2D(128, 3, 3, input_shape=(3, 32, 32), activation='relu',padding='same'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dropout(0.2))
model.add(Convolution2D(1024, 3, 3, activation='relu',kernel_constraint=maxnorm(3)))
model.add(Dropout(0.2))
model.add(Convolution2D(1024, 3, 3, activation='relu',kernel_constraint=maxnorm(3)))
model.add(Dropout(0.2))
model.add(Dense(num_classes,activation='softmax'))

# Compile model
epochs = 25
lrate = 0.01
decay = lrate/epochs
sgd = SGD(lr=lrate, momentum=0.9, decay=decay, nesterov=False)
model.compile(loss='categorical_crossentropy',optimizer=sgd,metrics=['accuracy'])
print(model.summary())



# Fit the model
model.fit(X_train, y_train,validation_data=(X_test, y_test),epochs=epochs, batch_size=64)

# Final evaluation of the model
scores = model.evaluate(X_test, y_test, verbose=0)
print("Accuracy: %.2f%%" % (scores[1]*100))

1.5 Extensions To Improve Model Performance

We have achieved good results on this very difficult problem, but we are still a good way from achieving world class results. Below are some ideas that you can try to extend upon the model and improve model performance.

  • Train for More Epochs. Each model was trained for a very small number of epochs, 25. It is common to train large convolutional neural networks for hundreds or thousands of epochs. I would expect that performance gains can be achieved by significantly raising the number of training epochs.
  • Image Data Augmentation. The objects in the image vary in their position. Another boost in model performance can likely be achieved by using some data augmentation. Methods such as standardization and random shifts and horizontal image flips may be beneficial.
  • Deeper Network Topology. The larger network presented is deep, but larger networks could be designed for the problem. This may involve more feature maps closer to the input and perhaps less aggressive pooling. Additionally, standard convolutional network topologies that have been shown useful may be adopted and evaluated on the problem. What accuracy can you achieve on this problem?

 1.6 Summary

In this lesson you discovered how to create deep learning models in Keras for object recognition in photographs. After working through this tutorial you learned:

  • About the CIFAR-10 dataset and how to load it in Keras and plot ad hoc examples from the dataset.
  • How to train and evaluate a simple Convolutional Neural Network on the problem.
  • How to expand a simple convolutional neural network into a deep convolutional neural network in order to boost performance on the difficult problem.
  • How to use data augmentation to get a further boost on the difficult object recognition problem.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值