CoolFace
Modelpublic

Siddhartha276/Fall_Detection

sourceHugging Facemitupdated 1y agoView on Hugging Face
0likes15downloads
cnn.py136 linesDownload Raw Back to root
1from google.colab import drive2drive.mount('/content/drive')3 4import tensorflow as tf5from tensorflow.keras.applications import EfficientNetB06from tensorflow.keras.layers import GlobalAveragePooling2D, Dropout, Dense, BatchNormalization7from tensorflow.keras.models import Model8from tensorflow.keras.regularizers import l29from tensorflow.keras.preprocessing import image_dataset_from_directory10import matplotlib.pyplot as plt11import numpy as np12from energyCnV import EnergyMonitor13 14 15# Dataset paths16train_dir = " " # Training data URI17val_dir = " " # Validiation or testing data URI18IMG_SIZE = (224, 224)19BATCH_SIZE = 3220 21# Load datasets22train_dataset = image_dataset_from_directory(23    train_dir,24    shuffle=True,25    batch_size=BATCH_SIZE,26    image_size=IMG_SIZE,27    seed=4228)29 30val_dataset = image_dataset_from_directory(31    val_dir,32    shuffle=True,33    batch_size=BATCH_SIZE,34    image_size=IMG_SIZE,35    seed=4236)37 38# Data augmentation39data_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 preprocessing46preprocess_input = tf.keras.applications.efficientnet.preprocess_input47 48# Model builder49def 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 initially53 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_model65 66# Build and compile model67model, base_model = build_fall_model()68 69model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),70              loss='binary_crossentropy',71              metrics=['accuracy'])72 73# Initial training74initial_epochs = 1075history = model.fit(train_dataset, validation_data=val_dataset, epochs=initial_epochs)76 77# Fine-tuning78base_model.trainable = True79fine_tune_at = 15080 81for layer in base_model.layers[:fine_tune_at]:82    layer.trainable = False83 84model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=1e-4),85              loss='binary_crossentropy',86              metrics=['accuracy'])87 88fine_tune_epochs = 589total_epochs = initial_epochs + fine_tune_epochs90 91history_fine = model.fit(train_dataset, validation_data=val_dataset,92                         epochs=total_epochs, initial_epoch=history.epoch[-1]+1)93 94# Plot Accuracy and Loss95acc = history.history['accuracy'] + history_fine.history['accuracy']96val_acc = history.history['val_accuracy'] + history_fine.history['val_accuracy']97 98loss = history.history['loss'] + history_fine.history['loss']99val_loss = history.history['val_loss'] + history_fine.history['val_loss']100 101epochs_range = range(len(acc))102 103plt.figure(figsize=(16, 6))104plt.subplot(1, 2, 1)105plt.plot(epochs_range, acc, label='Training Accuracy')106plt.plot(epochs_range, val_acc, label='Validation Accuracy')107plt.legend(loc='lower right')108plt.title('Training and Validation Accuracy')109 110plt.subplot(1, 2, 2)111plt.plot(epochs_range, loss, label='Training Loss')112plt.plot(epochs_range, val_loss, label='Validation Loss')113plt.legend(loc='upper right')114plt.title('Training and Validation Loss')115 116plt.show()117 118from tensorflow.keras.preprocessing import image119 120img_path = " " # Test Image URI121img = image.load_img(img_path, target_size=IMG_SIZE)122img_array = image.img_to_array(img)123img_array = np.expand_dims(img_array, axis=0)124img_array = preprocess_input(img_array)125 126plt.imshow(img)127plt.axis("off")128plt.show()129 130prediction = model.predict(img_array)131print(prediction)132 133if prediction[0] < 0.5:134    print("Prediction: ๐Ÿšจ Fall Detected! ๐Ÿšจ")135else:136    print("Prediction: โœ… No Fall Detected.")