File size: 13,281 Bytes
1690c98
 
 
7549e78
 
1690c98
 
 
7549e78
 
1690c98
 
 
7549e78
1690c98
 
7549e78
1690c98
 
 
 
7549e78
1690c98
7549e78
 
 
 
 
 
 
 
 
 
 
 
 
1690c98
 
 
7549e78
1690c98
 
 
 
 
 
 
 
 
 
 
 
7549e78
 
 
 
 
 
 
 
 
 
 
 
 
1690c98
 
7549e78
 
1690c98
 
 
 
 
 
 
 
 
7549e78
 
 
 
1690c98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7549e78
1690c98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7549e78
1690c98
7549e78
1690c98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7549e78
 
 
 
1690c98
 
 
 
 
 
 
7549e78
755b8ed
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
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

# Set the data directories.  In Hugging Face Spaces, the data should be in the same directory.
train_dir = "train"
val_dir = "val"
test_dir = "test"

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.  In Hugging Face Spaces, they should be relative to the repository root.")
    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 = 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)
    ##### SHORTCUT PATH ####
    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)
    X_shortcut = BatchNormalization(axis=3, name=bn_name_base + '1')(X_shortcut)
    # Final step: Add shortcut value to main path, and pass it through a RELU activation
    X = Add()([X, X_shortcut])
    X = Activation('relu')(X)
    return X

def ResNetCustom(input_shape=(224, 224, 3), classes=2, num_blocks_per_stage=[2, 2, 2, 2]):
    """
    Implementation of a custom ResNet architecture.  You can specify the number of blocks per stage.
    Arguments:
    input_shape -- shape of the images of the dataset
    classes -- integer, number of classes
    num_blocks_per_stage -- a list indicating the number of identity blocks in each stage after the convolutional block
    Returns:
    model -- a Model() instance in Keras
    """
    # Define the input as a tensor with shape input_shape
    X_input = Input(input_shape)
    # Zero-Padding
    X = ZeroPadding2D((3, 3))(X_input)
    # Stage 1
    X = Conv2D(64, (7, 7), strides=(2, 2), name='conv1', kernel_initializer=GlorotUniform(seed=0))(X)
    X = BatchNormalization(axis=3, name='bn_conv1')(X)
    X = Activation('relu')(X)
    X = MaxPooling2D((3, 3), strides=(2, 2))(X)
    # Stage 2
    X = convolutional_block(X, f=3, filters=[64, 64, 256], stage=2, block='a', s=1)
    for i in range(num_blocks_per_stage[0]):
        X = identity_block(X, 3, [64, 64, 256], stage=2, block=chr(ord('b') + i))  # b, c, d...
    # Stage 3
    X = convolutional_block(X, f=3, filters=[128, 128, 512], stage=3, block='a', s=2)
    for i in range(num_blocks_per_stage[1]):
        X = identity_block(X, 3, [128, 128, 512], stage=3, block=chr(ord('b') + i))
    # Stage 4
    X = convolutional_block(X, f=3, filters=[256, 256, 1024], stage=4, block='a', s=2)
    for i in range(num_blocks_per_stage[2]):
        X = identity_block(X, 3, [256, 256, 1024], stage=4, block=chr(ord('b') + i))
    # Stage 5
    X = convolutional_block(X, f=3, filters=[512, 512, 2048], stage=5, block='a', s=2)
    for i in range(num_blocks_per_stage[3]):
        X = identity_block(X, 3, [512, 512, 2048], stage=5, block=chr(ord('b') + i))
    # AVGPOOL
    X = AveragePooling2D(pool_size=(2, 2), name='avg_pool')(X)
    # FLATTEN
    X = Flatten()(X)
    # Fully connected layer
    X = Dense(classes, activation='softmax', name='fc' + str(classes), kernel_initializer=GlorotUniform(seed=0))(X)
    # Create model
    model = Model(inputs=X_input, outputs=X, name='ResNetCustom')
    return model

# Build the model
model = ResNetCustom(input_shape=(img_height, img_width, 3), classes=num_classes, num_blocks_per_stage=[1, 1, 1, 1])

# Compile the model
optimizer = Adam(learning_rate=0.001)
model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])

# Model summary
model.summary()

# Define callbacks
checkpoint_path = 'best_resnet_model.keras'
checkpoint = ModelCheckpoint(
    filepath=checkpoint_path,  # Use a simple filename
    monitor='val_accuracy',
    verbose=1,
    save_best_only=True,
    mode='max'
)

reduce_lr = ReduceLROnPlateau(
    monitor='val_loss',
    factor=0.2,
    patience=5,
    verbose=1,
    mode='min',
    min_lr=1e-6
)

early_stopping = EarlyStopping(
    monitor='val_loss',
    patience=10,
    restore_best_weights=True,
    verbose=1
)

callbacks = [checkpoint, reduce_lr, early_stopping]

# Train the model
try:
    history = model.fit(
        train_generator,
        steps_per_epoch=train_generator.samples // train_generator.batch_size,
        epochs=epochs,
        validation_data=validation_generator,
        validation_steps=validation_generator.samples // validation_generator.batch_size,
        callbacks=callbacks,
        verbose=1
    )
    print("Training complete!")

    # Evaluate the model on the test set
    test_loss, test_accuracy = model.evaluate(test_generator, steps=test_generator.samples // test_generator.batch_size, verbose=1)
    print(f"Test Loss: {test_loss:.4f}")
    print(f"Test Accuracy: {test_accuracy:.4f}")

    # Save the *entire* model, not just the weights.  This is crucial for Hugging Face.
    model.save("resnet_model.keras")  # Save as a .keras file
    print("Trained model saved to resnet_model.keras")

except KeyboardInterrupt:
    print("\nTraining interrupted by user (Ctrl+C).")
    print("Saving the model so far...")
    model.save('interrupted_resnet_model.keras')
    print("Model saved.  You can resume training later by loading this model.")
except Exception as e:
    print(f"An error occurred during training: {e}")
    print("Please check your data and model configuration.")
    print("Please check your data and model configuration.")