| from PIL import Image
|
| import matplotlib.pyplot as plt
|
| import seaborn as sns
|
| import pandas as pd
|
| import numpy as np
|
|
|
|
|
| from tensorflow.keras.preprocessing.image import load_img, img_to_array
|
| from sklearn.metrics import confusion_matrix
|
|
|
|
|
| def validate_image(file_path):
|
| """Validate image integrity
|
| Some images are corrupted and cannot be opened by PIL
|
| Args:
|
| file_path (str): Image file path
|
| Returns:
|
| bool: True if image is valid, False otherwise"""
|
|
|
| try:
|
| with Image.open(file_path) as img:
|
|
|
| img.verify()
|
| return True
|
| except Exception as e:
|
| print(f"Corrupted image: {file_path} - Error: {e}")
|
| return False
|
|
|
|
|
| def visualize_image(train_path, class_name="cat"):
|
| """Display image
|
| Args:
|
| file_path (str): Image file path
|
| class_name (str): Image class name
|
| Returns:
|
| 10 images of the specified class"""
|
|
|
| plt.figure(figsize=(20,20))
|
| plt.subplots_adjust(hspace=0.4)
|
|
|
| for i in range(10):
|
| plt.subplot(1,10,i+1)
|
| filename = train_path +'\\'+ f'{class_name}.' + str(i) + '.jpg'
|
| image = Image.open(filename)
|
| plt.imshow(image)
|
| plt.title(f'{class_name}',fontsize=12)
|
| plt.axis('off')
|
|
|
| plt.show()
|
|
|
| def visulaize_ouput(history):
|
| """Visualize model training output
|
| Args:
|
| history (tensorflow.python.keras.callbacks.History): Model training history
|
| Returns:
|
| plot of Loss and Accuracy"""
|
|
|
| result_df = pd.DataFrame(history.history)
|
|
|
| plt.figure(figsize=(18,5),dpi=200)
|
| sns.set_style('darkgrid')
|
|
|
| plt.subplot(121)
|
| plt.title('Cross Entropy Loss',fontsize=15)
|
| plt.xlabel('Epochs',fontsize=12)
|
| plt.ylabel('Loss',fontsize=12)
|
| plt.plot(result_df['loss'])
|
| plt.plot(result_df['val_loss'])
|
|
|
| plt.subplot(122)
|
| plt.title('Classification Accuracy',fontsize=15)
|
| plt.xlabel('Epochs',fontsize=12)
|
| plt.ylabel('Accuracy',fontsize=12)
|
| plt.plot(result_df['accuracy'])
|
| plt.plot(result_df['val_accuracy'])
|
|
|
| plt.show()
|
|
|
|
|
| def predictor(model, image_path, classes, img_size=(128, 128)):
|
| """Predict image class
|
| Args:
|
| model (tensorflow.python.keras.engine.sequential.Sequential): Model
|
| image_path (str): Image file path
|
| classes (list): List of class names
|
| img_size (tuple): Image size
|
| Returns:
|
| Image class prediction with plots"""
|
|
|
| img = load_img(image_path, target_size=img_size)
|
| img_array = img_to_array(img) / 255.0
|
| img_array = np.expand_dims(img_array, axis=0)
|
|
|
| predictions = model.predict(img_array)
|
| predicted_class = np.argmax(predictions, axis=1)[0]
|
| print(predictions)
|
| print(predicted_class)
|
| confidence = predictions[0][predicted_class]
|
| print(confidence)
|
| if confidence > 0.5:
|
| predicted_class = 1
|
| else:
|
| predicted_class = 0
|
|
|
| plt.imshow(img)
|
| plt.axis('off')
|
| plt.title(f"Prediction: {classes[predicted_class]}")
|
| plt.show()
|
|
|
|
|