newRoop commited on
Commit
eea2cd1
Β·
verified Β·
1 Parent(s): fe5961b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +34 -38
app.py CHANGED
@@ -1,5 +1,6 @@
1
  import subprocess
2
  import sys
 
3
 
4
  def install_tensorflow():
5
  """
@@ -16,15 +17,15 @@ def install_tensorflow():
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}")
@@ -39,47 +40,52 @@ def check_tensorflow_installation():
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(
@@ -93,7 +99,7 @@ train_datagen = ImageDataGenerator(
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
@@ -129,8 +135,6 @@ except Exception as 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
@@ -167,8 +171,6 @@ def identity_block(X, f, filters, stage, block):
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
@@ -208,8 +210,6 @@ def convolutional_block(X, f, filters, stage, block, s=2):
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.
@@ -255,11 +255,9 @@ def ResNetCustom(input_shape=(224, 224, 3), classes=2, num_blocks_per_stage=[2,
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)
@@ -313,13 +311,11 @@ try:
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
-
 
1
  import subprocess
2
  import sys
3
+ import os # Import the os module
4
 
5
  def install_tensorflow():
6
  """
 
17
  text=True, # Return output as text
18
  )
19
  print("TensorFlow installed successfully.")
20
+ print(result.stdout)
21
 
22
  except subprocess.CalledProcessError as e:
23
  print(f"Error installing TensorFlow: {e}")
24
+ print(f"Error output (stderr):\n{e.stderr}")
25
  print("Please check your pip installation and internet connection.")
26
  print("You may need to install TensorFlow manually. Instructions can be found at:")
27
  print("https://www.tensorflow.org/install")
28
+ sys.exit(1)
29
 
30
  except Exception as ex:
31
  print(f"An unexpected error occurred during TensorFlow installation: {ex}")
 
40
  import tensorflow as tf
41
  print(f"TensorFlow version: {tf.__version__}")
42
  print("TensorFlow is installed and ready to use.")
43
+ return True
44
  except ImportError:
45
  print("TensorFlow is not installed.")
46
  install_tensorflow()
47
+ return False
48
 
49
  # Check and install TensorFlow if necessary
50
  if not check_tensorflow_installation():
51
+ check_tensorflow_installation()
 
 
52
 
53
+ import tensorflow as tf
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
 
61
+ # Check if running in Google Colab
62
  try:
63
+ from google.colab import drive
64
+ IS_COLAB = True
65
+ except ImportError:
66
+ IS_COLAB = False
67
+ print("Not running in Google Colab. Using local file paths.")
68
+
69
+ # Mount Google Drive if in Colab
70
+ if IS_COLAB:
71
+ try:
72
+ drive.mount("/content/drive", timeout_ms=60000)
73
+ except Exception as e:
74
+ print(f"Error mounting drive: {e}")
75
+ print("Continuing without Google Drive...")
76
+ train_dir = 'train'
77
+ val_dir = 'val'
78
+ test_dir = 'test'
79
  else:
80
+ # Define your data directories for local system
81
+ train_dir = "data/train" # local paths
82
+ val_dir = "data/val"
83
+ test_dir = "data/test"
84
 
85
+ img_height, img_width = 224, 224
86
  batch_size = 32
87
  epochs = 100
88
+ num_classes = 2
89
 
90
  # Data augmentation (optional but recommended)
91
  train_datagen = ImageDataGenerator(
 
99
  fill_mode='nearest'
100
  )
101
 
102
+ val_datagen = ImageDataGenerator(rescale=1. / 255)
103
  test_datagen = ImageDataGenerator(rescale=1. / 255)
104
 
105
  # Create data generators
 
135
  print("Please check your directory paths and data.")
136
  exit()
137
 
 
 
138
  def identity_block(X, f, filters, stage, block):
139
  """
140
  Implementation of the identity block as defined in Figure 3 of the paper
 
171
  X = Activation('relu')(X)
172
  return X
173
 
 
 
174
  def convolutional_block(X, f, filters, stage, block, s=2):
175
  """
176
  Implementation of the convolutional block as defined in Figure 4
 
210
  X = Activation('relu')(X)
211
  return X
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.
 
255
  model = Model(inputs=X_input, outputs=X, name='ResNetCustom')
256
  return model
257
 
 
 
258
  # Build the model
259
  # You can customize the number of blocks per stage here. For a ResNet-10, use [1,1,1,1]
260
+ model = ResNetCustom(input_shape=(img_height, img_width, 3), classes=num_classes, num_blocks_per_stage=[1, 1, 1, 1])
261
 
262
  # Compile the model
263
  optimizer = Adam(learning_rate=0.001)
 
311
  print(f"Test Loss: {test_loss:.4f}")
312
  print(f"Test Accuracy: {test_accuracy:.4f}")
313
 
 
314
  except KeyboardInterrupt:
315
  print("\nTraining interrupted by user (Ctrl+C).")
316
  print("Saving the model so far...")
317
+ model.save('interrupted_resnet_model.keras')
318
  print("Model saved. You can resume training later by loading this model.")
319
  except Exception as e:
320
  print(f"An error occurred during training: {e}")
321
  print("Please check your data and model configuration.")