newRoop commited on
Commit
eff526b
Β·
verified Β·
1 Parent(s): 78178f3

Delete app.py

Browse files

import subprocess
import sys
import os
import re # Import the regular expression module
import shutil # Import the shutil module

def install_tensorflow():
"""
Installs TensorFlow using pip, targeting the *current* Python environment.
Handles potential errors during the installation. Also checks if the installation was successful.
"""
try:
print("Installing TensorFlow...")
# Use sys.executable to ensure we're using the correct pip for the current Python interpreter
result = subprocess.run(
[sys.executable, "-m", "pip", "install", "tensorflow"],
check=False, # Do NOT use check=True here. We'll handle errors ourselves.
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
)
print("pip install output (stdout):")
print(result.stdout)
print("pip install error output (stderr):")
print(result.stderr)

# Check for successful installation using regex
if re.search(r"Successfully installed tensorflow", result.stdout):
print("TensorFlow installation confirmed.")
return True # Indicate successful installation
else:
print(
"Warning: TensorFlow installation may not have been fully successful. "
"Please check the output above for any errors."
)
return False

except Exception as ex:
print(f"An unexpected error occurred during TensorFlow installation: {ex}")
return False # Indicate installation failure

def check_tensorflow_installation():
"""
Checks if TensorFlow is installed and can be imported.
If not installed, it calls the installation function.
"""
try:
import tensorflow as tf
print(f"TensorFlow version: {tf.__version__}")
print("TensorFlow is installed and ready to use.")
return True
except ImportError:
print("TensorFlow is not installed. Attempting to install...")
if install_tensorflow(): # Call install_tensorflow and check its return value
try:
import tensorflow as tf
print(f"TensorFlow version: {tf.__version__}")
print("TensorFlow is now installed and ready to use.")
return True
except ImportError:
print("TensorFlow installation failed. ImportError after installation.")
return False
else:
print("TensorFlow installation failed.")
return False

if not check_tensorflow_installation():
print("TensorFlow installation failed. Exiting.")
sys.exit(1)

import tensorflow as tf
from tensorflow.keras.layers import Input, Add, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D, MaxPooling2D, AveragePooling2D, Dropout
from tensorflow.keras.models import Model
from tensorflow.keras.initializers import GlorotUniform
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, EarlyStopping
# Check if running in Google Colab
try:
from google.colab import drive
IS_COLAB = True
except ImportError:
IS_COLAB = False
print("Not running in Google Colab. Using local file paths.")

# Mount Google Drive if in Colab
if IS_COLAB:
try:
drive.mount("/content/drive", timeout_ms=60000)
train_dir = "/content/drive/MyDrive/Periodontal_lessDataSet/train"
val_dir = "/content/drive/MyDrive/Periodontal_lessDataSet/val"
test_dir = "/content/drive/MyDrive/Periodontal_lessDataSet/test"
except Exception as e:
print(f"Error mounting drive: {e}")
print("Continuing without Google Drive...")
print("Please ensure your data is in the correct local paths.")
train_dir = "train" # These should be set even if the drive fails.
val_dir = "val"
test_dir = "test"

else:
# **CRITICAL: Explicitly define the paths RELATIVE to where you run the script**
# Get the directory where the script is located.
script_dir = os.path.dirname(os.path.abspath(__file__))

# Construct the full paths. This is the most reliable way to do it.
train_dir = os.path.join(script_dir, "train")
val_dir = os.path.join(script_dir, "val")
test_dir = os.path.join(script_dir, "test")

# ***VERY IMPORTANT DEBUGGING OUTPUT***
print(f"Script directory: {script_dir}")
print(f"Calculated train_dir: {train_dir}")
print(f"Calculated val_dir: {val_dir}")
print(f"Calculated test_dir: {test_dir}")

if not os.path.exists(train_dir):
print(f"Error: Training data directory not found at {train_dir}")
print("Please make sure the path is correct and the directory exists.")
sys.exit(1)
if not os.path.exists(val_dir):
print(f"Error: Validation data directory not found at {val_dir}")
print("Please make sure the path is correct and the directory exists.")
sys.exit(1)
if not os.path.exists(test_dir):
print(f"Error: Test data directory not found at {test_dir}")
print("Please make sure the path is correct and the directory exists.")
sys.exit(1)
print(f"Training data directory: {train_dir}")
print(f"Validation data directory: {val_dir}")
print(f"Test data directory: {test_dir}")

