Using transfer learning for binary classification. I train the model using my dataset which has been split into three folders - train, test, val. Each one of these further contains the individual folders for each class.
r = model.fit_generator(
training_set,
validation_data = val_set,
epochs=5,
steps_per_epoch=len(training_set),
validation_steps=len(test_set)
)
After training I get the model saved as an h5 file.
import tensorflow as tf
from keras.models import load_model
model.save('vgg16_new_model.h5')
How do I use this to test the model on the test set?
CodePudding user response:
There is an equivalent to fit_generator
called evaluate_generator
, which you can use when you want to pass a test dataset to your trained model. However, both options are deprecated in the latest Tensorflow
version, so just use model.fit
and model.evaluate
. Here is a simple example:
import tensorflow as tf
flowers = tf.keras.utils.get_file(
'flower_photos',
'https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz',
untar=True)
img_gen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255, rotation_range=20)
model = tf.keras.applications.vgg16.VGG16(include_top=False, input_shape=(256, 256, 3))
x = tf.keras.layers.Flatten()(model.layers[-1].output)
x = tf.keras.layers.Dense(1024, activation='relu')(x)
output = tf.keras.layers.Dense(5)(x)
model = tf.keras.Model(inputs=model.inputs, outputs=output)
model.summary()
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
epochs=1
model.fit(img_gen.flow_from_directory(flowers, batch_size=32, class_mode='sparse'), epochs=epochs)
model.save('vgg16_new_model.h5')
##############################################################
new_model = tf.keras.models.load_model('vgg16_new_model.h5')
results = new_model.evaluate(img_gen.flow_from_directory(flowers, batch_size=32, class_mode='sparse'))
tf.print('Accuracy: ', results[1]*100)
Found 3670 images belonging to 5 classes.
115/115 [==============================] - 73s 629ms/step - loss: 1.6048 - accuracy: 0.2447
Accuracy: 24.468664824962616
Note that I am using the same subset for training and evaluation, but you would pass your test set to model.evaluate
.