Spaces:
Runtime error
Runtime error
appy.py
Browse files
app.py
CHANGED
|
@@ -1,243 +1,325 @@
|
|
| 1 |
-
import
|
| 2 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
from tensorflow.keras.models import Model
|
| 4 |
from tensorflow.keras.initializers import GlorotUniform
|
| 5 |
from tensorflow.keras.preprocessing.image import ImageDataGenerator
|
| 6 |
from tensorflow.keras.optimizers import Adam
|
| 7 |
-
from tensorflow.keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, EarlyStopping
|
| 8 |
import os
|
| 9 |
from google.colab import drive
|
| 10 |
|
| 11 |
# Mount Google Drive
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
batch_size = 32
|
| 22 |
-
epochs =
|
| 23 |
-
num_classes = 2
|
| 24 |
|
| 25 |
-
# Data augmentation
|
| 26 |
train_datagen = ImageDataGenerator(
|
| 27 |
-
rescale=1./255,
|
| 28 |
-
rotation_range=
|
| 29 |
-
width_shift_range=0.
|
| 30 |
-
height_shift_range=0.
|
| 31 |
-
shear_range=0.
|
| 32 |
-
zoom_range=0.
|
| 33 |
horizontal_flip=True,
|
| 34 |
-
vertical_flip=True, # Added if orientation doesn't matter
|
| 35 |
fill_mode='nearest'
|
| 36 |
)
|
| 37 |
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
train_generator = train_datagen.flow_from_directory(
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
)
|
| 51 |
-
|
| 52 |
-
validation_generator = val_datagen.flow_from_directory(
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
|
| 61 |
-
test_generator = test_datagen.flow_from_directory(
|
| 62 |
-
test_dir,
|
| 63 |
-
target_size=(img_height, img_width),
|
| 64 |
-
batch_size=batch_size,
|
| 65 |
-
class_mode='categorical',
|
| 66 |
-
shuffle=False,
|
| 67 |
-
seed=42
|
| 68 |
-
)
|
| 69 |
|
| 70 |
-
# ======================
|
| 71 |
-
# ResNet-50 Architecture
|
| 72 |
-
# ======================
|
| 73 |
|
| 74 |
def identity_block(X, f, filters, stage, block):
|
| 75 |
"""
|
| 76 |
-
|
| 77 |
Arguments:
|
| 78 |
-
X -- input tensor
|
| 79 |
-
f --
|
| 80 |
-
filters -- list of
|
| 81 |
-
stage --
|
| 82 |
-
block --
|
|
|
|
|
|
|
| 83 |
"""
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
|
|
|
|
|
|
|
|
|
|
| 88 |
X_shortcut = X
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
X =
|
| 92 |
-
name=conv_name_base+'2a', kernel_initializer=GlorotUniform(seed=0))(X)
|
| 93 |
-
X = BatchNormalization(axis=3, name=bn_name_base+'2a')(X)
|
| 94 |
X = Activation('relu')(X)
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
X =
|
| 98 |
-
name=conv_name_base+'2b', kernel_initializer=GlorotUniform(seed=0))(X)
|
| 99 |
-
X = BatchNormalization(axis=3, name=bn_name_base+'2b')(X)
|
| 100 |
X = Activation('relu')(X)
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
X =
|
| 104 |
-
|
| 105 |
-
X =
|
| 106 |
-
|
| 107 |
-
# Add shortcut and activate
|
| 108 |
-
X = Add()([X, X_shortcut])
|
| 109 |
X = Activation('relu')(X)
|
| 110 |
-
|
| 111 |
return X
|
| 112 |
|
|
|
|
|
|
|
| 113 |
def convolutional_block(X, f, filters, stage, block, s=2):
|
| 114 |
"""
|
| 115 |
-
|
| 116 |
Arguments:
|
| 117 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
"""
|
| 119 |
-
|
| 120 |
-
|
|
|
|
|
|
|
| 121 |
F1, F2, F3 = filters
|
| 122 |
-
|
| 123 |
X_shortcut = X
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
X =
|
| 127 |
-
name=conv_name_base+'2a', kernel_initializer=GlorotUniform(seed=0))(X)
|
| 128 |
-
X = BatchNormalization(axis=3, name=bn_name_base+'2a')(X)
|
| 129 |
X = Activation('relu')(X)
|
| 130 |
-
|
| 131 |
-
X = Conv2D(F2, (f, f), strides=(1,1), padding='same',
|
| 132 |
-
|
| 133 |
-
X = BatchNormalization(axis=3, name=bn_name_base+'2b')(X)
|
| 134 |
X = Activation('relu')(X)
|
| 135 |
-
|
| 136 |
-
X = Conv2D(F3, (1, 1), strides=(1,1), padding='valid',
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
name=conv_name_base+'1', kernel_initializer=GlorotUniform(seed=0))(X_shortcut)
|
| 143 |
-
X_shortcut = BatchNormalization(axis=3, name=bn_name_base+'1')(X_shortcut)
|
| 144 |
-
|
| 145 |
-
# Add and activate
|
| 146 |
X = Add()([X, X_shortcut])
|
| 147 |
X = Activation('relu')(X)
|
| 148 |
-
|
| 149 |
return X
|
| 150 |
|
| 151 |
-
def ResNet50(input_shape=(224, 224, 3), classes=2):
|
| 152 |
-
"""True ResNet-50 implementation"""
|
| 153 |
-
X_input = Input(input_shape)
|
| 154 |
|
| 155 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 156 |
X = ZeroPadding2D((3, 3))(X_input)
|
|
|
|
| 157 |
X = Conv2D(64, (7, 7), strides=(2, 2), name='conv1', kernel_initializer=GlorotUniform(seed=0))(X)
|
| 158 |
X = BatchNormalization(axis=3, name='bn_conv1')(X)
|
| 159 |
X = Activation('relu')(X)
|
| 160 |
X = MaxPooling2D((3, 3), strides=(2, 2))(X)
|
| 161 |
-
|
| 162 |
-
# Stage 2 (3 blocks)
|
| 163 |
X = convolutional_block(X, f=3, filters=[64, 64, 256], stage=2, block='a', s=1)
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
# Stage 3 (4 blocks)
|
| 168 |
X = convolutional_block(X, f=3, filters=[128, 128, 512], stage=3, block='a', s=2)
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
# Stage 4 (6 blocks)
|
| 174 |
X = convolutional_block(X, f=3, filters=[256, 256, 1024], stage=4, block='a', s=2)
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
X = identity_block(X, 3, [256, 256, 1024], stage=4, block='e')
|
| 179 |
-
X = identity_block(X, 3, [256, 256, 1024], stage=4, block='f')
|
| 180 |
-
|
| 181 |
-
# Stage 5 (3 blocks)
|
| 182 |
X = convolutional_block(X, f=3, filters=[512, 512, 2048], stage=5, block='a', s=2)
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
X = Flatten()(X)
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
|
|
|
| 192 |
return model
|
| 193 |
|
| 194 |
-
# ==============
|
| 195 |
-
# Model Training
|
| 196 |
-
# ==============
|
| 197 |
|
| 198 |
-
# Build model
|
| 199 |
-
model = ResNet50(input_shape=(img_height, img_width, 3), classes=num_classes)
|
| 200 |
-
model.summary()
|
| 201 |
|
| 202 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
| 203 |
optimizer = Adam(learning_rate=0.001)
|
| 204 |
model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])
|
| 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 |
-
train_generator,
|
| 232 |
-
steps_per_epoch=train_generator.samples // batch_size,
|
| 233 |
-
epochs=epochs,
|
| 234 |
-
validation_data=validation_generator,
|
| 235 |
-
validation_steps=validation_generator.samples // batch_size,
|
| 236 |
-
callbacks=callbacks,
|
| 237 |
verbose=1
|
| 238 |
)
|
| 239 |
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import subprocess
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
def install_tensorflow():
|
| 5 |
+
"""
|
| 6 |
+
Installs TensorFlow using pip. Handles potential errors during the installation.
|
| 7 |
+
"""
|
| 8 |
+
try:
|
| 9 |
+
print("Installing TensorFlow...")
|
| 10 |
+
# Use subprocess.run for more robust command execution
|
| 11 |
+
result = subprocess.run(
|
| 12 |
+
[sys.executable, "-m", "pip", "install", "tensorflow"], # Install tensorflow
|
| 13 |
+
check=True, # Raise an exception if the command fails
|
| 14 |
+
stdout=subprocess.PIPE, # Capture standard output
|
| 15 |
+
stderr=subprocess.PIPE, # Capture standard error
|
| 16 |
+
text=True, # Return output as text
|
| 17 |
+
)
|
| 18 |
+
print("TensorFlow installed successfully.")
|
| 19 |
+
print(result.stdout) # Print the output of the installation command
|
| 20 |
+
|
| 21 |
+
except subprocess.CalledProcessError as e:
|
| 22 |
+
print(f"Error installing TensorFlow: {e}")
|
| 23 |
+
print(f"Error output (stderr):\n{e.stderr}") # Print the error output
|
| 24 |
+
print("Please check your pip installation and internet connection.")
|
| 25 |
+
print("You may need to install TensorFlow manually. Instructions can be found at:")
|
| 26 |
+
print("https://www.tensorflow.org/install")
|
| 27 |
+
sys.exit(1) # Exit the program
|
| 28 |
+
|
| 29 |
+
except Exception as ex:
|
| 30 |
+
print(f"An unexpected error occurred during TensorFlow installation: {ex}")
|
| 31 |
+
sys.exit(1)
|
| 32 |
+
|
| 33 |
+
def check_tensorflow_installation():
|
| 34 |
+
"""
|
| 35 |
+
Checks if TensorFlow is installed and can be imported.
|
| 36 |
+
If not installed, it calls the installation function.
|
| 37 |
+
"""
|
| 38 |
+
try:
|
| 39 |
+
import tensorflow as tf
|
| 40 |
+
print(f"TensorFlow version: {tf.__version__}")
|
| 41 |
+
print("TensorFlow is installed and ready to use.")
|
| 42 |
+
return True # Returns True if tensorflow is installed
|
| 43 |
+
except ImportError:
|
| 44 |
+
print("TensorFlow is not installed.")
|
| 45 |
+
install_tensorflow()
|
| 46 |
+
return False # Returns False if tensorflow is not installed
|
| 47 |
+
|
| 48 |
+
# Check and install TensorFlow if necessary
|
| 49 |
+
if not check_tensorflow_installation():
|
| 50 |
+
check_tensorflow_installation() # Call again, in case the first call installed it.
|
| 51 |
+
|
| 52 |
+
import tensorflow as tf # Import after installation is complete
|
| 53 |
+
|
| 54 |
+
from tensorflow.keras.layers import Input, Add, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D, MaxPooling2D, AveragePooling2D, Dropout
|
| 55 |
from tensorflow.keras.models import Model
|
| 56 |
from tensorflow.keras.initializers import GlorotUniform
|
| 57 |
from tensorflow.keras.preprocessing.image import ImageDataGenerator
|
| 58 |
from tensorflow.keras.optimizers import Adam
|
| 59 |
+
from tensorflow.keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, EarlyStopping
|
| 60 |
import os
|
| 61 |
from google.colab import drive
|
| 62 |
|
| 63 |
# Mount Google Drive
|
| 64 |
+
try:
|
| 65 |
+
drive.mount("/content/drive", timeout_ms=60000)
|
| 66 |
+
except Exception as e:
|
| 67 |
+
print(f"Error mounting drive: {e}")
|
| 68 |
+
print("Continuing without Google Drive...")
|
| 69 |
+
# If mounting fails, you might want to define your directories locally
|
| 70 |
+
train_dir = 'train' # Or wherever your local training data is
|
| 71 |
+
val_dir = 'val'
|
| 72 |
+
test_dir = 'test'
|
| 73 |
+
else:
|
| 74 |
+
# Define your data directories
|
| 75 |
+
train_dir = "/content/drive/MyDrive/Periodontal/train" # Update this
|
| 76 |
+
val_dir = "/content/drive/MyDrive/Periodontal/val" # Update this
|
| 77 |
+
test_dir = "/content/drive/MyDrive/Periodontal/test" # Update this
|
| 78 |
+
|
| 79 |
+
img_height, img_width = 224, 224 # You can adjust this based on your needs
|
| 80 |
batch_size = 32
|
| 81 |
+
epochs = 100
|
| 82 |
+
num_classes = 2 # Update this: Number of classes in your dataset
|
| 83 |
|
| 84 |
+
# Data augmentation (optional but recommended)
|
| 85 |
train_datagen = ImageDataGenerator(
|
| 86 |
+
rescale=1. / 255,
|
| 87 |
+
rotation_range=40,
|
| 88 |
+
width_shift_range=0.2,
|
| 89 |
+
height_shift_range=0.2,
|
| 90 |
+
shear_range=0.2,
|
| 91 |
+
zoom_range=0.2,
|
| 92 |
horizontal_flip=True,
|
|
|
|
| 93 |
fill_mode='nearest'
|
| 94 |
)
|
| 95 |
|
| 96 |
+
val_datagen = ImageDataGenerator(rescale=1. / 255) # Only rescaling for validation/test
|
| 97 |
+
test_datagen = ImageDataGenerator(rescale=1. / 255)
|
| 98 |
+
|
| 99 |
+
# Create data generators
|
| 100 |
+
try:
|
| 101 |
+
train_generator = train_datagen.flow_from_directory(
|
| 102 |
+
train_dir,
|
| 103 |
+
target_size=(img_height, img_width),
|
| 104 |
+
batch_size=batch_size,
|
| 105 |
+
class_mode='categorical',
|
| 106 |
+
shuffle=True,
|
| 107 |
+
seed=42
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
validation_generator = val_datagen.flow_from_directory(
|
| 111 |
+
val_dir,
|
| 112 |
+
target_size=(img_height, img_width),
|
| 113 |
+
batch_size=batch_size,
|
| 114 |
+
class_mode='categorical',
|
| 115 |
+
shuffle=False,
|
| 116 |
+
seed=42
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
test_generator = test_datagen.flow_from_directory(
|
| 120 |
+
test_dir,
|
| 121 |
+
target_size=(img_height, img_width),
|
| 122 |
+
batch_size=batch_size,
|
| 123 |
+
class_mode='categorical',
|
| 124 |
+
shuffle=False,
|
| 125 |
+
seed=42
|
| 126 |
+
)
|
| 127 |
+
except Exception as e:
|
| 128 |
+
print(f"Error creating data generators: {e}")
|
| 129 |
+
print("Please check your directory paths and data.")
|
| 130 |
+
exit()
|
| 131 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
|
|
|
|
|
|
|
|
|
|
| 133 |
|
| 134 |
def identity_block(X, f, filters, stage, block):
|
| 135 |
"""
|
| 136 |
+
Implementation of the identity block as defined in Figure 3 of the paper
|
| 137 |
Arguments:
|
| 138 |
+
X -- input tensor of shape (m, n_H_prev, n_W_prev, n_C_prev)
|
| 139 |
+
f -- integer, specifying the shape of the middle CONV's window for the main path
|
| 140 |
+
filters -- python list of integers, defining the number of filters in the CONV layers of the main path
|
| 141 |
+
stage -- integer, used to name the layers, depending on their position in the network
|
| 142 |
+
block -- string/character, used to name the layers, depending on their position in the network
|
| 143 |
+
Returns:
|
| 144 |
+
X -- output tensor of shape (m, n_H, n_W, n_C)
|
| 145 |
"""
|
| 146 |
+
# defining name basis
|
| 147 |
+
conv_name_base = 'conv' + str(stage) + block + '_branch'
|
| 148 |
+
bn_name_base = 'bn' + str(stage) + block + '_branch'
|
| 149 |
|
| 150 |
+
# Retrieve Filters
|
| 151 |
+
F1, F2, F3 = filters
|
| 152 |
+
# Save the input value. You'll need this later to add back to the main path.
|
| 153 |
X_shortcut = X
|
| 154 |
+
# First component of main path
|
| 155 |
+
X = Conv2D(filters=F1, kernel_size=(1, 1), strides=(1, 1), padding='valid', name=conv_name_base + '2a', kernel_initializer=GlorotUniform(seed=0))(X)
|
| 156 |
+
X = BatchNormalization(axis=3, name=bn_name_base + '2a')(X)
|
|
|
|
|
|
|
| 157 |
X = Activation('relu')(X)
|
| 158 |
+
# Second component of main path
|
| 159 |
+
X = Conv2D(filters=F2, kernel_size=(f, f), strides=(1, 1), padding='same', name=conv_name_base + '2b', kernel_initializer=GlorotUniform(seed=0))(X)
|
| 160 |
+
X = BatchNormalization(axis=3, name=bn_name_base + '2b')(X)
|
|
|
|
|
|
|
| 161 |
X = Activation('relu')(X)
|
| 162 |
+
# Third component of main path
|
| 163 |
+
X = Conv2D(filters=F3, kernel_size=(1, 1), strides=(1, 1), padding='valid', name=conv_name_base + '2c', kernel_initializer=GlorotUniform(seed=0))(X)
|
| 164 |
+
X = BatchNormalization(axis=3, name=bn_name_base + '2c')(X)
|
| 165 |
+
# Final step: Add shortcut value to main path, and pass it through a RELU activation
|
| 166 |
+
X = Add()([X, X_shortcut]) # X_shortcut from the beginning
|
|
|
|
|
|
|
|
|
|
| 167 |
X = Activation('relu')(X)
|
|
|
|
| 168 |
return X
|
| 169 |
|
| 170 |
+
|
| 171 |
+
|
| 172 |
def convolutional_block(X, f, filters, stage, block, s=2):
|
| 173 |
"""
|
| 174 |
+
Implementation of the convolutional block as defined in Figure 4
|
| 175 |
Arguments:
|
| 176 |
+
X -- input tensor of shape (m, n_H_prev, n_W_prev, n_C_prev)
|
| 177 |
+
f -- integer, specifying the shape of the middle CONV's window for the main path
|
| 178 |
+
filters -- python list of integers, defining the number of filters in the CONV layers of the main path
|
| 179 |
+
stage -- integer, used to name the layers, depending on their position in the network
|
| 180 |
+
block -- string/character, used to name the layers, depending on their position in the network
|
| 181 |
+
s -- integer, specifying the stride to be used
|
| 182 |
+
Returns:
|
| 183 |
+
X -- output tensor of shape (m, n_H, n_W, n_C)
|
| 184 |
"""
|
| 185 |
+
# defining name basis
|
| 186 |
+
conv_name_base = 'conv' + str(stage) + block + '_branch'
|
| 187 |
+
bn_name_base = 'bn' + str(stage) + block + '_branch'
|
| 188 |
+
# Retrieve Filters
|
| 189 |
F1, F2, F3 = filters
|
| 190 |
+
# Save the input value
|
| 191 |
X_shortcut = X
|
| 192 |
+
# First component of main path
|
| 193 |
+
X = Conv2D(filters=F1, kernel_size=(1, 1), strides=(s, s), padding='valid', name=conv_name_base + '2a', kernel_initializer=GlorotUniform(seed=0))(X)
|
| 194 |
+
X = BatchNormalization(axis=3, name=bn_name_base + '2a')(X)
|
|
|
|
|
|
|
| 195 |
X = Activation('relu')(X)
|
| 196 |
+
# Second component of main path
|
| 197 |
+
X = Conv2D(filters=F2, kernel_size=(f, f), strides=(1, 1), padding='same', name=conv_name_base + '2b', kernel_initializer=GlorotUniform(seed=0))(X)
|
| 198 |
+
X = BatchNormalization(axis=3, name=bn_name_base + '2b')(X)
|
|
|
|
| 199 |
X = Activation('relu')(X)
|
| 200 |
+
# Third component of main path
|
| 201 |
+
X = Conv2D(filters=F3, kernel_size=(1, 1), strides=(1, 1), padding='valid', name=conv_name_base + '2c', kernel_initializer=GlorotUniform(seed=0))(X)
|
| 202 |
+
X = BatchNormalization(axis=3, name=bn_name_base + '2c')(X)
|
| 203 |
+
##### SHORTCUT PATH ####
|
| 204 |
+
X_shortcut = Conv2D(filters=F3, kernel_size=(1, 1), strides=(s, s), padding='valid', name=conv_name_base + '1', kernel_initializer=GlorotUniform(seed=0))(X_shortcut)
|
| 205 |
+
X_shortcut = BatchNormalization(axis=3, name=bn_name_base + '1')(X_shortcut)
|
| 206 |
+
# Final step: Add shortcut value to main path, and pass it through a RELU activation
|
|
|
|
|
|
|
|
|
|
|
|
|
| 207 |
X = Add()([X, X_shortcut])
|
| 208 |
X = Activation('relu')(X)
|
|
|
|
| 209 |
return X
|
| 210 |
|
|
|
|
|
|
|
|
|
|
| 211 |
|
| 212 |
+
|
| 213 |
+
def ResNetCustom(input_shape=(224, 224, 3), classes=2, num_blocks_per_stage=[2, 2, 2, 2]):
|
| 214 |
+
"""
|
| 215 |
+
Implementation of a custom ResNet architecture. You can specify the number of blocks per stage.
|
| 216 |
+
Arguments:
|
| 217 |
+
input_shape -- shape of the images of the dataset
|
| 218 |
+
classes -- integer, number of classes
|
| 219 |
+
num_blocks_per_stage -- a list indicating the number of identity blocks in each stage after the convolutional block
|
| 220 |
+
Returns:
|
| 221 |
+
model -- a Model() instance in Keras
|
| 222 |
+
"""
|
| 223 |
+
# Define the input as a tensor with shape input_shape
|
| 224 |
+
X_input = Input(input_shape)
|
| 225 |
+
# Zero-Padding
|
| 226 |
X = ZeroPadding2D((3, 3))(X_input)
|
| 227 |
+
# Stage 1
|
| 228 |
X = Conv2D(64, (7, 7), strides=(2, 2), name='conv1', kernel_initializer=GlorotUniform(seed=0))(X)
|
| 229 |
X = BatchNormalization(axis=3, name='bn_conv1')(X)
|
| 230 |
X = Activation('relu')(X)
|
| 231 |
X = MaxPooling2D((3, 3), strides=(2, 2))(X)
|
| 232 |
+
# Stage 2
|
|
|
|
| 233 |
X = convolutional_block(X, f=3, filters=[64, 64, 256], stage=2, block='a', s=1)
|
| 234 |
+
for i in range(num_blocks_per_stage[0]):
|
| 235 |
+
X = identity_block(X, 3, [64, 64, 256], stage=2, block=chr(ord('b') + i)) # b, c, d...
|
| 236 |
+
# Stage 3
|
|
|
|
| 237 |
X = convolutional_block(X, f=3, filters=[128, 128, 512], stage=3, block='a', s=2)
|
| 238 |
+
for i in range(num_blocks_per_stage[1]):
|
| 239 |
+
X = identity_block(X, 3, [128, 128, 512], stage=3, block=chr(ord('b') + i))
|
| 240 |
+
# Stage 4
|
|
|
|
|
|
|
| 241 |
X = convolutional_block(X, f=3, filters=[256, 256, 1024], stage=4, block='a', s=2)
|
| 242 |
+
for i in range(num_blocks_per_stage[2]):
|
| 243 |
+
X = identity_block(X, 3, [256, 256, 1024], stage=4, block=chr(ord('b') + i))
|
| 244 |
+
# Stage 5
|
|
|
|
|
|
|
|
|
|
|
|
|
| 245 |
X = convolutional_block(X, f=3, filters=[512, 512, 2048], stage=5, block='a', s=2)
|
| 246 |
+
for i in range(num_blocks_per_stage[3]):
|
| 247 |
+
X = identity_block(X, 3, [512, 512, 2048], stage=5, block=chr(ord('b') + i))
|
| 248 |
+
# AVGPOOL
|
| 249 |
+
X = AveragePooling2D(pool_size=(2, 2), name='avg_pool')(X)
|
| 250 |
+
# FLATTEN
|
| 251 |
X = Flatten()(X)
|
| 252 |
+
# Fully connected layer
|
| 253 |
+
X = Dense(classes, activation='softmax', name='fc' + str(classes), kernel_initializer=GlorotUniform(seed=0))(X)
|
| 254 |
+
# Create model
|
| 255 |
+
model = Model(inputs=X_input, outputs=X, name='ResNetCustom')
|
| 256 |
return model
|
| 257 |
|
|
|
|
|
|
|
|
|
|
| 258 |
|
|
|
|
|
|
|
|
|
|
| 259 |
|
| 260 |
+
# Build the model
|
| 261 |
+
# You can customize the number of blocks per stage here. For a ResNet-10, use [1,1,1,1]
|
| 262 |
+
model = ResNetCustom(input_shape=(img_height, img_width, 3), classes=num_classes, num_blocks_per_stage=[1, 1, 1, 1]) # Example: [1,1,1,1] for ~10 layers
|
| 263 |
+
|
| 264 |
+
# Compile the model
|
| 265 |
optimizer = Adam(learning_rate=0.001)
|
| 266 |
model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])
|
| 267 |
|
| 268 |
+
# Model summary
|
| 269 |
+
model.summary()
|
| 270 |
+
|
| 271 |
+
# Define callbacks
|
| 272 |
+
checkpoint = ModelCheckpoint(
|
| 273 |
+
filepath='best_resnet_model.keras',
|
| 274 |
+
monitor='val_accuracy',
|
| 275 |
+
verbose=1,
|
| 276 |
+
save_best_only=True,
|
| 277 |
+
mode='max'
|
| 278 |
+
)
|
| 279 |
+
|
| 280 |
+
reduce_lr = ReduceLROnPlateau(
|
| 281 |
+
monitor='val_loss',
|
| 282 |
+
factor=0.2,
|
| 283 |
+
patience=5,
|
| 284 |
+
verbose=1,
|
| 285 |
+
mode='min',
|
| 286 |
+
min_lr=1e-6
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
early_stopping = EarlyStopping(
|
| 290 |
+
monitor='val_loss',
|
| 291 |
+
patience=10,
|
| 292 |
+
restore_best_weights=True,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 293 |
verbose=1
|
| 294 |
)
|
| 295 |
|
| 296 |
+
callbacks = [checkpoint, reduce_lr, early_stopping]
|
| 297 |
+
|
| 298 |
+
# Train the model
|
| 299 |
+
try:
|
| 300 |
+
history = model.fit(
|
| 301 |
+
train_generator,
|
| 302 |
+
steps_per_epoch=train_generator.samples // train_generator.batch_size,
|
| 303 |
+
epochs=epochs,
|
| 304 |
+
validation_data=validation_generator,
|
| 305 |
+
validation_steps=validation_generator.samples // validation_generator.batch_size,
|
| 306 |
+
callbacks=callbacks,
|
| 307 |
+
verbose=1
|
| 308 |
+
)
|
| 309 |
+
print("Training complete!")
|
| 310 |
+
|
| 311 |
+
# Evaluate the model on the test set
|
| 312 |
+
test_loss, test_accuracy = model.evaluate(test_generator, steps=test_generator.samples // test_generator.batch_size, verbose=1)
|
| 313 |
+
print(f"Test Loss: {test_loss:.4f}")
|
| 314 |
+
print(f"Test Accuracy: {test_accuracy:.4f}")
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
except KeyboardInterrupt:
|
| 318 |
+
print("\nTraining interrupted by user (Ctrl+C).")
|
| 319 |
+
print("Saving the model so far...")
|
| 320 |
+
model.save('interrupted_resnet_model.keras') # Save the model
|
| 321 |
+
print("Model saved. You can resume training later by loading this model.")
|
| 322 |
+
except Exception as e:
|
| 323 |
+
print(f"An error occurred during training: {e}")
|
| 324 |
+
print("Please check your data and model configuration.")
|
| 325 |
+
|