img_height, img_width = 224, 224
batch_size = 32
epochs = 100
num_classes = 2

# Data augmentation (optional but recommended)
train_datagen = ImageDataGenerator(
rescale=1. / 255,
rotation_range=40,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True,
fill_mode='nearest'
)

val_datagen = ImageDataGenerator(rescale=1. / 255)
test_datagen = ImageDataGenerator(rescale=1. / 255)

# Create data generators
try:
train_generator = train_datagen.flow_from_directory(
train_dir,
target_size=(img_height, img_width),
batch_size=batch_size,
class_mode='categorical',
shuffle=True,
seed=42
)

validation_generator = val_datagen.flow_from_directory(
val_dir,
target_size=(img_height, img_width),
batch_size=batch_size,
class_mode='categorical',
shuffle=False,
seed=42
)

test_generator = test_datagen.flow_from_directory(
test_dir,
target_size=(img_height, img_width),
batch_size=batch_size,
class_mode='categorical',
shuffle=False,
seed=42
)
except Exception as e:
print(f"Error creating data generators: {e}")
print("Please check your directory paths and data.")
exit()

def identity_block(X, f, filters, stage, block):
"""
Implementation of the identity block as defined in Figure 3 of the paper
Arguments:
X -- input tensor of shape (m, n_H_prev, n_W_prev, n_C_prev)
f -- integer, specifying the shape of the middle CONV's window for the main path
filters -- python list of integers, defining the number of filters in the CONV layers of the main path
stage -- integer, used to name the layers, depending on their position in the network
block -- string/character, used to name the layers, depending on their position in the network
Returns:
X -- output tensor of shape (m, n_H, n_W, n_C)
"""
# defining name basis
conv_name_base = 'conv' + str(stage) + block + '_branch'
bn_name_base = 'bn' + str(stage) + block + '_branch'

# Retrieve Filters
F1, F2, F3 = filters
# Save the input value. You'll need this later to add back to the main path.
X_shortcut = X
# First component of main path
X = Conv2D(filters=F1, kernel_size=(1, 1), strides=(1, 1), padding='valid', name=conv_name_base + '2a', kernel_initializer=GlorotUniform(seed=0))(X)
X = BatchNormalization(axis=3, name=bn_name_base + '2a')(X)
X = Activation('relu')(X)
# Second component of main path
X = Conv2D(filters=F2, kernel_size=(f, f), strides=(1, 1), padding='same', name=conv_name_base + '2b', kernel_initializer=GlorotUniform(seed=0))(X)
X = BatchNormalization(axis=3, name=bn_name_base + '2b')(X)
X = Activation('relu')(X)
# Third component of main path
X = Conv2D(filters=F3, kernel_size=(1, 1), strides=(1, 1), padding='valid', name=conv_name_base + '2c', kernel_initializer=GlorotUniform(seed=0))(X)
X = BatchNormalization(axis=3, name=bn_name_base + '2c')(X)
# Final step: Add shortcut value to main path, and pass it through a RELU activation
X = Add()([X, X_shortcut]) # X_shortcut from the beginning
X = Activation('relu')(X)
return X

def convolutional_block(X, f, filters, stage, block, s=2):
"""
Implementation of the convolutional block as defined in Figure 4
Arguments:
X -- input tensor of shape (m, n_H_prev, n_W_prev, n_C_prev)
f -- integer, specifying the shape of the middle CONV's window for the main path
filters -- python list of integers, defining the number of filters in the CONV layers of the main path
stage -- integer, used to name the layers, depending on their position in the network
block -- string/character, used to name the layers, depending on their position in the network
s -- integer, specifying the stride to be used
Returns:
X -- output tensor of shape (m, n_H, n_W, n_C)
"""
# defining name basis
conv_name_base = 'conv' + str(stage) + block + '_branch'
bn_name_base = 'bn' + str(stage) + block + '_branch'
# Retrieve Filters
F1, F2, F3 = filters
# Save the input value
X_shortcut = X
# First component of main path
X = Conv2D(filters=F1, kernel_size=(1, 1), strides=(s, s), padding='valid', name=conv_name_base + '2a', kernel_initializer=GlorotUniform(seed=0))(X)
X = BatchNormalization(axis=3, name=bn_name_base + '2a')(X)
X = Activation('relu')(X)
# Second component of main path
X = Conv2D(filters=F2, kernel_size=(f, f), strides=(1, 1), padding='same', name=conv_name_base + '2b', kernel_initializer=GlorotUniform(seed=0))(X)
X = BatchNormalizati

