Siddhartha276 commited on
Commit
cfa1fc6
·
verified ·
1 Parent(s): 002ce59

Upload cnn.py

Browse files
Files changed (1) hide show
  1. cnn.py +136 -0
cnn.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from google.colab import drive
2
+ drive.mount('/content/drive')
3
+
4
+ import tensorflow as tf
5
+ from tensorflow.keras.applications import EfficientNetB0
6
+ from tensorflow.keras.layers import GlobalAveragePooling2D, Dropout, Dense, BatchNormalization
7
+ from tensorflow.keras.models import Model
8
+ from tensorflow.keras.regularizers import l2
9
+ from tensorflow.keras.preprocessing import image_dataset_from_directory
10
+ import matplotlib.pyplot as plt
11
+ import numpy as np
12
+ from energyCnV import EnergyMonitor
13
+
14
+
15
+ # Dataset paths
16
+ train_dir = " " # Training data URI
17
+ val_dir = " " # Validiation or testing data URI
18
+ IMG_SIZE = (224, 224)
19
+ BATCH_SIZE = 32
20
+
21
+ # Load datasets
22
+ train_dataset = image_dataset_from_directory(
23
+ train_dir,
24
+ shuffle=True,
25
+ batch_size=BATCH_SIZE,
26
+ image_size=IMG_SIZE,
27
+ seed=42
28
+ )
29
+
30
+ val_dataset = image_dataset_from_directory(
31
+ val_dir,
32
+ shuffle=True,
33
+ batch_size=BATCH_SIZE,
34
+ image_size=IMG_SIZE,
35
+ seed=42
36
+ )
37
+
38
+ # Data augmentation
39
+ data_augmentation = tf.keras.Sequential([
40
+ tf.keras.layers.RandomFlip('horizontal'),
41
+ tf.keras.layers.RandomRotation(0.2),
42
+ tf.keras.layers.RandomZoom(0.3),
43
+ ])
44
+
45
+ # EfficientNet preprocessing
46
+ preprocess_input = tf.keras.applications.efficientnet.preprocess_input
47
+
48
+ # Model builder
49
+ def build_fall_model():
50
+ input_shape = IMG_SIZE + (3,)
51
+ base_model = EfficientNetB0(include_top=False, input_shape=input_shape, weights="imagenet")
52
+ base_model.trainable = False # Freeze base model initially
53
+
54
+ inputs = tf.keras.Input(shape=input_shape)
55
+ x = data_augmentation(inputs)
56
+ x = preprocess_input(x)
57
+ x = base_model(x, training=False)
58
+ x = GlobalAveragePooling2D()(x)
59
+ x = BatchNormalization()(x)
60
+ x = Dropout(0.4)(x)
61
+ outputs = Dense(1, activation='sigmoid', kernel_regularizer=l2(0.001))(x)
62
+
63
+ model = Model(inputs, outputs)
64
+ return model, base_model
65
+
66
+ # Build and compile model
67
+ model, base_model = build_fall_model()
68
+
69
+ model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),
70
+ loss='binary_crossentropy',
71
+ metrics=['accuracy'])
72
+
73
+ # Initial training
74
+ initial_epochs = 10
75
+ history = model.fit(train_dataset, validation_data=val_dataset, epochs=initial_epochs)
76
+
77
+ # Fine-tuning
78
+ base_model.trainable = True
79
+ fine_tune_at = 150
80
+
81
+ for layer in base_model.layers[:fine_tune_at]:
82
+ layer.trainable = False
83
+
84
+ model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=1e-4),
85
+ loss='binary_crossentropy',
86
+ metrics=['accuracy'])
87
+
88
+ fine_tune_epochs = 5
89
+ total_epochs = initial_epochs + fine_tune_epochs
90
+
91
+ history_fine = model.fit(train_dataset, validation_data=val_dataset,
92
+ epochs=total_epochs, initial_epoch=history.epoch[-1]+1)
93
+
94
+ # Plot Accuracy and Loss
95
+ acc = history.history['accuracy'] + history_fine.history['accuracy']
96
+ val_acc = history.history['val_accuracy'] + history_fine.history['val_accuracy']
97
+
98
+ loss = history.history['loss'] + history_fine.history['loss']
99
+ val_loss = history.history['val_loss'] + history_fine.history['val_loss']
100
+
101
+ epochs_range = range(len(acc))
102
+
103
+ plt.figure(figsize=(16, 6))
104
+ plt.subplot(1, 2, 1)
105
+ plt.plot(epochs_range, acc, label='Training Accuracy')
106
+ plt.plot(epochs_range, val_acc, label='Validation Accuracy')
107
+ plt.legend(loc='lower right')
108
+ plt.title('Training and Validation Accuracy')
109
+
110
+ plt.subplot(1, 2, 2)
111
+ plt.plot(epochs_range, loss, label='Training Loss')
112
+ plt.plot(epochs_range, val_loss, label='Validation Loss')
113
+ plt.legend(loc='upper right')
114
+ plt.title('Training and Validation Loss')
115
+
116
+ plt.show()
117
+
118
+ from tensorflow.keras.preprocessing import image
119
+
120
+ img_path = " " # Test Image URI
121
+ img = image.load_img(img_path, target_size=IMG_SIZE)
122
+ img_array = image.img_to_array(img)
123
+ img_array = np.expand_dims(img_array, axis=0)
124
+ img_array = preprocess_input(img_array)
125
+
126
+ plt.imshow(img)
127
+ plt.axis("off")
128
+ plt.show()
129
+
130
+ prediction = model.predict(img_array)
131
+ print(prediction)
132
+
133
+ if prediction[0] < 0.5:
134
+ print("Prediction: 🚨 Fall Detected! 🚨")
135
+ else:
136
+ print("Prediction: ✅ No Fall Detected.")