SwatiGuide / app_py.py
newRoop's picture
Update app_py.py
25d1474 verified
Raw History Blame Contribute Delete
15 kB
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 = 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 = ModelCheckpoint(
filepath='best_resnet_model.keras',
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}")
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.")