Concept
We can reduce overfitting by changing the picture itself - we can blur it, crop the sides, or rotate it. In the end, this will make our model more accurate and flexible, as it can now take blurred, rotated, or cropped pictures and still make accurate predictions
Implementation using Tensorflow
To implement data generation, we will use the ImageDataGenerator from Keras. We will first create a datagenerator object from our ImageDataGenerator, which will include all the augmentations we want to make. Next, we will build our CNN model (the function isn’t shown, but it should be the same as any CNN model function, such as the one in the previous chapter). Finally, we train on our generated images, however, there are a few twists - we need to use fit_generator instead of our regular model.fit function, and inside our fit function, we need to use datagenerator.flow(x_train, y_train) as our data.
import keras from keras.preprocessing.image import ImageDataGenerator #you should already have your x_train, y_train, and possibly x_test and y_test datagenerator = ImageDataGenerator( #list of augmentations ) datagenerator.fit(x_train) #applies generation to x_train #training on our model model = build_model() model.fit_generator(datagenerator.flow(x_train, y_train), validation_data = (x_test, y_test))
You can view the list of augmentations here.
Copyright © 2021 Code 4 Tomorrow. All rights reserved.
The code in this course is licensed under the MIT License.
If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.