Files changed (1) hide show
  1. app.py +0 -368
app.py DELETED
@@ -1,368 +0,0 @@
1
- import subprocess
2
- import sys
3
- import os
4
- import re # Import the regular expression module
5
- import shutil # Import the shutil module
6
-
7
- def install_tensorflow():
8
- """
9
- Installs TensorFlow using pip, targeting the *current* Python environment.
10
- Handles potential errors during the installation. Also checks if the installation was successful.
11
- """
12
- try:
13
- print("Installing TensorFlow...")
14
- # Use sys.executable to ensure we're using the correct pip for the current Python interpreter
15
- result = subprocess.run(
16
- [sys.executable, "-m", "pip", "install", "tensorflow"],
17
- check=False, # Do NOT use check=True here. We'll handle errors ourselves.
18
- stdout=subprocess.PIPE,
19
- stderr=subprocess.PIPE,
20
- text=True,
21
- )
22
- print("pip install output (stdout):")
23
- print(result.stdout)
24
- print("pip install error output (stderr):")
25
- print(result.stderr)
26
-
27
- # Check for successful installation using regex
28
- if re.search(r"Successfully installed tensorflow", result.stdout):
29
- print("TensorFlow installation confirmed.")
30
- return True # Indicate successful installation
31
- else:
32
- print(
33
- "Warning: TensorFlow installation may not have been fully successful. "
34
- "Please check the output above for any errors."
35
- )
36
- return False
37
-
38
- except Exception as ex:
39
- print(f"An unexpected error occurred during TensorFlow installation: {ex}")
40
- return False # Indicate installation failure
41
-
42
- def check_tensorflow_installation():
43
- """
44
- Checks if TensorFlow is installed and can be imported.
45
- If not installed, it calls the installation function.
46
- """
47
- try:
48
- import tensorflow as tf
49
- print(f"TensorFlow version: {tf.__version__}")
50
- print("TensorFlow is installed and ready to use.")
51
- return True
52
- except ImportError:
53
- print("TensorFlow is not installed. Attempting to install...")
54
- if install_tensorflow(): # Call install_tensorflow and check its return value
55
- try:
56
- import tensorflow as tf
57
- print(f"TensorFlow version: {tf.__version__}")
58
- print("TensorFlow is now installed and ready to use.")
59
- return True
60
- except ImportError:
61
- print("TensorFlow installation failed. ImportError after installation.")
62
- return False
63
- else:
64
- print("TensorFlow installation failed.")
65
- return False
66
-
67
- if not check_tensorflow_installation():
68
- print("TensorFlow installation failed. Exiting.")
69
- sys.exit(1)
70
-
71
- import tensorflow as tf
72
- from tensorflow.keras.layers import Input, Add, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D, MaxPooling2D, AveragePooling2D, Dropout
73
- from tensorflow.keras.models import Model
74
- from tensorflow.keras.initializers import GlorotUniform
75
- from tensorflow.keras.preprocessing.image import ImageDataGenerator
76
- from tensorflow.keras.optimizers import Adam
77
- from tensorflow.keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, EarlyStopping
78
- # Check if running in Google Colab
79
- try:
80
- from google.colab import drive
81
- IS_COLAB = True
82
- except ImportError:
83
- IS_COLAB = False
84
- print("Not running in Google Colab. Using local file paths.")
85
-
86
- # Mount Google Drive if in Colab
87
- if IS_COLAB:
88
- try:
89
- drive.mount("/content/drive", timeout_ms=60000)
90
- train_dir = "/content/drive/MyDrive/Periodontal_lessDataSet/train"
91
- val_dir = "/content/drive/MyDrive/Periodontal_lessDataSet/val"
92
- test_dir = "/content/drive/MyDrive/Periodontal_lessDataSet/test"
93
- except Exception as e:
94
- print(f"Error mounting drive: {e}")
95
- print("Continuing without Google Drive...")
96
- print("Please ensure your data is in the correct local paths.")
97
- train_dir = "train" # These should be set even if the drive fails.
98
- val_dir = "val"
99
- test_dir = "test"
100
-
101
- else:
102
- # **CRITICAL: Explicitly define the paths RELATIVE to where you run the script**
103
- # Get the directory where the script is located.
104
- script_dir = os.path.dirname(os.path.abspath(__file__))
105
-
106
- # Construct the full paths. This is the most reliable way to do it.
107
- train_dir = os.path.join(script_dir, "train")
108
- val_dir = os.path.join(script_dir, "val")
109
- test_dir = os.path.join(script_dir, "test")
110
-
111
- # ***VERY IMPORTANT DEBUGGING OUTPUT***
112
- print(f"Script directory: {script_dir}")
113
- print(f"Calculated train_dir: {train_dir}")
114
- print(f"Calculated val_dir: {val_dir}")
115
- print(f"Calculated test_dir: {test_dir}")
116
-
117
- if not os.path.exists(train_dir):
118
- print(f"Error: Training data directory not found at {train_dir}")
119
- print("Please make sure the path is correct and the directory exists.")
120
- sys.exit(1)
121
- if not os.path.exists(val_dir):
122
- print(f"Error: Validation data directory not found at {val_dir}")
123
- print("Please make sure the path is correct and the directory exists.")
124
- sys.exit(1)
125
- if not os.path.exists(test_dir):
126
- print(f"Error: Test data directory not found at {test_dir}")
127
- print("Please make sure the path is correct and the directory exists.")
128
- sys.exit(1)
129
- print(f"Training data directory: {train_dir}")
130
- print(f"Validation data directory: {val_dir}")
131
- print(f"Test data directory: {test_dir}")
132
-
133
- img_height, img_width = 224, 224
134
- batch_size = 32
135
- epochs = 100
136
- num_classes = 2
137
-
138
- # Data augmentation (optional but recommended)
139
- train_datagen = ImageDataGenerator(
140
- rescale=1. / 255,
141
- rotation_range=40,
142
- width_shift_range=0.2,
143
- height_shift_range=0.2,
144
- shear_range=0.2,
145
- zoom_range=0.2,
146
- horizontal_flip=True,
147
- fill_mode='nearest'
148
- )
149
-
150
- val_datagen = ImageDataGenerator(rescale=1. / 255)
151
- test_datagen = ImageDataGenerator(rescale=1. / 255)
152
-
153
- # Create data generators
154
- try:
155
- train_generator = train_datagen.flow_from_directory(
156
- train_dir,
157
- target_size=(img_height, img_width),
158
- batch_size=batch_size,
159
- class_mode='categorical',
160
- shuffle=True,
161
- seed=42
162
- )
163
-
164
- validation_generator = val_datagen.flow_from_directory(
165
- val_dir,
166
- target_size=(img_height, img_width),
167
- batch_size=batch_size,
168
- class_mode='categorical',
169
- shuffle=False,
170
- seed=42
171
- )
172
-
173
- test_generator = test_datagen.flow_from_directory(
174
- test_dir,
175
- target_size=(img_height, img_width),
176
- batch_size=batch_size,
177
- class_mode='categorical',
178
- shuffle=False,
179
- seed=42
180
- )
181
- except Exception as e:
182
- print(f"Error creating data generators: {e}")
183
- print("Please check your directory paths and data.")
184
- exit()
185
-
186
- def identity_block(X, f, filters, stage, block):
187
- """
188
- Implementation of the identity block as defined in Figure 3 of the paper
189
- Arguments:
190
- X -- input tensor of shape (m, n_H_prev, n_W_prev, n_C_prev)
191
- f -- integer, specifying the shape of the middle CONV's window for the main path
192
- filters -- python list of integers, defining the number of filters in the CONV layers of the main path
193
- stage -- integer, used to name the layers, depending on their position in the network
194
- block -- string/character, used to name the layers, depending on their position in the network
195
- Returns:
196
- X -- output tensor of shape (m, n_H, n_W, n_C)
197
- """
198
- # defining name basis
199
- conv_name_base = 'conv' + str(stage) + block + '_branch'
200
- bn_name_base = 'bn' + str(stage) + block + '_branch'
201
-
202
- # Retrieve Filters
203
- F1, F2, F3 = filters
204
- # Save the input value. You'll need this later to add back to the main path.
205
- X_shortcut = X
206
- # First component of main path
207
- X = Conv2D(filters=F1, kernel_size=(1, 1), strides=(1, 1), padding='valid', name=conv_name_base + '2a', kernel_initializer=GlorotUniform(seed=0))(X)
208
- X = BatchNormalization(axis=3, name=bn_name_base + '2a')(X)
209
- X = Activation('relu')(X)
210
- # Second component of main path
211
- X = Conv2D(filters=F2, kernel_size=(f, f), strides=(1, 1), padding='same', name=conv_name_base + '2b', kernel_initializer=GlorotUniform(seed=0))(X)
212
- X = BatchNormalization(axis=3, name=bn_name_base + '2b')(X)
213
- X = Activation('relu')(X)
214
- # Third component of main path
215
- X = Conv2D(filters=F3, kernel_size=(1, 1), strides=(1, 1), padding='valid', name=conv_name_base + '2c', kernel_initializer=GlorotUniform(seed=0))(X)
216
- X = BatchNormalization(axis=3, name=bn_name_base + '2c')(X)
217
- # Final step: Add shortcut value to main path, and pass it through a RELU activation
218
- X = Add()([X, X_shortcut]) # X_shortcut from the beginning
219
- X = Activation('relu')(X)
220
- return X
221
-
222
- def convolutional_block(X, f, filters, stage, block, s=2):
223
- """
224
- Implementation of the convolutional block as defined in Figure 4
225
- Arguments:
226
- X -- input tensor of shape (m, n_H_prev, n_W_prev, n_C_prev)
227
- f -- integer, specifying the shape of the middle CONV's window for the main path
228
- filters -- python list of integers, defining the number of filters in the CONV layers of the main path
229
- stage -- integer, used to name the layers, depending on their position in the network
230
- block -- string/character, used to name the layers, depending on their position in the network
231
- s -- integer, specifying the stride to be used
232
- Returns:
233
- X -- output tensor of shape (m, n_H, n_W, n_C)
234
- """
235
- # defining name basis
236
- conv_name_base = 'conv' + str(stage) + block + '_branch'
237
- bn_name_base = 'bn' + str(stage) + block + '_branch'
238
- # Retrieve Filters
239
- F1, F2, F3 = filters
240
- # Save the input value
241
- X_shortcut = X
242
- # First component of main path
243
- X = Conv2D(filters=F1, kernel_size=(1, 1), strides=(s, s), padding='valid', name=conv_name_base + '2a', kernel_initializer=GlorotUniform(seed=0))(X)
244
- X = BatchNormalization(axis=3, name=bn_name_base + '2a')(X)
245
- X = Activation('relu')(X)
246
- # Second component of main path
247
- X = Conv2D(filters=F2, kernel_size=(f, f), strides=(1, 1), padding='same', name=conv_name_base + '2b', kernel_initializer=GlorotUniform(seed=0))(X)
248
- X = BatchNormalization(axis=3, name=bn_name_base + '2b')(X)
249
- X = Activation('relu')(X)
250
- # Third component of main path
251
- X = Conv2D(filters=F3, kernel_size=(1, 1), strides=(1, 1), padding='valid', name=conv_name_base + '2c', kernel_initializer=GlorotUniform(seed=0))(X)
252
- X = BatchNormalization(axis=3, name=bn_name_base + '2c')(X)
253
- ##### SHORTCUT PATH ####
254
- 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)
255
- X_shortcut = BatchNormalization(axis=3, name=bn_name_base + '1')(X_shortcut)
256
- # Final step: Add shortcut value to main path, and pass it through a RELU activation
257
- X = Add()([X, X_shortcut])
258
- X = Activation('relu')(X)
259
- return X
260
-
261
- def ResNetCustom(input_shape=(224, 224, 3), classes=2, num_blocks_per_stage=[2, 2, 2, 2]):
262
- """
263
- Implementation of a custom ResNet architecture. You can specify the number of blocks per stage.
264
- Arguments:
265
- input_shape -- shape of the images of the dataset
266
- classes -- integer, number of classes
267
- num_blocks_per_stage -- a list indicating the number of identity blocks in each stage after the convolutional block
268
- Returns:
269
- model -- a Model() instance in Keras
270
- """
271
- # Define the input as a tensor with shape input_shape
272
- X_input = Input(input_shape)
273
- # Zero-Padding
274
- X = ZeroPadding2D((3, 3))(X_input)
275
- # Stage 1
276
- X = Conv2D(64, (7, 7), strides=(2, 2), name='conv1', kernel_initializer=GlorotUniform(seed=0))(X)
277
- X = BatchNormalization(axis=3, name='bn_conv1')(X)
278
- X = Activation('relu')(X)
279
- X = MaxPooling2D((3, 3), strides=(2, 2))(X)
280
- # Stage 2
281
- X = convolutional_block(X, f=3, filters=[64, 64, 256], stage=2, block='a', s=1)
282
- for i in range(num_blocks_per_stage[0]):
283
- X = identity_block(X, 3, [64, 64, 256], stage=2, block=chr(ord('b') + i)) # b, c, d...
284
- # Stage 3
285
- X = convolutional_block(X, f=3, filters=[128, 128, 512], stage=3, block='a', s=2)
286
- for i in range(num_blocks_per_stage[1]):
287
- X = identity_block(X, 3, [128, 128, 512], stage=3, block=chr(ord('b') + i))
288
- # Stage 4
289
- X = convolutional_block(X, f=3, filters=[256, 256, 1024], stage=4, block='a', s=2)
290
- for i in range(num_blocks_per_stage[2]):
291
- X = identity_block(X, 3, [256, 256, 1024], stage=4, block=chr(ord('b') + i))
292
- # Stage 5
293
- X = convolutional_block(X, f=3, filters=[512, 512, 2048], stage=5, block='a', s=2)
294
- for i in range(num_blocks_per_stage[3]):
295
- X = identity_block(X, 3, [512, 512, 2048], stage=5, block=chr(ord('b') + i))
296
- # AVGPOOL
297
- X = AveragePooling2D(pool_size=(2, 2), name='avg_pool')(X)
298
- # FLATTEN
299
- X = Flatten()(X)
300
- # Fully connected layer
301
- X = Dense(classes, activation='softmax', name='fc' + str(classes), kernel_initializer=GlorotUniform(seed=0))(X)
302
- # Create model
303
- model = Model(inputs=X_input, outputs=X, name='ResNetCustom')
304
- return model
305
-
306
- # Build the model
307
- model = ResNetCustom(input_shape=(img_height, img_width, 3), classes=num_classes, num_blocks_per_stage=[1, 1, 1, 1])
308
-
309
- # Compile the model
310
- optimizer = Adam(learning_rate=0.001)
311
- model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])
312
-
313
- # Model summary
314
- model.summary()
315
-
316
- # Define callbacks
317
- checkpoint = ModelCheckpoint(
318
- filepath='best_resnet_model.keras',
319
- monitor='val_accuracy',
320
- verbose=1,
321
- save_best_only=True,
322
- mode='max'
323
- )
324
-
325
- reduce_lr = ReduceLROnPlateau(
326
- monitor='val_loss',
327
- factor=0.2,
328
- patience=5,
329
- verbose=1,
330
- mode='min',
331
- min_lr=1e-6
332
- )
333
-
334
- early_stopping = EarlyStopping(
335
- monitor='val_loss',
336
- patience=10,
337
- restore_best_weights=True,
338
- verbose=1
339
- )
340
-
341
- callbacks = [checkpoint, reduce_lr, early_stopping]
342
-
343
- # Train the model
344
- try:
345
- history = model.fit(
346
- train_generator,
347
- steps_per_epoch=train_generator.samples // train_generator.batch_size,
348
- epochs=epochs,
349
- validation_data=validation_generator,
350
- validation_steps=validation_generator.samples // validation_generator.batch_size,
351
- callbacks=callbacks,
352
- verbose=1
353
- )
354
- print("Training complete!")
355
-
356
- # Evaluate the model on the test set
357
- test_loss, test_accuracy = model.evaluate(test_generator, steps=test_generator.samples // test_generator.batch_size, verbose=1)
358
- print(f"Test Loss: {test_loss:.4f}")
359
- print(f"Test Accuracy: {test_accuracy:.4f}")
360
-
361
- except KeyboardInterrupt:
362
- print("\nTraining interrupted by user (Ctrl+C).")
363
- print("Saving the model so far...")
364
- model.save('interrupted_resnet_model.keras')
365
- print("Model saved. You can resume training later by loading this model.")
366
- except Exception as e:
367
- print(f"An error occurred during training: {e}")
368
- print("Please check your data and model configuration.")