#!/usr/bin/env python # coding: utf-8 # In[1]: #export import tensorflow as tf from tensorflow import keras from tensorflow.keras.models import Sequential from tensorflow.keras.optimizers import Adam, Adamax from tensorflow.keras.metrics import categorical_crossentropy from tensorflow.keras.preprocessing.image import ImageDataGenerator from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Activation, Dropout, BatchNormalization from tensorflow.keras import regularizers from keras.callbacks import EarlyStopping, LearningRateScheduler import numpy as np from tensorflow.keras.preprocessing import image from tensorflow.keras.applications.efficientnet import preprocess_input # In[2]: # Create Model Structure class_labels = ['Angry', 'Other', 'Sad', 'Happy'] img_size = (224, 224) channels = 3 img_shape = (img_size[0], img_size[1], channels) class_count = len(class_labels) # to define number of classes in dense layer # create pre-trained model (you can built on pretrained model such as : efficientnet, VGG , Resnet ) # we will use efficientnetb3 from EfficientNet family. base_model = tf.keras.applications.efficientnet.EfficientNetB5(include_top= False, weights= "imagenet", input_shape= img_shape, pooling= 'max') base_model.trainable = False model = Sequential([ base_model, BatchNormalization(axis= -1, momentum= 0.99, epsilon= 0.001), Dense(256, activation='relu'), Dense(128, kernel_regularizer= regularizers.l2(l= 0.016), activity_regularizer= regularizers.l1(0.006), bias_regularizer= regularizers.l1(0.006), activation= 'relu'), Dropout(rate= 0.45, seed= 123), Dense(class_count, activation= 'softmax') ]) model.trainable = False # model.compile(Adamax(learning_rate= 0.001), loss= 'categorical_crossentropy', metrics= ['accuracy']) model.summary() # In[6]: from tensorflow.keras.preprocessing import image from tensorflow.keras.applications.efficientnet import preprocess_input import matplotlib.pyplot as plt class_labels = ['Angry', 'Other', 'Sad', 'Happy'] def predict_and_display(image_path, model): img = image.load_img(image_path, target_size=(224, 224)) img_array = image.img_to_array(img) img_array = np.expand_dims(img_array, axis=0) img_array = preprocess_input(img_array) prediction = model.predict(img_array) predicted_class_index = np.argmax(prediction) # class_indices = train_gen.class_indices # class_labels = list(class_indices.keys()) predicted_class_label = class_labels[predicted_class_index] plt.imshow(img) plt.axis('off') if predicted_class_label == 'Other': plt.title(f"The pet is normal") else: plt.title(f"The Pet is {predicted_class_label}") plt.show() model.load_weights('my_model_weights.h5') # Replace 'path_to_test_image' with the path to the image you want to test image_path_to_test = 'pets-facial-expression-dataset/Angry/02.jpg' predict_and_display(image_path_to_test, model) # In[11]: image_path_to_test = 'IMG_0243.jpg' predict_and_display(image_path_to_test, model) # In[ ]: