I am trying transfer learning via tensorflow.keras but someting is not working out. The training is showing a nice curves (Training Loss and Validation loss nicely droping ,validation_accuracy increases to 90%). So far all good. My issue is that testing a single image results in a totally different class being selected. What am I doing wrong? My guess it is in the preprocessing of the single image. But perhaps that is a wrong assumption, and is my trained VGG16 totally bad...
Thanks Michiel. Code below
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.layers import Dense, Conv2D, MaxPool2D , Flatten
from tensorflow.keras.applications.vgg16 import preprocess_input
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.models import Model
from tensorflow.keras import optimizers
tsdata = ImageDataGenerator(preprocessing_function=preprocess_input)
testdata = tsdata.flow_from_directory(directory=test_dir, target_size=(224,224),batch_size=64,shuffle=True)
trdata = ImageDataGenerator(horizontal_flip=True,vertical_flip=True,zoom_range=0.2,rotation_range=30,preprocessing_function=preprocess_input)
traindata = trdata.flow_from_directory(directory=train_dir,target_size=(224,224),batch_size=64,shuffle=True)
from tensorflow.keras.applications.vgg16 import VGG16
vggmodel = VGG16(weights='imagenet', include_top=True)
for layers in (vggmodel.layers)[:19]:
print(layers)
layers.trainable = False
Dropout=0.2
X= vggmodel.layers[-2].output
predictions = Dense(102, activation="softmax")(X)
model_final = Model(vggmodel.input, predictions)
model_final.compile(loss = "categorical_crossentropy", optimizer = optimizers.SGD(learning_rate=0.001, momentum=0.9), metrics=["accuracy"])
checkpoint = ModelCheckpoint(vgg16_1.h5", monitor='val_accuracy', verbose=1, save_best_only=True,save_weights_only=False, mode='auto', save_freq="epoch")
early = EarlyStopping(monitor='val_accuracy', min_delta=0, patience=40, verbose=1, mode='auto')
history=model_final.fit(traindata, steps_per_epoch= 2, epochs= 100, validation_data= testdata, validation_steps=1, callbacks=[checkpoint,early])
model_final.save("vgg16_1.h5")
import matplotlib.pyplot as plt
plt.plot(history.history["accuracy"])
plt.plot(history.history['val_accuracy'])
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title("model accuracy")
plt.ylabel("Accuracy")
plt.xlabel("Epoch")
plt.legend(["Accuracy","Validation Accuracy","loss","Validation Loss"])
plt.show()
image_path= path_to_image\image_06734.jpg"
image = tf.keras.preprocessing.image.load_img(image_path,target_size=(224,224))
input_arr = tf.keras.preprocessing.image.img_to_array(image)
input_arr = np.array([input_arr]) # Convert single image to a batch.
predictions = model_reload.predict(input_arr)
print(predictions)
print(np.argmax((predictions), axis=1))
'''