-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodel_microscopic.py
More file actions
252 lines (215 loc) · 8.8 KB
/
model_microscopic.py
File metadata and controls
252 lines (215 loc) · 8.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
import numpy as np
import tensorflow as tf
from tensorflow import keras
from keras import layers, models
from keras.preprocessing.image import ImageDataGenerator
from sklearn.metrics import classification_report, confusion_matrix
import matplotlib.pyplot as plt
import seaborn as sns
import os
# Configuration
IMG_SIZE = 128
BATCH_SIZE = 32
EPOCHS = 15
NUM_CLASSES = 5 # Start with 5 organisms for demo
class MicroscopicOrganismClassifier:
def __init__(self, num_classes=5, img_size=128):
self.num_classes = num_classes
self.img_size = img_size
self.model = self.build_model()
def build_model(self):
"""Build CNN architecture optimized for microscopic images"""
model = models.Sequential([
# First Conv Block
layers.Conv2D(32, (3, 3), activation='relu', padding='same',
input_shape=(self.img_size, self.img_size, 3)),
layers.BatchNormalization(),
layers.Conv2D(32, (3, 3), activation='relu', padding='same'),
layers.MaxPooling2D((2, 2)),
layers.Dropout(0.25),
# Second Conv Block
layers.Conv2D(64, (3, 3), activation='relu', padding='same'),
layers.BatchNormalization(),
layers.Conv2D(64, (3, 3), activation='relu', padding='same'),
layers.MaxPooling2D((2, 2)),
layers.Dropout(0.25),
# Third Conv Block
layers.Conv2D(128, (3, 3), activation='relu', padding='same'),
layers.BatchNormalization(),
layers.Conv2D(128, (3, 3), activation='relu', padding='same'),
layers.MaxPooling2D((2, 2)),
layers.Dropout(0.25),
# Dense Layers
layers.Flatten(),
layers.Dense(256, activation='relu'),
layers.BatchNormalization(),
layers.Dropout(0.5),
layers.Dense(128, activation='relu'),
layers.Dropout(0.3),
layers.Dense(self.num_classes, activation='softmax')
])
model.compile(
optimizer=keras.optimizers.Adam(learning_rate=0.001),
loss='categorical_crossentropy',
metrics=['accuracy', keras.metrics.Precision(), keras.metrics.Recall()]
)
return model
def prepare_data(self, train_dir, val_dir):
"""Prepare data with augmentation"""
train_datagen = ImageDataGenerator(
rescale=1./255,
rotation_range=30,
width_shift_range=0.2,
height_shift_range=0.2,
horizontal_flip=True,
vertical_flip=True,
zoom_range=0.2,
brightness_range=[0.8, 1.2],
fill_mode='nearest'
)
val_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(
train_dir,
target_size=(self.img_size, self.img_size),
batch_size=BATCH_SIZE,
class_mode='categorical'
)
val_generator = val_datagen.flow_from_directory(
val_dir,
target_size=(self.img_size, self.img_size),
batch_size=BATCH_SIZE,
class_mode='categorical'
)
return train_generator, val_generator
def train(self, train_generator, val_generator, epochs=EPOCHS):
"""Train the model with callbacks"""
callbacks = [
keras.callbacks.EarlyStopping(
monitor='val_loss',
patience=5,
restore_best_weights=True
),
keras.callbacks.ReduceLROnPlateau(
monitor='val_loss',
factor=0.5,
patience=3,
min_lr=1e-7
),
keras.callbacks.ModelCheckpoint(
'best_model.h5',
monitor='val_accuracy',
save_best_only=True
)
]
history = self.model.fit(
train_generator,
epochs=epochs,
validation_data=val_generator,
callbacks=callbacks
)
return history
def plot_training_history(self, history):
"""Plot training metrics"""
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
# Accuracy
axes[0, 0].plot(history.history['accuracy'], label='Train')
axes[0, 0].plot(history.history['val_accuracy'], label='Validation')
axes[0, 0].set_title('Model Accuracy')
axes[0, 0].set_xlabel('Epoch')
axes[0, 0].set_ylabel('Accuracy')
axes[0, 0].legend()
axes[0, 0].grid(True)
# Loss
axes[0, 1].plot(history.history['loss'], label='Train')
axes[0, 1].plot(history.history['val_loss'], label='Validation')
axes[0, 1].set_title('Model Loss')
axes[0, 1].set_xlabel('Epoch')
axes[0, 1].set_ylabel('Loss')
axes[0, 1].legend()
axes[0, 1].grid(True)
# Precision
axes[1, 0].plot(history.history['precision'], label='Train')
axes[1, 0].plot(history.history['val_precision'], label='Validation')
axes[1, 0].set_title('Precision')
axes[1, 0].set_xlabel('Epoch')
axes[1, 0].set_ylabel('Precision')
axes[1, 0].legend()
axes[1, 0].grid(True)
# Recall
axes[1, 1].plot(history.history['recall'], label='Train')
axes[1, 1].plot(history.history['val_recall'], label='Validation')
axes[1, 1].set_title('Recall')
axes[1, 1].set_xlabel('Epoch')
axes[1, 1].set_ylabel('Recall')
axes[1, 1].legend()
axes[1, 1].grid(True)
plt.tight_layout()
plt.savefig('training_history.png', dpi=300)
plt.show()
def evaluate_model(self, val_generator, class_names):
"""Evaluate model and generate reports"""
# Predictions
y_pred = self.model.predict(val_generator)
y_pred_classes = np.argmax(y_pred, axis=1)
y_true = val_generator.classes
# Classification Report
print("\n" + "="*60)
print("CLASSIFICATION REPORT")
print("="*60)
print(classification_report(y_true, y_pred_classes, target_names=class_names))
# Confusion Matrix
cm = confusion_matrix(y_true, y_pred_classes)
plt.figure(figsize=(10, 8))
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues',
xticklabels=class_names, yticklabels=class_names)
plt.title('Confusion Matrix', fontsize=16, fontweight='bold')
plt.xlabel('Predicted Label', fontsize=12)
plt.ylabel('True Label', fontsize=12)
plt.tight_layout()
plt.savefig('confusion_matrix.png', dpi=300)
plt.show()
return y_pred, y_pred_classes
def predict_single_image(self, img_path, class_names):
"""Predict single image with visualization"""
img = keras.preprocessing.image.load_img(
img_path, target_size=(self.img_size, self.img_size)
)
img_array = keras.preprocessing.image.img_to_array(img)
img_array = np.expand_dims(img_array, axis=0) / 255.0
predictions = self.model.predict(img_array)[0]
predicted_class = class_names[np.argmax(predictions)]
confidence = np.max(predictions) * 100
# Visualization
fig, axes = plt.subplots(1, 2, figsize=(12, 5))
# Image
axes[0].imshow(img)
axes[0].axis('off')
axes[0].set_title(f'Predicted: {predicted_class}\nConfidence: {confidence:.2f}%',
fontsize=14, fontweight='bold')
# Probability distribution
axes[1].barh(class_names, predictions, color='skyblue')
axes[1].set_xlabel('Probability', fontsize=12)
axes[1].set_title('Prediction Probabilities', fontsize=14, fontweight='bold')
axes[1].set_xlim([0, 1])
plt.tight_layout()
plt.savefig('prediction_result.png', dpi=300)
plt.show()
return predicted_class, confidence, predictions
# Example Usage
if __name__ == "__main__":
# Initialize classifier
classifier = MicroscopicOrganismClassifier(num_classes=5, img_size=128)
print("Model Summary:")
classifier.model.summary()
# Train model (uncomment when data is ready)
# train_gen, val_gen = classifier.prepare_data('data/train', 'data/val')
# history = classifier.train(train_gen, val_gen, epochs=15)
# classifier.plot_training_history(history)
#
# # Evaluate
# class_names = list(train_gen.class_indices.keys())
# classifier.evaluate_model(val_gen, class_names)
#
# # Save model
# classifier.model.save('microscopic_organism_classifier.h5')
# print("\nModel saved successfully!")