push main.ipynb utils.py and model.py
Browse files- main.ipynb +0 -0
- models.py +40 -0
- utils.py +109 -0
main.ipynb
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
models.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from tensorflow.keras.models import Sequential
|
| 2 |
+
import tensorflow.keras.layers as tfl
|
| 3 |
+
|
| 4 |
+
def cat_dog_model(image_size, image_channel):
|
| 5 |
+
model = Sequential([
|
| 6 |
+
# Block 1
|
| 7 |
+
tfl.Conv2D(32, (3, 3), activation='relu', input_shape=(image_size, image_size, image_channel)),
|
| 8 |
+
tfl.BatchNormalization(),
|
| 9 |
+
tfl.MaxPooling2D(pool_size=(2, 2)),
|
| 10 |
+
tfl.Dropout(0.2),
|
| 11 |
+
|
| 12 |
+
# Block 2
|
| 13 |
+
tfl.Conv2D(64, (3, 3), activation='relu'),
|
| 14 |
+
tfl.BatchNormalization(),
|
| 15 |
+
tfl.MaxPooling2D(pool_size=(2, 2)),
|
| 16 |
+
tfl.Dropout(0.2),
|
| 17 |
+
|
| 18 |
+
# Block 3
|
| 19 |
+
tfl.Conv2D(128, (3, 3), activation='relu'),
|
| 20 |
+
tfl.BatchNormalization(),
|
| 21 |
+
tfl.MaxPooling2D(pool_size=(2, 2)),
|
| 22 |
+
tfl.Dropout(0.2),
|
| 23 |
+
|
| 24 |
+
# Block 4
|
| 25 |
+
tfl.Conv2D(256, (3, 3), activation='relu'),
|
| 26 |
+
tfl.BatchNormalization(),
|
| 27 |
+
tfl.MaxPooling2D(pool_size=(2, 2)),
|
| 28 |
+
tfl.Dropout(0.2),
|
| 29 |
+
|
| 30 |
+
# Fully Connected Layers
|
| 31 |
+
tfl.Flatten(),
|
| 32 |
+
tfl.Dense(512, activation='relu'),
|
| 33 |
+
tfl.BatchNormalization(),
|
| 34 |
+
tfl.Dropout(0.2),
|
| 35 |
+
|
| 36 |
+
# Output Layer (Softmax for multi-class classification)
|
| 37 |
+
tfl.Dense(1, activation='sigmoid')
|
| 38 |
+
])
|
| 39 |
+
|
| 40 |
+
return model
|
utils.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from PIL import Image
|
| 2 |
+
import matplotlib.pyplot as plt
|
| 3 |
+
import seaborn as sns
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import numpy as np
|
| 6 |
+
|
| 7 |
+
# for image processing
|
| 8 |
+
from tensorflow.keras.preprocessing.image import load_img, img_to_array
|
| 9 |
+
from sklearn.metrics import confusion_matrix
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def validate_image(file_path):
|
| 13 |
+
"""Validate image integrity
|
| 14 |
+
Some images are corrupted and cannot be opened by PIL
|
| 15 |
+
Args:
|
| 16 |
+
file_path (str): Image file path
|
| 17 |
+
Returns:
|
| 18 |
+
bool: True if image is valid, False otherwise"""
|
| 19 |
+
|
| 20 |
+
try:
|
| 21 |
+
with Image.open(file_path) as img:
|
| 22 |
+
# Verify image integrity
|
| 23 |
+
img.verify()
|
| 24 |
+
return True
|
| 25 |
+
except Exception as e:
|
| 26 |
+
print(f"Corrupted image: {file_path} - Error: {e}")
|
| 27 |
+
return False
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def visualize_image(train_path, class_name="cat"):
|
| 31 |
+
"""Display image
|
| 32 |
+
Args:
|
| 33 |
+
file_path (str): Image file path
|
| 34 |
+
class_name (str): Image class name
|
| 35 |
+
Returns:
|
| 36 |
+
10 images of the specified class"""
|
| 37 |
+
|
| 38 |
+
plt.figure(figsize=(20,20))
|
| 39 |
+
plt.subplots_adjust(hspace=0.4)
|
| 40 |
+
|
| 41 |
+
for i in range(10):
|
| 42 |
+
plt.subplot(1,10,i+1)
|
| 43 |
+
filename = train_path +'\\'+ f'{class_name}.' + str(i) + '.jpg'
|
| 44 |
+
image = Image.open(filename)
|
| 45 |
+
plt.imshow(image)
|
| 46 |
+
plt.title(f'{class_name}',fontsize=12)
|
| 47 |
+
plt.axis('off')
|
| 48 |
+
|
| 49 |
+
plt.show()
|
| 50 |
+
|
| 51 |
+
def visulaize_ouput(history):
|
| 52 |
+
"""Visualize model training output
|
| 53 |
+
Args:
|
| 54 |
+
history (tensorflow.python.keras.callbacks.History): Model training history
|
| 55 |
+
Returns:
|
| 56 |
+
plot of Loss and Accuracy"""
|
| 57 |
+
|
| 58 |
+
result_df = pd.DataFrame(history.history)
|
| 59 |
+
|
| 60 |
+
plt.figure(figsize=(18,5),dpi=200)
|
| 61 |
+
sns.set_style('darkgrid')
|
| 62 |
+
|
| 63 |
+
plt.subplot(121)
|
| 64 |
+
plt.title('Cross Entropy Loss',fontsize=15)
|
| 65 |
+
plt.xlabel('Epochs',fontsize=12)
|
| 66 |
+
plt.ylabel('Loss',fontsize=12)
|
| 67 |
+
plt.plot(result_df['loss'])
|
| 68 |
+
plt.plot(result_df['val_loss'])
|
| 69 |
+
|
| 70 |
+
plt.subplot(122)
|
| 71 |
+
plt.title('Classification Accuracy',fontsize=15)
|
| 72 |
+
plt.xlabel('Epochs',fontsize=12)
|
| 73 |
+
plt.ylabel('Accuracy',fontsize=12)
|
| 74 |
+
plt.plot(result_df['accuracy'])
|
| 75 |
+
plt.plot(result_df['val_accuracy'])
|
| 76 |
+
|
| 77 |
+
plt.show()
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def predictor(model, image_path, classes, img_size=(128, 128)):
|
| 81 |
+
"""Predict image class
|
| 82 |
+
Args:
|
| 83 |
+
model (tensorflow.python.keras.engine.sequential.Sequential): Model
|
| 84 |
+
image_path (str): Image file path
|
| 85 |
+
classes (list): List of class names
|
| 86 |
+
img_size (tuple): Image size
|
| 87 |
+
Returns:
|
| 88 |
+
Image class prediction with plots"""
|
| 89 |
+
|
| 90 |
+
img = load_img(image_path, target_size=img_size)
|
| 91 |
+
img_array = img_to_array(img) / 255.0
|
| 92 |
+
img_array = np.expand_dims(img_array, axis=0)
|
| 93 |
+
|
| 94 |
+
predictions = model.predict(img_array)
|
| 95 |
+
predicted_class = np.argmax(predictions, axis=1)[0]
|
| 96 |
+
print(predictions)
|
| 97 |
+
print(predicted_class)
|
| 98 |
+
confidence = predictions[0][predicted_class]
|
| 99 |
+
print(confidence)
|
| 100 |
+
if confidence > 0.5:
|
| 101 |
+
predicted_class = 1
|
| 102 |
+
else:
|
| 103 |
+
predicted_class = 0
|
| 104 |
+
|
| 105 |
+
plt.imshow(img)
|
| 106 |
+
plt.axis('off')
|
| 107 |
+
plt.title(f"Prediction: {classes[predicted_class]}")
|
| 108 |
+
plt.show()
|
| 109 |
+
|