Spaces:
Sleeping
Sleeping
Upload 15 files
Browse filesFiles changed (15)
- .gitignore.txtAdded+22
- Attention.pyAdded+321
- README.md+23-13
- Self.pyAdded+62
- aug.pyAdded+68
- cnn_multi.pyAdded+759
- curve.pyAdded+39
- gen.pyAdded+154
- generate_gradcam.pyAdded+166
- new_report.pyAdded+181
- packages.txtAdded+82
- predict.pyAdded+74
- report.pyAdded+161
- requirements.txtAdded+87
- train.pyAdded+239
12345678910111213141516171819202122.ipynb_checkpoints
__pycache__
Dataset
LATEST
Logs
mod
Nov 2025
Plot
Records
Update 2k25 nov
utils
vsv
gradcam
h
new_report
old train.py
packages
ProposedNetwork_StratifiedKFold_Final_fold_5_training
qwerty
train old
Untitled
Untitled2123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321from keras.layers import GlobalAveragePooling2D, GlobalMaxPooling2D, Reshape, Dense, multiply, Multiply, Permute, Concatenate, Conv2D, Add, Activation, Lambda, AveragePooling2D, BatchNormalization, UpSampling2Dfrom keras.layers import Dense, Layer, Dropoutfrom keras import backend as Kfrom keras.activations import sigmoidimport tensorflow as tf
def custom_attention(input_feature, ratio=8, kernel_size=7): """ Custom Attention Module: Combines Spatial Attention and Channel Attention (SE). """ # Get channel dimension channel_axis = 1 if K.image_data_format() == "channels_first" else -1 channel = K.int_shape(input_feature)[channel_axis] assert channel is not None, "Input feature map must have a defined channel dimension."
# ----- Condition A: Spatial Attention ----- # Global Average Pooling avg_pool = Lambda(lambda x: K.mean(x, axis=channel_axis, keepdims=True))(input_feature) assert K.int_shape(avg_pool)[channel_axis] == 1, "Average pooling should reduce channel axis to 1." # Global Max Pooling max_pool = Lambda(lambda x: K.max(x, axis=channel_axis, keepdims=True))(input_feature) assert K.int_shape(max_pool)[channel_axis] == 1, "Max pooling should reduce channel axis to 1." # Concatenate along channel axis concat = Concatenate(axis=channel_axis)([avg_pool, max_pool]) assert K.int_shape(concat)[channel_axis] == 2, "Concatenation should result in 2 channels (Avg + Max)." # Convolution to produce spatial attention weights spatial_attention = Conv2D(filters=1, kernel_size=kernel_size, strides=1, padding='same', activation='sigmoid')(concat) assert K.int_shape(spatial_attention)[channel_axis] == 1, "Spatial attention should have 1 channel after Conv2D." # Apply spatial attention weights F_s = multiply([input_feature, spatial_attention]) assert K.int_shape(F_s) == K.int_shape(input_feature), "Spatially refined feature map should match input dimensions."
# ----- Condition B: Channel Attention (SE Block) ----- # Squeeze: Global Average Pooling gap = GlobalAveragePooling2D()(input_feature) assert K.int_shape(gap)[-1] == channel, "Global Average Pooling should reduce spatial dimensions but keep channels." # First Dense Layer (Reduction) dense1 = Dense(channel // ratio, activation='relu', kernel_initializer='he_normal', use_bias=True)(gap) assert K.int_shape(dense1)[-1] == channel // ratio, "First Dense layer should reduce channels by 'ratio'." # Second Dense Layer (Expansion) dense2 = Dense(channel, activation='sigmoid', kernel_initializer='he_normal', use_bias=True)(dense1) assert K.int_shape(dense2)[-1] == channel, "Second Dense layer should restore the original channel size." # Reshape to apply channel attention channel_attention = Reshape((1, 1, channel))(dense2) assert K.int_shape(channel_attention)[1:] == (1, 1, channel), "Channel attention should have shape (1, 1, channels)." # Apply channel attention weights F_c = multiply([input_feature, channel_attention]) assert K.int_shape(F_c) == K.int_shape(input_feature), "Channel-refined feature map should match input dimensions."
# ----- Combine Spatial and Channel Attention ----- output = Add()([F_s, F_c]) assert K.int_shape(output) == K.int_shape(input_feature), "Final output should match the input dimensions."
return output
# class MultiHeadSelfAttention(Layer):# def __init__(self, num_heads, key_dim=None, dropout=0.1, **kwargs):# super(MultiHeadSelfAttention, self).__init__(**kwargs)# self.num_heads = num_heads# self.key_dim = key_dim# self.dropout = Dropout(dropout) # def build(self, input_shape):# embedding_dim = input_shape[-1] # # Calculate key_dim if not specified and ensure divisibility# if self.key_dim is None:# if embedding_dim % self.num_heads != 0:# raise ValueError(f"Embedding dimension {embedding_dim} must be divisible by num_heads {self.num_heads}.")# self.key_dim = embedding_dim // self.num_heads # self.query_dense = Dense(self.num_heads * self.key_dim, use_bias=False)# self.key_dense = Dense(self.num_heads * self.key_dim, use_bias=False)# self.value_dense = Dense(self.num_heads * self.key_dim, use_bias=False)# self.output_dense = Dense(embedding_dim, use_bias=False)# super(MultiHeadSelfAttention, self).build(input_shape) # def call(self, inputs):# batch_size = tf.shape(inputs)[0] # # Project inputs to queries, keys, and values# query = self.query_dense(inputs)# key = self.key_dense(inputs)# value = self.value_dense(inputs) # # Split into heads# query = self._split_heads(query, batch_size)# key = self._split_heads(key, batch_size)# value = self._split_heads(value, batch_size) # # Scaled dot-product attention# attention_scores = tf.matmul(query, key, transpose_b=True)# attention_scores = attention_scores / tf.math.sqrt(tf.cast(self.key_dim, tf.float32))# attention_weights = tf.nn.softmax(attention_scores, axis=-1)# attention_weights = self.dropout(attention_weights)
# # Compute attention context# context = tf.matmul(attention_weights, value)# context = self._combine_heads(context, batch_size) # # Final linear projection# output = self.output_dense(context)# return output
# def _split_heads(self, x, batch_size):# """Split the last dimension into (num_heads, key_dim)."""# x = tf.reshape(x, (batch_size, -1, self.num_heads, self.key_dim))# return tf.transpose(x, perm=[0, 2, 1, 3])
# def _combine_heads(self, x, batch_size):# """Combine the heads into the original shape."""# x = tf.transpose(x, perm=[0, 2, 1, 3])# return tf.reshape(x, (batch_size, -1, self.num_heads * self.key_dim)) # def get_config(self):# config = super(MultiHeadSelfAttention, self).get_config()# config.update({"num_heads": self.num_heads, "key_dim": self.key_dim})# return config
# class LayerNormalization(Layer):# def __init__(self, epsilon=1e-6, **kwargs):# self.epsilon = epsilon# super(LayerNormalization, self).__init__(**kwargs)
# def build(self, input_shape):# self.gamma = self.add_weight(name='gamma', shape=input_shape[-1:], initializer='ones', trainable=True)# self.beta = self.add_weight(name='beta', shape=input_shape[-1:], initializer='zeros', trainable=True)# super(LayerNormalization, self).build(input_shape)
# def call(self, inputs):# mean = K.mean(inputs, axis=-1, keepdims=True)# std = K.std(inputs, axis=-1, keepdims=True)# return self.gamma * (inputs - mean) / (std + self.epsilon) + self.beta # def get_config(self):# config = super(LayerNormalization, self).get_config()# config.update({"epsilon": self.epsilon})# return config
def attach_attention_module(net, attention_module): if attention_module == 'se_block': # SE_block net = se_block(net) elif attention_module == 'cbam_block': # CBAM_block net = cbam_block(net) elif attention_module == 'self_attention_block': # self_attention_block net = self_attention_block(net) else: raise Exception("'{}' is not supported attention module!".format(attention_module))
return net
def se_block(input_feature, ratio=8): """Contains the implementation of Squeeze-and-Excitation(SE) block. As described in https://arxiv.org/abs/1709.01507. """ channel_axis = 1 if K.image_data_format() == "channels_first" else -1 channel = input_feature.shape[channel_axis]
se_feature = GlobalAveragePooling2D()(input_feature) se_feature = Reshape((1, 1, channel))(se_feature) assert se_feature.shape[1:] == (1,1,channel) se_feature = Dense(channel // ratio, activation='relu', kernel_initializer='he_normal', use_bias=True, bias_initializer='zeros')(se_feature) assert se_feature.shape[1:] == (1,1,channel//ratio) se_feature = Dense(channel, activation='sigmoid', kernel_initializer='he_normal', use_bias=True, bias_initializer='zeros')(se_feature) assert se_feature.shape[1:] == (1,1,channel) if K.image_data_format() == 'channels_first': se_feature = Permute((3, 1, 2))(se_feature)
se_feature = multiply([input_feature, se_feature]) return se_feature
def cbam_block(cbam_feature, ratio=8): """Contains the implementation of Convolutional Block Attention Module(CBAM) block. As described in https://arxiv.org/abs/1807.06521. """ cbam_feature = channel_attention(cbam_feature, ratio) cbam_feature = spatial_attention(cbam_feature) return cbam_feature
def channel_attention(input_feature, ratio=8): channel_axis = 1 if K.image_data_format() == "channels_first" else -1 channel = input_feature.shape[channel_axis] shared_layer_one = Dense(channel//ratio, activation='relu', kernel_initializer='he_normal', use_bias=True, bias_initializer='zeros') shared_layer_two = Dense(channel, kernel_initializer='he_normal', use_bias=True, bias_initializer='zeros') avg_pool = GlobalAveragePooling2D()(input_feature) avg_pool = Reshape((1,1,channel))(avg_pool) assert avg_pool.shape[1:] == (1,1,channel) avg_pool = shared_layer_one(avg_pool) assert avg_pool.shape[1:] == (1,1,channel//ratio) avg_pool = shared_layer_two(avg_pool) assert avg_pool.shape[1:] == (1,1,channel) max_pool = GlobalMaxPooling2D()(input_feature) max_pool = Reshape((1,1,channel))(max_pool) assert max_pool.shape[1:] == (1,1,channel) max_pool = shared_layer_one(max_pool) assert max_pool.shape[1:] == (1,1,channel//ratio) max_pool = shared_layer_two(max_pool) assert max_pool.shape[1:] == (1,1,channel) cbam_feature = Add()([avg_pool,max_pool]) cbam_feature = Activation('sigmoid')(cbam_feature) if K.image_data_format() == "channels_first": cbam_feature = Permute((3, 1, 2))(cbam_feature) return multiply([input_feature, cbam_feature])
def spatial_attention(input_feature): kernel_size = 7 if K.image_data_format() == "channels_first": channel = input_feature.shape[1] cbam_feature = Permute((2,3,1))(input_feature) else: channel = input_feature.shape[-1] cbam_feature = input_feature avg_pool = Lambda(lambda x: K.mean(x, axis=3, keepdims=True))(cbam_feature) assert avg_pool.shape[-1] == 1 max_pool = Lambda(lambda x: K.max(x, axis=3, keepdims=True))(cbam_feature) assert max_pool.shape[-1] == 1 concat = Concatenate(axis=3)([avg_pool, max_pool]) assert concat.shape[-1] == 2 cbam_feature = Conv2D(filters = 1, kernel_size=kernel_size, strides=1, padding='same', activation='sigmoid', kernel_initializer='he_normal', use_bias=False)(concat) assert cbam_feature.shape[-1] == 1 if K.image_data_format() == "channels_first": cbam_feature = Permute((3, 1, 2))(cbam_feature) return multiply([input_feature, cbam_feature])
from keras.layers import Conv2D, BatchNormalization, Activation, Reshape, Permute, multiply, AveragePooling2D, UpSampling2D, Cropping2D, ZeroPadding2D, Lambdaimport tensorflow.keras.backend as K
def self_attention_block(input_tensor, reduction_ratio=4): # Step 1: Downsample spatially to reduce memory usage reduced_input = AveragePooling2D(pool_size=(reduction_ratio, reduction_ratio), padding='same')(input_tensor) # Extract spatial dimensions and channels shape = K.int_shape(reduced_input) height, width, channels = shape[1], shape[2], shape[3] # Flatten the spatial dimensions for query, key, and value query = Reshape((height * width, channels))(reduced_input) key = Reshape((height * width, channels))(reduced_input) value = Reshape((height * width, channels))(reduced_input) # Step 3: Calculate attention matrix with axes adjustment attention_scores = K.batch_dot(query, key, axes=[2, 2]) / K.sqrt(K.cast(channels, K.floatx())) attention_scores = Activation('softmax')(attention_scores) # Step 4: Multiply attention scores with value attention_output = K.batch_dot(attention_scores, value, axes=[1, 1]) # Step 5: Reshape attention output back to reduced input shape attention_output = Reshape((height, width, channels))(attention_output) # Step 6: Upsample to match input tensor's dimensions attention_output = UpSampling2D(size=(reduction_ratio, reduction_ratio), interpolation='bilinear')(attention_output) attention_output = Conv2D(K.int_shape(input_tensor)[-1], (1, 1), padding='same', activation='sigmoid')(attention_output)
# Step 7: Adjust dimensions if there's a mismatch input_shape = K.int_shape(input_tensor) output_shape = K.int_shape(attention_output) height_diff = input_shape[1] - output_shape[1] width_diff = input_shape[2] - output_shape[2]
# Apply padding or cropping to align dimensions if height_diff > 0 or width_diff > 0: # Pad attention_output to match input_tensor dimensions padding_height = (height_diff // 2, height_diff - height_diff // 2) padding_width = (width_diff // 2, width_diff - width_diff // 2) attention_output = ZeroPadding2D(padding=(padding_height, padding_width))(attention_output) elif height_diff < 0 or width_diff < 0: # Crop attention_output to match input_tensor dimensions cropping_height = (abs(height_diff) // 2, abs(height_diff) - abs(height_diff) // 2) cropping_width = (abs(width_diff) // 2, abs(width_diff) - abs(width_diff) // 2) attention_output = Cropping2D(cropping=(cropping_height, cropping_width))(attention_output)
# Step 8: Multiply input and attention output (residual connection) output = multiply([input_tensor, attention_output]) return output123456789101112131234567891011121314151617181920212223---title: Fire Detectionemoji: 🏃colorFrom: greencolorTo: indigosdk: gradiosdk_version: 6.0.1app_file: app.pypinned: falselicense: mit---
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference# Fire-Classification
## Installation
* Install requirements in your environment.
* Clone this repository.
* Download fire datasets by following the instructions below and put into "Dataset" folder.
## Datasets
* We use 6 datasets:
* FireNet
* FireSense
* CairFire
* FireSmoke
* FireDetection
* ThermalFire (Proposed dataset)
## Training and evaluation
* Command line: (`python train.py`)
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162from keras.layers import Conv2D, BatchNormalization, Activation, Reshape, Permute, multiply, AveragePooling2D, UpSampling2D, Cropping2D, ZeroPadding2D, Lambda
import tensorflow.keras.backend as K
def self_attention_block(input_tensor, reduction_ratio=4):
# Step 1: Downsample spatially to reduce memory usage
reduced_input = AveragePooling2D(pool_size=(reduction_ratio, reduction_ratio), padding='same')(input_tensor)
# Extract spatial dimensions and channels
shape = K.int_shape(reduced_input)
height, width, channels = shape[1], shape[2], shape[3]
# Flatten the spatial dimensions for query, key, and value
query = Reshape((height * width, channels))(reduced_input)
key = Reshape((height * width, channels))(reduced_input)
value = Reshape((height * width, channels))(reduced_input)
# Step 3: Calculate attention matrix with axes adjustment
# attention_scores = K.batch_dot(query, key, axes=[2, 2]) / K.sqrt(K.cast(channels, K.floatx()))
# attention_scores = Activation('softmax')(attention_scores)
key_T = Permute((2, 1))(key)
attention_scores = K.batch_dot(query, key_T)
attention_scores = attention_scores / K.sqrt(K.cast(channels, K.floatx()))
attention_scores = Activation('softmax')(attention_scores)
# Step 4: Multiply attention scores with value
# attention_output = K.batch_dot(attention_scores, value, axes=[1, 1])
attention_output = K.batch_dot(attention_scores, value)
# Step 5: Reshape attention output back to reduced input shape
attention_output = Reshape((height, width, channels))(attention_output)
# Step 6: Upsample to match input tensor's dimensions
attention_output = UpSampling2D(size=(reduction_ratio, reduction_ratio), interpolation='bilinear')(attention_output)
attention_output = Conv2D(K.int_shape(input_tensor)[-1], (1, 1), padding='same', activation='sigmoid')(attention_output)
# Step 7: Adjust dimensions if there's a mismatch
input_shape = K.int_shape(input_tensor)
output_shape = K.int_shape(attention_output)
height_diff = input_shape[1] - output_shape[1]
width_diff = input_shape[2] - output_shape[2]
# Apply padding or cropping to align dimensions
if height_diff > 0 or width_diff > 0:
# Pad attention_output to match input_tensor dimensions
padding_height = (height_diff // 2, height_diff - height_diff // 2)
padding_width = (width_diff // 2, width_diff - width_diff // 2)
attention_output = ZeroPadding2D(padding=(padding_height, padding_width))(attention_output)
elif height_diff < 0 or width_diff < 0:
# Crop attention_output to match input_tensor dimensions
cropping_height = (abs(height_diff) // 2, abs(height_diff) - abs(height_diff) // 2)
cropping_width = (abs(width_diff) // 2, abs(width_diff) - abs(width_diff) // 2)
attention_output = Cropping2D(cropping=(cropping_height, cropping_width))(attention_output)
# Step 8: Multiply input and attention output (residual connection)
output = multiply([input_tensor, attention_output])
return output1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768from keras.preprocessing.image import ImageDataGenerator, img_to_array, load_imgimport osimport tensorflow as tf
# Pathsdataset_path = './Dataset/FireNet/' # Original dataset pathaugmented_dataset_path = './Dataset/FireNet_Augmented/' # Path to save augmented images
# Ensure augmented directory existsos.makedirs(augmented_dataset_path, exist_ok=True)
# Augmentation parametersaugmentation_multiplier = 3 # Number of augmented images per original imagetarget_size = (224, 224) # Resize dimensions
# Define augmentation functiondef augment_image(image): """Apply GPU-accelerated augmentations.""" image = tf.image.random_flip_left_right(image) # Horizontal flip image = tf.image.random_flip_up_down(image) # Vertical flip image = tf.image.random_brightness(image, max_delta=0.3) # Random brightness image = tf.image.random_contrast(image, lower=0.7, upper=1.3) # Random contrast image = tf.image.random_saturation(image, lower=0.7, upper=1.3) # Random saturation image = tf.image.random_hue(image, max_delta=0.1) # Random hue image = tf.image.resize_with_crop_or_pad(image, target_size[0] + 10, target_size[1] + 10) # Add padding image = tf.image.random_crop(image, size=[target_size[0], target_size[1], 3]) # Random crop image = tf.clip_by_value(image, 0.0, 1.0) # Ensure pixel values are between [0, 1] return image
# Process and save augmented imagesfor class_folder in os.listdir(dataset_path): class_path = os.path.join(dataset_path, class_folder) if not os.path.isdir(class_path): continue # Create corresponding folder for augmented images augmented_class_path = os.path.join(augmented_dataset_path, class_folder) os.makedirs(augmented_class_path, exist_ok=True) for img_idx, img_name in enumerate(os.listdir(class_path), start=1): # Track image number with img_idx img_path = os.path.join(class_path, img_name) try: # Load and preprocess the image raw_image = tf.io.read_file(img_path) image = tf.image.decode_image(raw_image, channels=3) image = tf.image.resize(image, target_size) / 255.0 # Normalize to [0, 1] # Print progress print(f"Processing Image {img_idx}: {img_name}") # Save the original image (optional, if you want it in the augmented dataset) tf.keras.preprocessing.image.save_img( os.path.join(augmented_class_path, img_name), image.numpy() ) # Generate augmented images for i in range(augmentation_multiplier): augmented_image = augment_image(image) tf.keras.preprocessing.image.save_img( os.path.join(augmented_class_path, f"aug_{i}_{img_name}"), augmented_image.numpy() ) print(f" Augmented Image {i+1} saved for {img_name}") except Exception as e: print(f"Error processing image {img_path}: {e}")
print("GPU-accelerated augmentation complete!")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759from keras.layers import Activation, Convolution2D, Dropout, Conv2D, Dense, Concatenate, Add, PReLU, LeakyReLU, concatenate, Lambdafrom keras.layers import AveragePooling2D, BatchNormalizationfrom keras.layers import GlobalAveragePooling2D, ZeroPadding2D, UpSampling2Dfrom keras.models import Sequentialfrom keras.layers import Flattenfrom keras.models import Modelfrom keras.layers import Inputfrom keras.layers import MaxPooling2Dfrom keras.layers import SeparableConv2Dfrom keras import layersfrom keras.regularizers import l2from keras import regularizersfrom keras.activations import linearfrom keras.layers import multiply
def count_params(weights): """Counts the total number of parameters in a list of weights.""" return int(sum(tf.keras.backend.count_params(w) for w in weights))
from keras.applications.vgg16 import VGG16from keras.applications.vgg19 import VGG19# from keras.applications import MobileNet, MobileNetV2 # Unused importfrom keras.applications.xception import Xception# from keras.applications import InceptionV3 # Unused import# from keras.applications import DenseNet121 # Unused import# from keras.applications import NASNetMobile # Unused importimport tensorflow as tf
import numpy as npimport cv2
from Attention import cbam_block, se_block, self_attention_block, custom_attention# , MultiHeadSelfAttention, LayerNormalization#from Inception import inception_module
# def resize_like(target, ref):# """Resize `target` tensor to match the spatial dimensions of `ref` tensor."""# target_height, target_width = ref.shape[1], ref.shape[2]# return Lambda(lambda x: tf.image.resize(x, [target_height, target_width]))(target)
def count_model_params(model): total_params = count_params(model.trainable_weights) + count_params(model.non_trainable_weights) trainable_params = count_params(model.trainable_weights) non_trainable_params = count_params(model.non_trainable_weights) return total_params, trainable_params, non_trainable_params
def inception_module(layer_in, f1_1x1, f1_5x5, f2_1x1, f2_3x3, f3_1x1, f4_1x1): # Branch 1: 1x1 DWConv -> 5x5 DWConv branch1 = SeparableConv2D(f1_1x1, (1, 1), padding='same', activation='relu')(layer_in) branch1 = SeparableConv2D(f1_5x5, (5, 5), padding='same', activation='relu')(branch1)
# Branch 2: 1x1 DWConv -> 3x3 DWConv branch2 = SeparableConv2D(f2_1x1, (1, 1), padding='same', activation='relu')(layer_in) branch2 = SeparableConv2D(f2_3x3, (3, 3), padding='same', activation='relu')(branch2)
# Branch 3: 3x3 Max Pooling -> 1x1 DWConv branch3 = MaxPooling2D((3, 3), strides=(1, 1), padding='same')(layer_in) branch3 = SeparableConv2D(f3_1x1, (1, 1), padding='same', activation='relu')(branch3)
# Branch 4: 1x1 DWConv only branch4 = SeparableConv2D(f4_1x1, (1, 1), padding='same', activation='relu')(layer_in)
# Concatenate all branches layer_out = concatenate([branch1, branch2, branch3, branch4], axis=-1) return layer_out
def combine_4SC_2_1_V3(input_shape, num_classes, l2_regularization=0.01): regularization = l2(l2_regularization)
# Block1 - 16 channels img_input = Input(input_shape) x = SeparableConv2D(16, (7, 7), strides=(1, 1), padding='same', kernel_regularizer=regularization, use_bias=False)(img_input) x = BatchNormalization()(x) x = Activation('relu')(x) x = SeparableConv2D(16, (7, 7), strides=(1, 1), padding='same', kernel_regularizer=regularization, use_bias=False)(x) x = BatchNormalization()(x) x = Activation('relu')(x) x = AveragePooling2D((3, 3), strides=(2, 2))(x)# x = se_block(x)# x = cbam_block(x)# x = self_attention_block(x) # block-1 shape # print("block-1:", x.shape) x = custom_attention(x) # block-1 shape # print("block-1:", x.shape) x = Dropout(0.5)(x)
model_block1 = Model(inputs=img_input, outputs=x) total_params, trainable_params, non_trainable_params = count_model_params(model_block1) print(f"Block 1 Parameters: Total={total_params}, Trainable={trainable_params}, Non-trainable={non_trainable_params}") # Block2 - 32 channels x = SeparableConv2D(32, (5, 5), padding='same', kernel_regularizer=regularization, use_bias=False)(x) x = BatchNormalization()(x) x = Activation('relu')(x) x = SeparableConv2D(32, (3, 3), padding='same', kernel_regularizer=regularization, use_bias=False)(x) x = AveragePooling2D((3, 3), strides=(2, 2), padding='same')(x)# x = inception_module(x, 32, 24, 32, 24, 32, 32)# x = se_block(x)# x = cbam_block(x)# x = self_attention_block(x) # block-2 shape # print("block-2:", x.shape) x = custom_attention(x) # block-2 shape # print("block-2:", x.shape) x = Dropout(0.5)(x)
model_block2 = Model(inputs=img_input, outputs=x) total_params, trainable_params, non_trainable_params = count_model_params(model_block2) print(f"Block 2 Parameters: Total={total_params}, Trainable={trainable_params}, Non-trainable={non_trainable_params}") # Block3 - 64 channels residual = SeparableConv2D(32, (3, 3), strides=(1, 1),padding='same', use_bias=False)(x) residual = AveragePooling2D((3, 3), strides=(2, 2), padding='same')(residual) residual = SeparableConv2D(64, (1, 1), strides=(1, 1), padding='same', use_bias=False)(residual) # residual = BatchNormalization()(residual) # residual = se_block(residual) # residual = cbam_block(residual) # block-3 shape # print("block-3 res before att:", residual.shape)# residual = custom_attention(residual) # block-3 shape # print("block-3 res after att:", residual.shape)
model_c1 = Model(inputs=img_input, outputs=x) total_params, trainable_params, non_trainable_params = count_model_params(model_c1) print(f"Connection 1 Parameters: Total={total_params}, Trainable={trainable_params}, Non-trainable={non_trainable_params}") # 2nd Inception and CBAM x = SeparableConv2D(64, (5, 5), padding='same', kernel_regularizer=regularization, use_bias=False)(x) x = BatchNormalization()(x) x = Activation('relu')(x) x = SeparableConv2D(64, (3, 3), padding='same', kernel_regularizer=regularization, use_bias=False)(x) # x = BatchNormalization()(x) # x = Activation('relu')(x) x = AveragePooling2D((3, 3),padding='same', strides=(2, 2))(x)# x = inception_module(x, 32, 16, 32, 16, 16, 16)# x = se_block(x)# x = cbam_block(x)# x = self_attention_block(x) x = custom_attention(x) x = Dropout(0.5)(x) model_block3 = Model(inputs=img_input, outputs=x) total_params, trainable_params, non_trainable_params = count_model_params(model_block3) print(f"Block 3 Parameters: Total={total_params}, Trainable={trainable_params}, Non-trainable={non_trainable_params}") #Connection 1 x = Add()([x, residual]) model_c1a = Model(inputs=img_input, outputs=x) total_params, trainable_params, non_trainable_params = count_model_params(model_c1a) print(f"After adding Connection 1 Parameters: Total={total_params}, Trainable={trainable_params}, Non-trainable={non_trainable_params}")
# Block4 - 128 channels residual = SeparableConv2D(128, (3, 3), strides=(1, 1),padding='same', use_bias=False)(x) residual = AveragePooling2D((3, 3), strides=(2, 2), padding='same')(residual) residual = SeparableConv2D(256, (1, 1), strides=(1, 1), padding='same', use_bias=False)(residual) residual = BatchNormalization()(residual) # residual = custom_attention(residual) # residual = Activation('relu')(residual)
x = SeparableConv2D(64, (5, 5), padding='same', kernel_regularizer=regularization, use_bias=False)(x) x = BatchNormalization()(x) x = Activation('relu')(x) x = SeparableConv2D(128, (3, 3), padding='same', kernel_regularizer=regularization, use_bias=False)(x) # x = BatchNormalization()(x) # x = Activation('relu')(x) x = AveragePooling2D((3, 3), padding='same', strides=(2, 2))(x)# x = inception_module(x, 128, 32, 128, 32, 32, 32)# x = se_block(x)# x = cbam_block(x)# x = self_attention_block(x) # block-4 shape # print("block-4:", x.shape) x = custom_attention(x) # block-4 shape # print("block-4:", x.shape) x = Dropout(0.5)(x) model_block4 = Model(inputs=img_input, outputs=x) total_params, trainable_params, non_trainable_params = count_model_params(model_block4) print(f"Block 4 Parameters: Total={total_params}, Trainable={trainable_params}, Non-trainable={non_trainable_params}") # Final block residual2 = SeparableConv2D(128, (3, 3), strides=(1, 1), padding='same', use_bias=False)(x) # residual2 = BatchNormalization()(residual2) # residual2 = Activation('relu')(residual2) residual2 = SeparableConv2D(256, (1, 1), strides=(1, 1), padding='same', use_bias=False)(residual2) residual2 = BatchNormalization()(residual2) # residual2 = Activation('relu')(residual2) # residual = cbam_block(residual) # block-5 shape # print("block-5 before res:", residual.shape) # residual = custom_attention(residual) # block-5 shape # print("block-5 after res:", residual.shape)
model_c2 = Model(inputs=img_input, outputs=x) total_params, trainable_params, non_trainable_params = count_model_params(model_c2) print(f"Connection 2 Parameters: Total={total_params}, Trainable={trainable_params}, Non-trainable={non_trainable_params}")
x = SeparableConv2D(256, (3, 3), padding='same', kernel_regularizer=regularization, use_bias=False)(x) x = BatchNormalization()(x) x = Activation('relu')(x) # 4th Inception and CBAM# x = inception_module(x, 256, 64, 256, 64, 64, 64)# x = se_block(x)# x = cbam_block(x)# x = self_attention_block(x) # block-5 shape # print("block-5:", x.shape) x = custom_attention(x) # block-5 shape # print("block-5:", x.shape)
#Connection 2 x = Add()([x, residual]) #Connection 3 x = Add()([x, residual2]) model_c2a = Model(inputs=img_input, outputs=x) total_params, trainable_params, non_trainable_params = count_model_params(model_c2a) print(f"After Adding Connection 2 Parameters: Total={total_params}, Trainable={trainable_params}, Non-trainable={non_trainable_params}")
x = SeparableConv2D(256, (3, 3), padding='same', kernel_regularizer=regularization, use_bias=False)(x) x = BatchNormalization()(x) x = Activation('relu')(x) model_block5 = Model(inputs=img_input, outputs=x) total_params, trainable_params, non_trainable_params = count_model_params(model_block5) print(f"Block 5 Parameters: Total={total_params}, Trainable={trainable_params}, Non-trainable={non_trainable_params}") # #condition 1# x = SeparableConv2D(128, (1, 1), padding='same', kernel_regularizer=regularization, use_bias=False)(x)# x = BatchNormalization()(x)# x = Activation('relu')(x)# x = SeparableConv2D(2, (1, 1), padding='same', kernel_regularizer=regularization, use_bias=False)(x)# x = BatchNormalization()(x)# x = Activation('relu')(x) # flattened = Flatten()(x)
# # # Fully connected layer with softmax activation# output = Dense(2, activation='softmax')(flattened) #condition 2 x = SeparableConv2D(2, (1, 1), padding='same', kernel_regularizer=regularization, use_bias=False)(x) x = BatchNormalization()(x) x = Activation('relu')(x) x = GlobalAveragePooling2D()(x) output = Dense(num_classes, activation='softmax', name='predictions')(x)
model = Model(img_input, output) return model
# def combine_4SC_2_1_V3(input_shape, num_classes, l2_regularization=0.01):# regularization = l2(l2_regularization)
# # Block1 - 16 channels# img_input = Input(input_shape)# x = Conv2D(16, (7, 7), strides=(1, 1), padding='same', kernel_regularizer=regularization, use_bias=False)(img_input)# x = BatchNormalization()(x)# x = Activation('relu')(x)# x = Conv2D(16, (7, 7), strides=(1, 1), padding='same', kernel_regularizer=regularization, use_bias=False)(x)# x = BatchNormalization()(x)# x = Activation('relu')(x)# x = AveragePooling2D((3, 3), strides=(2, 2))(x)# x = se_block(x)# # x = cbam_block(x)# # x = self_attention_block(x)# x = Dropout(0.5)(x)
# # Block2 - 32 channels # x = Conv2D(32, (3, 3), padding='same', kernel_regularizer=regularization, use_bias=False)(x)# x = BatchNormalization()(x)# x = Activation('relu')(x)# x = SeparableConv2D(32, (3, 3), padding='same', kernel_regularizer=regularization, use_bias=False)(x)# x = BatchNormalization()(x)# x = AveragePooling2D((3, 3), strides=(2, 2), padding='same')(x)# x = inception_module(x, 32, 24, 32, 24, 32, 32)# x = se_block(x)# # x = cbam_block(x)# # x = self_attention_block(x) # x = Dropout(0.5)(x)
# # Module 3 - 64 channels# residual = SeparableConv2D(32, (3, 3), strides=(1, 1),padding='same', use_bias=False)(x)# residual = AveragePooling2D((3, 3), strides=(2, 2), padding='same')(residual)# residual = SeparableConv2D(64, (1, 1), strides=(1, 1), padding='same', use_bias=False)(residual)# residual = BatchNormalization()(residual) # # 2nd Inception and CBAM # x = Conv2D(64, (3, 3), padding='same', kernel_regularizer=regularization, use_bias=False)(x)# x = BatchNormalization()(x)# x = Activation('relu')(x)# x = SeparableConv2D(64, (3, 3), padding='same', kernel_regularizer=regularization, use_bias=False)(x)# x = BatchNormalization()(x)# x = AveragePooling2D((3, 3),padding='same', strides=(2, 2))(x)# x = inception_module(x, 32, 16, 32, 16, 16, 16)# x = se_block(x)# # x = cbam_block(x)# # x = self_attention_block(x)# x = Dropout(0.5)(x) # #Connection 1# x = Add()([x, residual])
# # Module 4 - 128 channels # x = Conv2D(128, (3, 3), padding='same', kernel_regularizer=regularization, use_bias=False)(x)# x = BatchNormalization()(x)# x = Activation('relu')(x)# x = SeparableConv2D(128, (3, 3), padding='same', kernel_regularizer=regularization, use_bias=False)(x)# x = BatchNormalization()(x)# x = AveragePooling2D((3, 3), padding='same', strides=(2, 2))(x)# x = inception_module(x, 128, 32, 128, 32, 32, 32)# x = se_block(x)# # x = cbam_block(x)# # x = self_attention_block(x) # x = Dropout(0.5)(x)
# # Final block# residual = Conv2D(128, (3, 3), strides=(1, 1), padding='same', use_bias=False)(x)# residual = SeparableConv2D(256, (1, 1), strides=(1, 1), padding='same', use_bias=False)(residual)# residual = BatchNormalization()(residual)
# x = SeparableConv2D(256, (3, 3), padding='same', kernel_regularizer=regularization, use_bias=False)(x)# x = BatchNormalization()(x)# x = Activation('relu')(x) # # 4th Inception and CBAM# x = inception_module(x, 256, 64, 256, 64, 64, 64)# x = se_block(x)# # x = cbam_block(x)# # x = self_attention_block(x)
# x = SeparableConv2D(256, (3, 3), padding='same', kernel_regularizer=regularization, use_bias=False)(x)# x = BatchNormalization()(x)# x = Activation('relu')(x) # x = Add()([x, residual]) # # #condition 1# x = SeparableConv2D(128, (1, 1), padding='same', kernel_regularizer=regularization, use_bias=False)(x)# x = BatchNormalization()(x)# x = Activation('relu')(x)# x = SeparableConv2D(2, (1, 1), padding='same', kernel_regularizer=regularization, use_bias=False)(x)# x = BatchNormalization()(x)# x = Activation('relu')(x) # flattened = Flatten()(x)
# # Fully connected layer with softmax activation# output = Dense(2, activation='softmax')(flattened) # # #condition 2# # x = SeparableConv2D(2, (1, 1), padding='same', kernel_regularizer=regularization, use_bias=False)(x) # # x = GlobalAveragePooling2D()(x) # # output = Dense(num_classes, activation='softmax', name='predictions')(x)
# model = Model(img_input, output)# return model
#SqueezeNetdef fire_module(input_fire, s1, e1, e3, weight_decay_l2, fireID): ''' A wrapper to build fire module # Arguments input_fire: input activations s1: number of filters for squeeze step e1: number of filters for 1x1 expansion step e3: number of filters for 3x3 expansion step weight_decay_l2: weight decay for conv layers fireID: ID for the module # Return Output activations ''' # Squezee step output_squeeze = Convolution2D( s1, (1, 1), activation='relu', kernel_initializer='glorot_uniform', kernel_regularizer=regularizers.l2(weight_decay_l2), padding='same', name='fire' + str(fireID) + '_squeeze', data_format="channels_last")(input_fire) # Expansion steps output_expand1 = Convolution2D( e1, (1, 1), activation='relu', kernel_initializer='glorot_uniform', kernel_regularizer=regularizers.l2(weight_decay_l2), padding='same', name='fire' + str(fireID) + '_expand1', data_format="channels_last")(output_squeeze) output_expand2 = Convolution2D( e3, (3, 3), activation='relu', kernel_initializer='glorot_uniform', kernel_regularizer=regularizers.l2(weight_decay_l2), padding='same', name='fire' + str(fireID) + '_expand2', data_format="channels_last")(output_squeeze) # Merge expanded activations output_fire = Concatenate(axis=3)([output_expand1, output_expand2]) return output_fire
def SqueezeNet(input_shape, num_classes, weight_decay_l2=0.0001): ''' A wrapper to build SqueezeNet Model # Arguments num_classes: number of classes defined for classification task weight_decay_l2: weight decay for conv layers inputs: input image dimensions # Return A SqueezeNet Keras Model ''' input_img = Input(shape=input_shape) conv1 = Convolution2D( 32, (7, 7), activation='relu', kernel_initializer='glorot_uniform', strides=(2, 2), padding='same', name='conv1', data_format="channels_last")(input_img) maxpool1 = MaxPooling2D( pool_size=(2, 2), strides=(2, 2), name='maxpool1', data_format="channels_last")(conv1) fire2 = fire_module(maxpool1, 8, 16, 16, weight_decay_l2, 2) fire3 = fire_module(fire2, 8, 16, 16, weight_decay_l2, 3) fire4 = fire_module(fire3, 16, 32, 32, weight_decay_l2, 4) maxpool4 = MaxPooling2D( pool_size=(2, 2), strides=(2, 2), name='maxpool4', data_format="channels_last")(fire4) fire5 = fire_module(maxpool4, 16, 32, 32, weight_decay_l2, 5) fire6 = fire_module(fire5, 32, 64, 64, weight_decay_l2, 6) fire7 = fire_module(fire6, 32, 64, 64, weight_decay_l2, 7) fire8 = fire_module(fire7, 64, 128, 128, weight_decay_l2, 8) maxpool8 = MaxPooling2D( pool_size=(2, 2), strides=(2, 2), name='maxpool8', data_format="channels_last")(fire8) fire9 = fire_module(maxpool8, 64, 128, 128, weight_decay_l2, 9) fire9_dropout = Dropout(0.5, name='fire9_dropout')(fire9) conv10 = Convolution2D( num_classes, (1, 1), activation='relu', kernel_initializer='glorot_uniform', padding='valid', name='conv10', data_format="channels_last")(fire9_dropout)
global_avgpool10 = GlobalAveragePooling2D(data_format='channels_last')(conv10) softmax = Activation("softmax", name='softmax')(global_avgpool10) return Model(inputs=input_img, outputs=softmax)
# MobileNet V2def MobileNetV2_MODEL(input_shape, num_classes): # Remove fully connected layer and replace # with softmax for classifying 10 classes model_MobileNet_1 = MobileNetV2(weights="imagenet", include_top=False)
# Freeze all layers of the pre-trained model for layer in model_MobileNet_1.layers: layer.trainable = False x = model_MobileNet_1.output x = GlobalAveragePooling2D()(x) x = Dense(1024, activation='relu')(x) predictions = Dense(num_classes, activation = 'softmax')(x)
model = Model(input = model_MobileNet_1.input, output = predictions) return model
# NASNetMobiledef NASNetMobile_MODEL(input_shape, num_classes): # Remove fully connected layer and replace # with softmax for classifying 10 classes model_NASNetMobile_1 = NASNetMobile(weights="imagenet", include_top=False)
# Freeze all layers of the pre-trained model for layer in model_NASNetMobile_1.layers: layer.trainable = False x = model_NASNetMobile_1.output x = GlobalAveragePooling2D()(x) x = Dense(1024, activation='relu')(x) predictions = Dense(num_classes, activation = 'softmax')(x)
model = Model(input = model_NASNetMobile_1.input, output = predictions) return model# DenseNet121def DenseNet121_MODEL(input_shape, num_classes): # Remove fully connected layer and replace # with softmax for classifying 10 classes model_DenseNet121_1 = DenseNet121(weights="imagenet", include_top=False)
# Freeze all layers of the pre-trained model for layer in model_DenseNet121_1.layers: layer.trainable = False x = model_DenseNet121_1.output x = GlobalAveragePooling2D()(x) x = Dense(1024, activation='relu')(x) predictions = Dense(num_classes, activation = 'softmax')(x)
model = Model(input = model_DenseNet121_1.input, output = predictions) return model# InceptionV3def InceptionV3_MODEL(input_shape, num_classes): # Remove fully connected layer and replace # with softmax for classifying 10 classes model_InceptionV3_1 = InceptionV3(weights="imagenet", include_top=False)
# Freeze all layers of the pre-trained model for layer in model_InceptionV3_1.layers: layer.trainable = False x = model_InceptionV3_1.output x = GlobalAveragePooling2D()(x) x = Dense(1024, activation='relu')(x) predictions = Dense(num_classes, activation = 'softmax')(x)
model = Model(input = model_InceptionV3_1.input, output = predictions) return model
#InceptionV3# Model 16 def VGG13_LRELU_2(input_shape, num_classes): #model = Sequential() img_input = Input(input_shape)
x = Conv2D(64, (3, 3), padding='same',kernel_regularizer=regularizers.l2(0.01))(img_input) x = LeakyReLU(alpha=0.01)(x) x = BatchNormalization()(x) x = Dropout(0.4)(x) # layer2 48*48*64 x = Conv2D(64, (3, 3), padding='same',kernel_regularizer=regularizers.l2(0.01))(x) x = LeakyReLU(alpha=0.01)(x) x = BatchNormalization()(x) x = MaxPooling2D(pool_size=(2, 2))(x) x = Dropout(0.4)(x)
# layer3 24*24*64 x = Conv2D(128, (3, 3), padding='same',kernel_regularizer=regularizers.l2(0.01))(x) x = LeakyReLU(alpha=0.01)(x) x = BatchNormalization()(x) x = Dropout(0.4)(x) # layer4 24*24*128 x = Conv2D(128, (3, 3), padding='same',kernel_regularizer=regularizers.l2(0.01))(x) x = LeakyReLU(alpha=0.01)(x) x = BatchNormalization()(x) x = MaxPooling2D(pool_size=(2, 2))(x) x = Dropout(0.4)(x)
# layer5 12*12*128 x = Conv2D(256, (3, 3), padding='same',kernel_regularizer=regularizers.l2(0.01))(x) x = LeakyReLU(alpha=0.01)(x) x = BatchNormalization()(x) x = Dropout(0.4)(x) # layer6 12*12*256 x = Conv2D(256, (3, 3), padding='same',kernel_regularizer=regularizers.l2(0.01))(x) x = LeakyReLU(alpha=0.01)(x) x = BatchNormalization()(x) # layer7 12*12*256 x = MaxPooling2D(pool_size=(2, 2))(x) x = Dropout(0.4)(x)
# layer8 6*6*256 x = Conv2D(512, (3, 3), padding='same',kernel_regularizer=regularizers.l2(0.01))(x) x = LeakyReLU(alpha=0.01)(x) x = BatchNormalization()(x) x = Dropout(0.4)(x) # layer9 6*6*512 x = Conv2D(512, (3, 3), padding='same',kernel_regularizer=regularizers.l2(0.01))(x) x = LeakyReLU(alpha=0.01)(x) x = BatchNormalization()(x) # layer10 6*6*512 x = MaxPooling2D(pool_size=(2, 2))(x) x = Dropout(0.4)(x)
# layer11 3*3*512 #x = Conv2D(512, (3, 3), padding='same',kernel_regularizer=regularizers.l2(0.01))(x) #x = LeakyReLU(alpha=0.01)(x) #x = BatchNormalization()(x) #x = Dropout(0.4)(x) # layer12 3*3*512 #x = Conv2D(512, (3, 3), padding='same',kernel_regularizer=regularizers.l2(0.01))(x) #x = LeakyReLU(alpha=0.01)(x) #x = BatchNormalization()(x) # layer13 3*3*512 #x = MaxPooling2D(pool_size=(2, 2))(x) #x = Dropout(0.4)(x)
# layer14 1*1*512 x = GlobalAveragePooling2D()(x) #x = Flatten()(x) #x = Dropout(0.4)(x) #x = Dense(128)(x) x = Dense(1024)(x) x = LeakyReLU(alpha=0.01)(x) x = Dropout(0.5)(x)
x = Dense(num_classes, activation='softmax')(x)
model = Model(img_input, x) return model
# Xceptiondef Xception_MODEL(input_shape, num_classes): # Remove fully connected layer and replace # with softmax for classifying 10 classes model_Xception_1 = VGG16(weights="imagenet", include_top=False)
# Freeze all layers of the pre-trained model for layer in model_Xception_1.layers: layer.trainable = False x = model_Xception_1.output x = GlobalAveragePooling2D()(x) x = Dense(1024, activation='relu')(x) predictions = Dense(num_classes, activation = 'softmax')(x)
model = Model(input = model_Xception_1.input, output = predictions) return model
# VGG19def VGG19_MODEL(input_shape, num_classes): # Remove fully connected layer and replace # with softmax for classifying 10 classes model_vgg19_1 = VGG19(weights="imagenet", include_top=False) # Freeze all layers of the pre-trained model for layer in model_vgg19_1.layers: layer.trainable = False x = model_vgg19_1.output x = GlobalAveragePooling2D()(x) x = Dense(1024, activation='relu')(x) predictions = Dense(num_classes, activation = 'softmax')(x)
model = Model(input = model_vgg19_1.input, output = predictions) return model# MobileNetdef MobileNet_MODEL(input_shape, num_classes): # Remove fully connected layer and replace # with softmax for classifying 10 classes model_MobileNet_1 = MobileNet(weights="imagenet", include_top=False)
# Freeze all layers of the pre-trained model for layer in model_MobileNet_1.layers: layer.trainable = False x = model_MobileNet_1.output x = GlobalAveragePooling2D()(x) x = Dense(1024, activation='relu')(x) predictions = Dense(num_classes, activation = 'softmax')(x)
model = Model(input = model_MobileNet_1.input, output = predictions) return model# VGG16def VGG16_MODEL(input_shape, num_classes): # Remove fully connected layer and replace # with softmax for classifying 10 classes model_vgg16_1 = VGG16(weights="imagenet", include_top=False)
# Freeze all layers of the pre-trained model for layer in model_vgg16_1.layers: layer.trainable = False x = model_vgg16_1.output x = GlobalAveragePooling2D()(x) x = Dense(1024, activation='relu')(x) predictions = Dense(num_classes, activation = 'softmax')(x)
model = Model(input = model_vgg16_1.input, output = predictions) return model
# Lenetdef Lenet(input_shape, num_classes): # initialize the model model = Sequential() #Input(input_shape)
# if we are using "channel_first", update the input shape #if K.image_data_format() == "channel_first": # inputShape = (depth, height, width)
# first set of CONV => RELU => POOL layers model.add(Conv2D(20, (5, 5), padding = "same", input_shape=input_shape)) model.add(Activation("relu")) model.add(MaxPooling2D(pool_size = (2, 2), strides = (2, 2)))
# second set of CONV => RELU => POOL layers model.add(Conv2D(50, (5, 5), padding = "same")) model.add(Activation("relu")) model.add(MaxPooling2D(pool_size = (2, 2), strides = (2, 2)))
# first set of FC => RELU layers model.add(Flatten()) model.add(Dense(500)) model.add(Activation("relu"))
# softmax classififer model.add(Dense(num_classes)) model.add(Activation("softmax"))
# return the constructed network architecture return model
123456789101112131415161718192021222324252627282930313233343536373839import pandas as pdimport matplotlib.pyplot as plt
name_file = "optimized_model"# Load the CSV filecsv_file = 'ProposedNetwork_StratifiedKFold_Final_fold_5_training.csv' # Replace with your actual CSV file pathdata = pd.read_csv(csv_file)
# Extract the required columnsepochs = range(1, len(data) + 1) # Epoch numberstrain_acc = data['accuracy'] # Training accuracyval_acc = data['val_accuracy'] # Validation accuracytrain_loss = data['loss'] # Training lossval_loss = data['val_loss'] # Validation loss
plt.figure(figsize=(15, 10)) plt.plot(epochs,train_loss,'r', label='Train_loss')plt.plot(epochs,val_loss,'b', label='Val_loss')plt.title('Train Loss vs Validation Loss', fontsize=24)plt.xlabel('Epochs', fontsize=20)plt.ylabel('Loss', fontsize=20)plt.legend(fontsize=18)plt.tick_params(axis='both', which='major', labelsize=16) plt.savefig("./Plot/" +name_file+'_Loss.png',dpi=300)#plt.figure()plt.show()
plt.figure(figsize=(15, 10)) plt.plot(epochs,train_acc,'r', label='Train_acc')plt.plot(epochs,val_acc,'b', label='Val_acc')plt.title('Train Accuracy vs Validation Accuracy', fontsize=24)plt.xlabel('Epochs', fontsize=20)plt.ylabel('Accuracy', fontsize=20)plt.legend(fontsize=18)plt.tick_params(axis='both', which='major', labelsize=16) plt.savefig("./Plot/" +name_file+'_Acc.png',dpi=300)#plt.figure()plt.show()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154import osimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport itertoolsimport tensorflow as tffrom imutils import pathsfrom sklearn.model_selection import StratifiedKFoldfrom sklearn.metrics import confusion_matrixfrom tensorflow.keras.models import load_modelfrom tensorflow.keras.preprocessing.image import ImageDataGenerator
# ==============================================================================# 1. CONFIGURATION# ==============================================================================# --- !!! IMPORTANT: SET THE FOLD YOU WANT TO EVALUATE !!! ---FOLD_TO_EVALUATE = 5 # Change this to 1, 2, 3, 4, or 5
# --- Paths and Parameters (should match your training script) ---MODEL_NAME = "ProposedNetwork_StratifiedKFold_Final"DATASET_PATH = './Dataset/FireNet_Augmented/'MODEL_DIR = "./Model"PLOT_DIR = "./Plot"
N_SPLITS = 5NORM_SIZE = 224BATCH_SIZE = 32
# Construct the model path based on the fold numbermodel_path = f"{MODEL_DIR}/{MODEL_NAME}_fold_{FOLD_TO_EVALUATE}.hdf5"os.makedirs(PLOT_DIR, exist_ok=True)
# ==============================================================================# 2. LOAD DATA AND RE-CREATE THE EXACT K-FOLD SPLIT# ==============================================================================print(f"[INFO] Evaluating model for Fold {FOLD_TO_EVALUATE} from path: {model_path}")
# Load all image filepaths and labels into a DataFrameprint("[INFO] Loading image paths and creating DataFrame...")imagePaths = sorted(list(paths.list_images(DATASET_PATH)))data = [(path, os.path.basename(os.path.dirname(path))) for path in imagePaths]df = pd.DataFrame(data, columns=['filepath', 'class']).sample(frac=1, random_state=42).reset_index(drop=True)
# Initialize StratifiedKFold with the SAME parameters as in training to get the same splitsskf = StratifiedKFold(n_splits=N_SPLITS, shuffle=True, random_state=42)
# Find the specific validation set indices for the fold we want to evaluateval_indices = Nonefor i, (train_index, val_index) in enumerate(skf.split(df['filepath'], df['class'])): if i + 1 == FOLD_TO_EVALUATE: val_indices = val_index break
if val_indices is None: raise ValueError(f"Could not find indices for Fold {FOLD_TO_EVALUATE}. Check N_SPLITS.")
# Create the validation DataFrame for the specified foldvalidation_df = df.iloc[val_indices]print(f"[INFO] Successfully isolated the validation dataset for Fold {FOLD_TO_EVALUATE} ({len(validation_df)} images).")
# ==============================================================================# 3. CREATE GENERATOR, LOAD MODEL, AND PREDICT# ==============================================================================# Create a data generator for ONLY the validation data of the chosen fold# IMPORTANT: We only rescale the data. No augmentation for evaluation.val_datagen = ImageDataGenerator(rescale=1.0 / 255)
validation_generator = val_datagen.flow_from_dataframe( dataframe=validation_df, x_col='filepath', y_col='class', target_size=(NORM_SIZE, NORM_SIZE), batch_size=BATCH_SIZE, class_mode="categorical", shuffle=False # CRITICAL: Do not shuffle for evaluation)
# Load the saved model for the specified foldprint("[INFO] Loading model...")model = load_model(model_path)
# Predict on the correct validation dataprint("[INFO] Generating predictions...")y_prob = model.predict(validation_generator, verbose=1)y_pred = y_prob.argmax(axis=-1) # Predicted class indicesy_true = validation_generator.classes # True class labels
# ==============================================================================# 4. GENERATE AND PLOT THE CONFUSION MATRIX# ==============================================================================# Generate Confusion Matrixcm = confusion_matrix(y_true, y_pred)labels = ['NoFire', 'Fire']
def plot_confusion_matrix_with_counts(cm, classes, normalize=False, title='Normalized Confusion Matrix with Counts', cmap=plt.cm.Blues, figsize=(12, 12), font_size=16, value_font_size=14, save_path=None): """ Function to plot a confusion matrix with normalized and absolute values. """ if normalize: cm_normalized = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] else: cm_normalized = cm
fig, ax = plt.subplots(figsize=figsize) im = ax.imshow(cm_normalized, interpolation='nearest', cmap=cmap, aspect='auto') # Align color bar cbar = fig.colorbar(im, ax=ax) # Add color bar cbar.ax.tick_params(labelsize=font_size - 2) # Adjust color bar font size ax.set_title(title, fontsize=font_size)
# Set tick marks and labels tick_marks = np.arange(len(classes)) ax.set_xticks(tick_marks) ax.set_xticklabels(classes, rotation=45, ha='right', fontsize=font_size - 2) ax.set_yticks(tick_marks) ax.set_yticklabels(classes, fontsize=font_size - 2)
# Add text annotations (normalized and absolute counts) fmt = '.2f' if normalize else 'd' thresh = cm_normalized.max() / 2.0 for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): normalized_value = f"{cm_normalized[i, j]:.2f}" absolute_value = f"{cm[i, j]} of {int(cm[i, :].sum())} images" text_color = "white" if cm_normalized[i, j] > thresh else "black" ax.text(j, i, f"{normalized_value}\n{absolute_value}", ha="center", va="center", color=text_color, fontsize=value_font_size)
ax.set_ylabel('True label', fontsize=font_size) ax.set_xlabel('Predicted label', fontsize=font_size) fig.tight_layout()
if save_path: plt.savefig(save_path, dpi=300, bbox_inches='tight') print(f"Confusion matrix saved to {save_path}") plt.show()
# Call the function to plotplot_confusion_matrix_with_counts( cm, classes=labels, normalize=True, title='Normalized Confusion Matrix with Counts', cmap=plt.cm.Blues, figsize=(12, 12), # Adjust size as needed font_size=18, value_font_size=22, save_path='./Plot/confusion_matrix_custom.png')123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166import osimport pandas as pdimport numpy as npimport matplotlib# Use a backend that doesn't require a GUI, which is more reliablematplotlib.use('Agg')import matplotlib.pyplot as pltimport cv2import tensorflow as tffrom imutils import pathsfrom sklearn.model_selection import StratifiedKFoldfrom tensorflow.keras.models import load_modelfrom tensorflow.keras.preprocessing.image import img_to_array, load_img
# ==============================================================================# 1. CONFIGURATION - !!! ONLY EDIT THIS SECTION !!!# ==============================================================================FOLD_TO_USE = 5NUM_IMAGES = 8MODEL_NAME = "ProposedNetwork_StratifiedKFold_Final"DATASET_PATH = './Dataset/ThermalFire/'MODEL_DIR = "./Model"PLOT_DIR = "./Plot"N_SPLITS = 5NORM_SIZE = 224BATCH_SIZE = 1
# ==============================================================================# DO NOT EDIT BELOW THIS LINE# ==============================================================================
print("[INFO] Starting Grad-CAM script...")os.makedirs(PLOT_DIR, exist_ok=True)model_path = "{}/{}_fold_{}.hdf5".format(MODEL_DIR, MODEL_NAME, FOLD_TO_USE)
if not os.path.exists(model_path): raise FileNotFoundError("Model file not found at: {}\nPlease ensure the model for Fold {} exists.".format(model_path, FOLD_TO_USE))
# ==============================================================================# 2. HELPER FUNCTIONS# ==============================================================================def getLabel(class_id): """Returns the string label for a given class ID.""" return ['NoFire', 'Fire'][class_id]
def get_gradcam_heatmap(model, img_array, last_conv_layer_name, pred_index=None): grad_model = tf.keras.models.Model( [model.inputs], [model.get_layer(last_conv_layer_name).output, model.output] ) with tf.GradientTape() as tape: last_conv_layer_output, preds = grad_model(img_array) if pred_index is None: pred_index = tf.argmax(preds[0]) class_channel = preds[:, pred_index] grads = tape.gradient(class_channel, last_conv_layer_output) if grads is None: print("[ERROR] Gradient calculation failed. The gradient is None.") return None
pooled_grads = tf.reduce_mean(grads, axis=(0, 1, 2)) last_conv_layer_output = last_conv_layer_output[0] heatmap = last_conv_layer_output @ pooled_grads[..., tf.newaxis] heatmap = tf.squeeze(heatmap) heatmap = tf.maximum(heatmap, 0) / (tf.math.reduce_max(heatmap) + tf.keras.backend.epsilon()) return heatmap.numpy()
def superimpose_gradcam(img, heatmap, alpha=0.4): heatmap = np.uint8(255 * heatmap) jet = plt.get_cmap("jet") jet_colors = jet(np.arange(256))[:, :3] jet_heatmap = jet_colors[heatmap] jet_heatmap = tf.keras.preprocessing.image.array_to_img(jet_heatmap) jet_heatmap = jet_heatmap.resize((img.shape[1], img.shape[0])) jet_heatmap = tf.keras.preprocessing.image.img_to_array(jet_heatmap) superimposed_img = jet_heatmap * alpha + img superimposed_img = tf.keras.preprocessing.image.array_to_img(superimposed_img) return superimposed_img
# ==============================================================================# 3. LOAD DATA AND MODEL# ==============================================================================print("[INFO] Loading model from: {}".format(model_path))model = load_model(model_path)model.layers[-1].activation = Noneprint("[DEBUG] Model loaded successfully.")
last_conv_layer_name = ""for layer in reversed(model.layers): if isinstance(layer, (tf.keras.layers.Conv2D, tf.keras.layers.SeparableConv2D)): last_conv_layer_name = layer.name breakprint("[DEBUG] Automatically found last convolutional layer: '{}'".format(last_conv_layer_name))
print("[DEBUG] Loading and splitting data manifest...")imagePaths = sorted(list(paths.list_images(DATASET_PATH)))data = [(path, os.path.basename(os.path.dirname(path))) for path in imagePaths]df = pd.DataFrame(data, columns=['filepath', 'class'])df = df.sample(frac=1, random_state=42).reset_index(drop=True) # Shuffle is important for samplingskf = StratifiedKFold(n_splits=N_SPLITS, shuffle=True, random_state=42)all_splits = list(skf.split(df['filepath'], df['class']))_, val_index = all_splits[FOLD_TO_USE - 1]val_df = df.iloc[val_index]
fire_df = val_df[val_df['class'] == '1'].sample(NUM_IMAGES // 2, random_state=42)nofire_df = val_df[val_df['class'] == '0'].sample(NUM_IMAGES // 2, random_state=42)sample_df = pd.concat([fire_df, nofire_df])
# ===================================================================# === THE CRITICAL FIX IS APPLIED HERE ===# We rename the 'class' column because 'class' is a reserved keyword in Python# and cannot be used as an attribute (e.g., row.class).sample_df = sample_df.rename(columns={'class': 'class_label'})# ===================================================================
if sample_df.empty: raise ValueError("[ERROR] The sample DataFrame is empty. Could not find images to process.")else: print("[DEBUG] Selected {} images for visualization.".format(len(sample_df)))
# ==============================================================================# 4. GENERATE AND SAVE THE VISUALIZATION# ==============================================================================print("[INFO] Starting image processing loop to generate Grad-CAMs...")fig, axes = plt.subplots(NUM_IMAGES, 2, figsize=(8, NUM_IMAGES * 4))fig.suptitle('Grad-CAM Explainability Analysis', fontsize=20)
for i, row in enumerate(sample_df.itertuples()): print("[DEBUG] Processing image {} of {}: {}".format(i + 1, len(sample_df), row.filepath)) img = load_img(row.filepath, target_size=(NORM_SIZE, NORM_SIZE)) img_array = img_to_array(img) img_array_scaled = np.expand_dims(img_array / 255.0, axis=0)
preds = model.predict(img_array_scaled) pred_class_index = np.argmax(preds[0]) pred_class_name = "Fire" if pred_class_index == 1 else "NoFire"
heatmap = get_gradcam_heatmap(model, img_array_scaled, last_conv_layer_name, pred_index=pred_class_index) if heatmap is None: print("[FATAL] Could not generate heatmap for {}. Skipping this image.".format(row.filepath)) continue
gradcam_img = superimpose_gradcam(img_array, heatmap)
# Plot original image, now using the safe attribute name 'class_label' axes[i, 0].imshow(img) axes[i, 0].set_title("Original (True: {})".format(getLabel(int(row.class_label)))) axes[i, 0].axis('off')
# Plot Grad-CAM image axes[i, 1].imshow(gradcam_img) axes[i, 1].set_title("Grad-CAM (Predicted: {})".format(pred_class_name)) axes[i, 1].axis('off')
print("[DEBUG] Image processing loop finished.")plt.tight_layout(rect=[0, 0, 1, 0.98])save_path = "{}/final_report_gradcam.png".format(PLOT_DIR)
print("[INFO] Saving final figure to {}...".format(save_path))plt.savefig(save_path, dpi=300)# plt.show() is commented out to ensure it saves even on systems without a GUIprint("[INFO] Figure saved successfully.")
print("\n[INFO] Grad-CAM script finished.")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181import osimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport itertoolsimport cv2import tensorflow as tffrom imutils import pathsfrom sklearn.model_selection import StratifiedKFoldfrom sklearn.metrics import confusion_matrix, classification_report, matthews_corrcoeffrom tensorflow.keras.models import load_modelfrom tensorflow.keras.preprocessing.image import ImageDataGenerator
# ==============================================================================# 1. CONFIGURATION - !!! ONLY EDIT THIS SECTION !!!# ==============================================================================# --- Choose which fold's visualizations to generate as a representative example ---FOLD_FOR_VISUALIZATION = 5 # <--- You can change this to 1, 2, 3, 4, or 5
# --- Paths and Parameters (MUST MATCH YOUR TRAINING SCRIPT) ---MODEL_NAME = "ProposedNetwork_StratifiedKFold_Final"DATASET_PATH = './Dataset/FireNet_Augmented/'MODEL_DIR = "./Model"PLOT_DIR = "./Plot"
N_SPLITS = 5NORM_SIZE = 224BATCH_SIZE = 32
# ==============================================================================# DO NOT EDIT BELOW THIS LINE# ==============================================================================
# --- Setup and Verification ---os.makedirs(PLOT_DIR, exist_ok=True)print("[INFO] Starting the comprehensive report generation process...")
# ==============================================================================# 2. HELPER FUNCTIONS FOR VISUALIZATION# ==============================================================================def getLabel(class_id): """Returns the string label for a given class ID.""" return ['NoFire', 'Fire'][class_id]
def plot_confusion_matrix_with_counts(cm, classes, title, save_path): """Plots a detailed confusion matrix with both normalized values and absolute counts.""" cm_counts = cm.astype(int) cm_sum = cm_counts.sum(axis=1)[:, np.newaxis] cm_normalized = np.divide(cm_counts.astype('float'), cm_sum, out=np.zeros_like(cm_counts, dtype=float), where=(cm_sum!=0)) fig, ax = plt.subplots(figsize=(10, 10)) im = ax.imshow(cm_normalized, interpolation='nearest', cmap=plt.cm.Blues, vmin=0, vmax=1) ax.figure.colorbar(im, ax=ax, shrink=0.8) ax.set(xticks=np.arange(cm.shape[1]), yticks=np.arange(cm.shape[0]), xticklabels=classes, yticklabels=classes, title=title, ylabel='True label', xlabel='Predicted label') plt.setp(ax.get_xticklabels(), rotation=45, ha="right", rotation_mode="anchor") thresh = cm_normalized.max() / 2. for i in range(cm.shape[0]): for j in range(cm.shape[1]): ax.text(j, i, "{:.2f}\n({} images)".format(cm_normalized[i, j], cm_counts[i, j]), ha="center", va="center", color="white" if cm_normalized[i, j] > thresh else "black", fontsize=14) fig.tight_layout() plt.savefig(save_path, dpi=300) plt.show()
# ==============================================================================# 3. LOAD DATA AND RE-CREATE K-FOLD SPLITS# ==============================================================================print("[INFO] Loading image paths and recreating K-Fold splits...")imagePaths = sorted(list(paths.list_images(DATASET_PATH)))data = [(path, os.path.basename(os.path.dirname(path))) for path in imagePaths]df = pd.DataFrame(data, columns=['filepath', 'class']).sample(frac=1, random_state=42).reset_index(drop=True)
skf = StratifiedKFold(n_splits=N_SPLITS, shuffle=True, random_state=42)all_splits = list(skf.split(df['filepath'], df['class']))
# ==============================================================================# 4. EVALUATE ALL FOLDS TO GET AGGREGATED METRICS# ==============================================================================all_scores = { 'accuracy': [], 'precision_macro': [], 'recall_macro': [], 'f1_macro': [], 'mcc': [] }
for i in range(N_SPLITS): fold_num = i + 1 print("\n--- Evaluating Fold {}/{} ---".format(fold_num, N_SPLITS)) # Isolate the validation data for this fold _, val_index = all_splits[i] val_df = df.iloc[val_index]
# Create generator for this fold's validation set val_datagen = ImageDataGenerator(rescale=1.0 / 255) validation_generator = val_datagen.flow_from_dataframe( dataframe=val_df, x_col='filepath', y_col='class', target_size=(NORM_SIZE, NORM_SIZE), batch_size=BATCH_SIZE, class_mode="categorical", shuffle=False )
# Load the corresponding model model_path = "{}/{}_fold_{}.hdf5".format(MODEL_DIR, MODEL_NAME, fold_num) if not os.path.exists(model_path): print("WARNING: Model file not found for Fold {} at {}. Skipping.".format(fold_num, model_path)) continue model = load_model(model_path) # Predict and calculate metrics y_true = validation_generator.classes y_pred = np.argmax(model.predict(validation_generator, verbose=0), axis=1) # Use macro averaging and calculate MCC report = classification_report(y_true, y_pred, output_dict=True) mcc = matthews_corrcoef(y_true, y_pred) # Store the required metrics all_scores['accuracy'].append(report['accuracy']) all_scores['precision_macro'].append(report['macro avg']['precision']) all_scores['recall_macro'].append(report['macro avg']['recall']) all_scores['f1_macro'].append(report['macro avg']['f1-score']) all_scores['mcc'].append(mcc) print("Fold {} Accuracy: {:.4f}, MCC: {:.4f}".format(fold_num, report['accuracy'], mcc))
# ==============================================================================# 5. DISPLAY THE FINAL AGGREGATED REPORT (FOR YOUR PAPER'S TABLE)# ==============================================================================print("\n========== FINAL CROSS-VALIDATION REPORT (Mean ± Std. Dev.) ==========")for metric, scores in all_scores.items(): if scores: # Check if there are any scores to average mean = np.mean(scores) std = np.std(scores) # Using ljust for clean alignment print("{:<25}: {:.4f} ± {:.4f}".format(metric.replace('_', ' ').title(), mean, std))print("======================================================================")
# ==============================================================================# 6. GENERATE VISUALIZATIONS FOR THE REPRESENTATIVE FOLD (FOR YOUR PAPER'S FIGURES)# ==============================================================================print("\n[INFO] Generating visualizations for representative Fold {}...".format(FOLD_FOR_VISUALIZATION))
# Isolate data for the chosen visualization fold_, val_index_vis = all_splits[FOLD_FOR_VISUALIZATION - 1]val_df_vis = df.iloc[val_index_vis]validation_generator_vis = val_datagen.flow_from_dataframe( dataframe=val_df_vis, x_col='filepath', y_col='class', target_size=(NORM_SIZE, NORM_SIZE), batch_size=BATCH_SIZE, class_mode="categorical", shuffle=False)
# Load the model and get predictionsmodel_path_vis = "{}/{}_fold_{}.hdf5".format(MODEL_DIR, MODEL_NAME, FOLD_FOR_VISUALIZATION)model_vis = load_model(model_path_vis)y_true_vis = validation_generator_vis.classesy_pred_vis = np.argmax(model_vis.predict(validation_generator_vis, verbose=0), axis=1)
# --- Plot 1: Detailed Confusion Matrix ---cm = confusion_matrix(y_true_vis, y_pred_vis)plot_confusion_matrix_with_counts(cm, classes=['NoFire', 'Fire'], title='Confusion Matrix (Fold {})'.format(FOLD_FOR_VISUALIZATION), save_path='{}/final_report_cm.png'.format(PLOT_DIR))
# --- Plot 2: Classification Report as a Table (from your code) ---report_vis = classification_report(y_true_vis, y_pred_vis, target_names=['NoFire', 'Fire'], output_dict=True)report_df = pd.DataFrame(report_vis).transpose()fig, ax = plt.subplots(figsize=(8, 4))ax.axis('tight'); ax.axis('off')table = ax.table(cellText=report_df.round(3).values, colLabels=report_df.columns, rowLabels=report_df.index, cellLoc='center', loc='center')table.auto_set_font_size(False); table.set_fontsize(10); table.scale(1.2, 1.2)ax.set_title("Classification Report (Fold {})".format(FOLD_FOR_VISUALIZATION), pad=20, fontsize=16)plt.savefig("{}/final_report_table.png".format(PLOT_DIR), dpi=300, bbox_inches='tight'); plt.show()
# --- Plot 3: Prediction Examples (from your code) ---images, _ = next(validation_generator_vis)predictions = np.argmax(model_vis.predict(images), axis=1)plt.figure(figsize=(15, 15))for i in range(min(12, len(images))): plt.subplot(4, 3, i + 1) rgb_image = cv2.cvtColor((images[i]*255).astype(np.uint8), cv2.COLOR_BGR2RGB) plt.imshow(rgb_image) plt.title("Prediction: {}".format(getLabel(predictions[i]))) plt.axis('off')plt.tight_layout(); plt.savefig("{}/final_report_predictions.png".format(PLOT_DIR), dpi=300); plt.show()
print("\n[INFO] All reports and visualizations have been generated successfully.")12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182# This file may be used to create an environment using:
# $ conda create --name <env> --file <this file>
# platform: win-64
@EXPLICIT
https://conda.anaconda.org/conda-forge/win-64/ca-certificates-2024.8.30-h56e8100_0.conda
https://conda.anaconda.org/conda-forge/win-64/intel-openmp-2024.2.1-h57928b3_1083.conda
https://conda.anaconda.org/conda-forge/win-64/msys2-conda-epoch-20160418-1.tar.bz2
https://conda.anaconda.org/conda-forge/win-64/python_abi-3.9-5_cp39.conda
https://conda.anaconda.org/conda-forge/noarch/tzdata-2024b-hc8b5060_0.conda
https://conda.anaconda.org/conda-forge/win-64/ucrt-10.0.22621.0-h57928b3_1.conda
https://conda.anaconda.org/conda-forge/win-64/m2w64-gmp-6.1.0-2.tar.bz2
https://conda.anaconda.org/conda-forge/win-64/m2w64-libwinpthread-git-5.0.0.4634.697f757-2.tar.bz2
https://conda.anaconda.org/conda-forge/win-64/vc14_runtime-14.40.33810-hcc2c482_22.conda
https://conda.anaconda.org/conda-forge/win-64/m2w64-gcc-libs-core-5.3.0-7.tar.bz2
https://conda.anaconda.org/conda-forge/win-64/vc-14.3-ha32ba9b_22.conda
https://conda.anaconda.org/conda-forge/win-64/vs2015_runtime-14.40.33810-h3bf8584_22.conda
https://conda.anaconda.org/conda-forge/win-64/bzip2-1.0.8-h2466b09_7.conda
https://conda.anaconda.org/conda-forge/win-64/cudatoolkit-11.2.2-h7d7167e_13.conda
https://conda.anaconda.org/conda-forge/win-64/libffi-3.4.2-h8ffe710_5.tar.bz2
https://conda.anaconda.org/conda-forge/win-64/libiconv-1.17-hcfcfb64_2.conda
https://conda.anaconda.org/conda-forge/win-64/libsodium-1.0.20-hc70643c_0.conda
https://conda.anaconda.org/conda-forge/win-64/libsqlite-3.47.0-h2466b09_1.conda
https://conda.anaconda.org/conda-forge/win-64/libzlib-1.3.1-h2466b09_2.conda
https://conda.anaconda.org/conda-forge/win-64/m2w64-gcc-libgfortran-5.3.0-6.tar.bz2
https://conda.anaconda.org/conda-forge/win-64/openssl-3.3.2-h2466b09_0.conda
https://conda.anaconda.org/conda-forge/win-64/pthreads-win32-2.9.1-h2466b09_4.conda
https://conda.anaconda.org/conda-forge/win-64/tk-8.6.13-h5226925_1.conda
https://conda.anaconda.org/conda-forge/win-64/xz-5.2.6-h8d14728_0.tar.bz2
https://conda.anaconda.org/conda-forge/win-64/cudnn-8.1.0.77-h3e0f4f4_0.tar.bz2
https://conda.anaconda.org/conda-forge/win-64/krb5-1.21.3-hdf4eb48_0.conda
https://conda.anaconda.org/conda-forge/win-64/libxml2-2.13.4-h442d1da_2.conda
https://conda.anaconda.org/conda-forge/win-64/m2w64-gcc-libs-5.3.0-7.tar.bz2
https://conda.anaconda.org/conda-forge/win-64/python-3.9.20-hfaddaf0_1_cpython.conda
https://conda.anaconda.org/conda-forge/noarch/backcall-0.2.0-pyh9f0ad1d_0.tar.bz2
https://conda.anaconda.org/conda-forge/noarch/colorama-0.4.6-pyhd8ed1ab_0.tar.bz2
https://conda.anaconda.org/conda-forge/win-64/debugpy-1.8.7-py39ha51f57c_0.conda
https://conda.anaconda.org/conda-forge/noarch/decorator-5.1.1-pyhd8ed1ab_0.tar.bz2
https://conda.anaconda.org/conda-forge/noarch/executing-2.1.0-pyhd8ed1ab_0.conda
https://conda.anaconda.org/conda-forge/win-64/libhwloc-2.11.1-default_h8125262_1000.conda
https://conda.anaconda.org/conda-forge/noarch/nest-asyncio-1.6.0-pyhd8ed1ab_0.conda
https://conda.anaconda.org/conda-forge/noarch/packaging-24.1-pyhd8ed1ab_0.conda
https://conda.anaconda.org/conda-forge/noarch/parso-0.8.4-pyhd8ed1ab_0.conda
https://conda.anaconda.org/conda-forge/noarch/pickleshare-0.7.5-py_1003.tar.bz2
https://conda.anaconda.org/conda-forge/noarch/platformdirs-4.3.6-pyhd8ed1ab_0.conda
https://conda.anaconda.org/conda-forge/win-64/psutil-6.1.0-py39ha55e580_0.conda
https://conda.anaconda.org/conda-forge/noarch/pure_eval-0.2.3-pyhd8ed1ab_0.conda
https://conda.anaconda.org/conda-forge/noarch/pygments-2.18.0-pyhd8ed1ab_0.conda
https://conda.anaconda.org/conda-forge/win-64/pywin32-307-py39ha51f57c_3.conda
https://conda.anaconda.org/conda-forge/noarch/setuptools-75.3.0-pyhd8ed1ab_0.conda
https://conda.anaconda.org/conda-forge/noarch/six-1.16.0-pyh6c4a22f_0.tar.bz2
https://conda.anaconda.org/conda-forge/noarch/threadpoolctl-3.5.0-pyhc1e730c_0.conda
https://conda.anaconda.org/conda-forge/win-64/tornado-6.4.1-py39ha55e580_1.conda
https://conda.anaconda.org/conda-forge/noarch/traitlets-5.14.3-pyhd8ed1ab_0.conda
https://conda.anaconda.org/conda-forge/noarch/typing_extensions-4.12.2-pyha770c72_0.conda
https://conda.anaconda.org/conda-forge/noarch/wcwidth-0.2.13-pyhd8ed1ab_0.conda
https://conda.anaconda.org/conda-forge/noarch/wheel-0.44.0-pyhd8ed1ab_0.conda
https://conda.anaconda.org/conda-forge/win-64/zeromq-4.3.5-ha9f60a1_6.conda
https://conda.anaconda.org/conda-forge/noarch/zipp-3.20.2-pyhd8ed1ab_0.conda
https://conda.anaconda.org/conda-forge/noarch/asttokens-2.4.1-pyhd8ed1ab_0.conda
https://conda.anaconda.org/conda-forge/noarch/comm-0.2.2-pyhd8ed1ab_0.conda
https://conda.anaconda.org/conda-forge/noarch/importlib-metadata-8.5.0-pyha770c72_0.conda
https://conda.anaconda.org/conda-forge/noarch/jedi-0.19.1-pyhd8ed1ab_0.conda
https://conda.anaconda.org/conda-forge/noarch/joblib-1.4.2-pyhd8ed1ab_0.conda
https://conda.anaconda.org/conda-forge/win-64/jupyter_core-5.7.2-py39hcbf5309_0.conda
https://conda.anaconda.org/conda-forge/noarch/matplotlib-inline-0.1.7-pyhd8ed1ab_0.conda
https://conda.anaconda.org/conda-forge/noarch/pip-24.3.1-pyh8b19718_0.conda
https://conda.anaconda.org/conda-forge/noarch/prompt-toolkit-3.0.48-pyha770c72_0.conda
https://conda.anaconda.org/conda-forge/noarch/python-dateutil-2.9.0-pyhd8ed1ab_0.conda
https://conda.anaconda.org/conda-forge/win-64/pyzmq-26.2.0-py39h03e5c00_3.conda
https://conda.anaconda.org/conda-forge/win-64/tbb-2021.13.0-hc790b64_0.conda
https://conda.anaconda.org/conda-forge/noarch/jupyter_client-8.6.3-pyhd8ed1ab_0.conda
https://conda.anaconda.org/conda-forge/win-64/mkl-2024.2.2-h66d3029_14.conda
https://conda.anaconda.org/conda-forge/noarch/prompt_toolkit-3.0.48-hd8ed1ab_0.conda
https://conda.anaconda.org/conda-forge/noarch/stack_data-0.6.2-pyhd8ed1ab_0.conda
https://conda.anaconda.org/conda-forge/noarch/ipython-8.12.0-pyh08f2357_0.conda
https://conda.anaconda.org/conda-forge/win-64/libblas-3.9.0-25_win64_mkl.conda
https://conda.anaconda.org/conda-forge/noarch/ipykernel-6.29.5-pyh4bbf305_0.conda
https://conda.anaconda.org/conda-forge/win-64/libcblas-3.9.0-25_win64_mkl.conda
https://conda.anaconda.org/conda-forge/win-64/liblapack-3.9.0-25_win64_mkl.conda
https://conda.anaconda.org/conda-forge/win-64/numpy-1.19.2-py39h5659d19_1.tar.bz2
https://conda.anaconda.org/conda-forge/win-64/scipy-1.5.3-py39hc0c34ad_0.tar.bz2
https://conda.anaconda.org/conda-forge/win-64/scikit-learn-1.5.2-py39hdd013cc_1.conda1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374# predict.pyimport tensorflow as tffrom tensorflow.keras.models import load_modelfrom tensorflow.keras.preprocessing.image import img_to_array, load_imgimport numpy as npimport argparseimport cv2
# --- Configuration ---MODEL_PATH = "./models/ProposedNetwork_StratifiedKFold_Final_fold_5.hdf5" # Path to your best modelIMAGE_SIZE = 224
def getLabel(class_id): """Returns the string label for a given class ID.""" return 'NoFire' if class_id == 0 else 'Fire'
# --- Argument Parser ---# This allows us to run the script from the command lineparser = argparse.ArgumentParser(description="Predict if an image contains fire using a trained model.")parser.add_argument("-i", "--image", required=True, help="Path to the input image")args = vars(parser.parse_args())
# --- Load and Preprocess the Image ---try: print("[INFO] Loading and preprocessing image...") # Load the image using Keras helper utility image = load_img(args["image"], target_size=(IMAGE_SIZE, IMAGE_SIZE)) image = img_to_array(image) # Scale pixel values to the range [0, 1] as done during training image = image / 255.0 # Add a batch dimension, as the model expects it image = np.expand_dims(image, axis=0)except Exception as e: print("[ERROR] Could not load or process the image. Please check the path.") print("Error details:", e) exit()
# --- Load the Model and Predict ---try: print("[INFO] Loading the trained model...") model = load_model(MODEL_PATH)
print("[INFO] Making prediction...") # Get the raw prediction (probabilities) prediction_probs = model.predict(image)[0] # Get the class index with the highest probability predicted_class_index = np.argmax(prediction_probs) # Get the corresponding label and confidence predicted_label = getLabel(predicted_class_index) confidence = prediction_probs[predicted_class_index]
# --- Display the Result --- print("\n========== PREDICTION RESULT ==========") print("Prediction: {}".format(predicted_label)) print("Confidence: {:.2f}%".format(confidence * 100)) print("=======================================")
# Optional: Display the image with the prediction original_image = cv2.imread(args["image"]) text = "{}: {:.2f}%".format(predicted_label, confidence * 100) color = (0, 0, 255) if predicted_label == "Fire" else (0, 255, 0) cv2.putText(original_image, text, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2) cv2.imshow("Result", original_image) cv2.waitKey(0) # Press any key to close the image window cv2.destroyAllWindows()
except Exception as e: print("[ERROR] An error occurred during model loading or prediction.") print("Error details:", e)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161from keras.models import load_modelfrom sklearn.metrics import classification_report, precision_score, recall_score, f1_score, accuracy_scoreimport numpy as npfrom keras.preprocessing.image import img_to_array, ImageDataGeneratorfrom sklearn.metrics import classification_reportimport pandas as pdimport matplotlib.pyplot as pltimport numpy as np
# Path to your saved modelmodel_path = "./Model/optimized_model_LAST.hdf5" # Replace with your model's namemodel = load_model(model_path)
# Dataset Parametersdataset_path = "./Dataset/FireNet_Augmented/" # Replace with your dataset pathnorm_size = 224batch_size = 32
# Data Generator for Validationdatagen = ImageDataGenerator(rescale=1.0 / 255, validation_split=0.3)validation_generator = datagen.flow_from_directory( dataset_path, target_size=(norm_size, norm_size), batch_size=batch_size, class_mode="categorical", subset="validation", shuffle=False # Ensure labels and predictions align)
y_true = validation_generator.classes # True labels from the generatory_pred_prob = model.predict(validation_generator, verbose=1) # Predicted probabilitiesy_pred = np.argmax(y_pred_prob, axis=1) # Predicted class indices
# Compute metricsaccuracy = accuracy_score(y_true, y_pred)precision = precision_score(y_true, y_pred, average='weighted', zero_division=1)recall = recall_score(y_true, y_pred, average='weighted', zero_division=1)f1 = f1_score(y_true, y_pred, average='weighted', zero_division=1)
# Print metricsprint("Accuracy:", accuracy)print("Precision:", precision)print("Recall:", recall)print("F1 Score:", f1)
# Detailed classification reportreport = classification_report( y_true, y_pred, target_names=['NoFire', 'Fire'], output_dict=True, zero_division=1)metrics_data = { 'Metric': ['F1 Score', 'Precision', 'Recall'], 'Fire': [ round(report['Fire']['f1-score'], 3), round(report['Fire']['precision'], 3), round(report['Fire']['recall'], 3) ], 'No Fire': [ round(report['NoFire']['f1-score'], 3), round(report['NoFire']['precision'], 3), round(report['NoFire']['recall'], 3) ]}
metrics_df = pd.DataFrame(metrics_data)
# Prepare data for the tablecell_text = [["Labels", "F1 Score", "Precision", "Recall"], # Column Headers ["Fire", metrics_df['Fire'][0], metrics_df['Fire'][1], metrics_df['Fire'][2]], # Fire Data Row ["No Fire", metrics_df['No Fire'][0], metrics_df['No Fire'][1], metrics_df['No Fire'][2]]] # No Fire Data Row
# Set up figure and axisfig, ax = plt.subplots(figsize=(8, 3)) # Adjust size as neededax.axis('off')
# Add the title text just above the table with minimal spacingax.text(0.50, 0.75, 'Classification Report', ha='center', va='top', fontsize=14, weight='bold', transform=ax.transAxes)
# Create the tabletable = ax.table( cellText=cell_text, cellLoc='center', colWidths=[0.3, 0.2, 0.2, 0.2], loc='center')
# Adjust the main table stylingtable.auto_set_font_size(False)table.set_fontsize(12)table.scale(1.2, 1.2) # Scale up for readability
# Set bold for header row in the main tablefor (i, j), cell in table.get_celld().items(): if i == 0: # Header Row Styling cell.set_text_props(weight='bold')
plt.show()
name_file = "optimized_model"from keras.models import load_modelimport matplotlib.pyplot as pltimport cv2import numpy as np
# Define the getLabel functiondef getLabel(id): return ['NoFire', 'Fire'][id]
# Helper function to get distinct balanced samples from the validation generatordef get_balanced_samples(generator, num_samples_per_class=6): """ Collect balanced samples from the generator. Args: generator: Validation generator. num_samples_per_class: Number of samples to select per class. Returns: images: Array of balanced images. labels: Array of corresponding labels. """ images, labels = [], [] class_counts = {0: 0, 1: 0} # Track counts for 'NoFire' and 'Fire' while class_counts[0] < num_samples_per_class or class_counts[1] < num_samples_per_class: batch_data, batch_labels = next(generator) # Get a batch for i in range(len(batch_data)): label = np.argmax(batch_labels[i]) # Convert one-hot encoding to class index if class_counts[label] < num_samples_per_class: images.append(batch_data[i]) labels.append(label) class_counts[label] += 1 if class_counts[0] == num_samples_per_class and class_counts[1] == num_samples_per_class: break return np.array(images), np.array(labels)
# Load the best model# model_path = "./Model/" + name_file + ".hdf5"# model = load_model(model_path, compile=False)
# Get a balanced batch of validation dataX_test, y_test = get_balanced_samples(validation_generator, num_samples_per_class=6)
# Make predictionsres = model.predict(X_test).argmax(axis=-1)
# Visualize predictions for the best modelplt.figure(figsize=(12, 12))for i in range(12): # Display all 12 images plt.subplot(3, 4, i + 1) # Create a 3x4 grid of plots
# Convert data to a valid range for imshow image = (X_test[i] * 255).astype(np.uint8) # Denormalize image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # Convert to RGB
plt.imshow(image) plt.gca().get_xaxis().set_ticks([]) plt.gca().get_yaxis().set_ticks([]) plt.ylabel('Prediction = %s' % getLabel(res[i]), fontsize=10)
# Save and display the plotplt.tight_layout() # Adjust spacing for the 3x4 gridplt.savefig('./Plot/' + name_file + '_Best.png', dpi=300)plt.show()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687absl-py==0.15.0
asttokens @ file:///home/conda/feedstock_root/build_artifacts/asttokens_1698341106958/work
astunparse==1.6.3
backcall @ file:///home/conda/feedstock_root/build_artifacts/backcall_1592338393461/work
cachetools==5.5.0
certifi==2024.8.30
charset-normalizer==3.4.0
colorama @ file:///home/conda/feedstock_root/build_artifacts/colorama_1666700638685/work
comm @ file:///home/conda/feedstock_root/build_artifacts/comm_1710320294760/work
contourpy==1.3.0
cycler==0.12.1
debugpy @ file:///D:/bld/debugpy_1728594250619/work
decorator @ file:///home/conda/feedstock_root/build_artifacts/decorator_1641555617451/work
executing @ file:///home/conda/feedstock_root/build_artifacts/executing_1725214404607/work
flatbuffers==1.12
fonttools==4.54.1
gast==0.4.0
google-auth==2.36.0
google-auth-oauthlib==0.4.6
google-pasta==0.2.0
grpcio==1.34.1
h5py==3.1.0
idna==3.10
importlib_metadata @ file:///home/conda/feedstock_root/build_artifacts/importlib-metadata_1726082825846/work
importlib_resources==6.4.5
imutils==0.5.4
ipykernel @ file:///D:/bld/ipykernel_1719845595208/work
ipython @ file:///D:/bld/ipython_1680185618122/work
jedi @ file:///home/conda/feedstock_root/build_artifacts/jedi_1696326070614/work
joblib @ file:///home/conda/feedstock_root/build_artifacts/joblib_1714665484399/work
jupyter_client @ file:///home/conda/feedstock_root/build_artifacts/jupyter_client_1726610684920/work
jupyter_core @ file:///D:/bld/jupyter_core_1710257377578/work
Keras==2.4.3
Keras-Preprocessing==1.1.2
kiwisolver==1.4.7
Markdown==3.7
MarkupSafe==3.0.2
matplotlib==3.3.4
matplotlib-inline @ file:///home/conda/feedstock_root/build_artifacts/matplotlib-inline_1713250518406/work
nest_asyncio @ file:///home/conda/feedstock_root/build_artifacts/nest-asyncio_1705850609492/work
numpy @ file:///D:/bld/numpy_1603047748240/work
oauthlib==3.2.2
opencv-python==4.10.0.84
opt-einsum==3.3.0
packaging @ file:///home/conda/feedstock_root/build_artifacts/packaging_1718189413536/work
pandas==1.1.5
parso @ file:///home/conda/feedstock_root/build_artifacts/parso_1712320355065/work
pickleshare @ file:///home/conda/feedstock_root/build_artifacts/pickleshare_1602536217715/work
pillow==11.0.0
platformdirs @ file:///home/conda/feedstock_root/build_artifacts/platformdirs_1726613481435/work
prompt_toolkit @ file:///home/conda/feedstock_root/build_artifacts/prompt-toolkit_1727341649933/work
protobuf==3.20.3
psutil @ file:///D:/bld/psutil_1729847171148/work
pure_eval @ file:///home/conda/feedstock_root/build_artifacts/pure_eval_1721585709575/work
pyasn1==0.6.1
pyasn1_modules==0.4.1
Pygments @ file:///home/conda/feedstock_root/build_artifacts/pygments_1714846767233/work
pyparsing==3.2.0
python-dateutil @ file:///home/conda/feedstock_root/build_artifacts/python-dateutil_1709299778482/work
pytz==2024.2
pywin32==307
PyYAML==6.0.2
pyzmq @ file:///D:/bld/pyzmq_1728642354337/work
requests==2.32.3
requests-oauthlib==2.0.0
rsa==4.9
scikit-learn @ file:///D:/bld/scikit-learn_1726082805314/work/dist/scikit_learn-1.5.2-cp39-cp39-win_amd64.whl#sha256=ae5765420950e15ea2e5d7255f8963a2a33063e6d841408a2b1b94d1917cf6c2
scipy @ file:///C:/bld/scipy_1604305141961/work
seaborn==0.11.2
six==1.15.0
stack-data @ file:///home/conda/feedstock_root/build_artifacts/stack_data_1669632077133/work
tensorboard==2.11.2
tensorboard-data-server==0.6.1
tensorboard-plugin-wit==1.8.1
tensorflow-estimator==2.5.0
tensorflow-gpu==2.5.0
termcolor==1.1.0
threadpoolctl @ file:///home/conda/feedstock_root/build_artifacts/threadpoolctl_1714400101435/work
tornado @ file:///D:/bld/tornado_1724956258948/work
traitlets @ file:///home/conda/feedstock_root/build_artifacts/traitlets_1713535121073/work
typing-extensions==3.7.4.3
tzdata==2024.2
urllib3==2.2.3
wcwidth @ file:///home/conda/feedstock_root/build_artifacts/wcwidth_1704731205417/work
Werkzeug==3.1.2
wrapt==1.12.1
zipp @ file:///home/conda/feedstock_root/build_artifacts/zipp_1726248574750/work123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239# ==============================================================================# 1. IMPORTS AND SETUP# ==============================================================================import osimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport itertoolsimport cv2import tensorflow as tffrom imutils import pathsfrom sklearn.model_selection import StratifiedKFoldfrom sklearn.metrics import confusion_matrix, classification_report, matthews_corrcoeffrom tensorflow.keras.preprocessing.image import ImageDataGeneratorfrom tensorflow.keras.optimizers import Adamfrom tensorflow.keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, EarlyStopping, CSVLoggerfrom tensorflow.keras import backend as Kfrom tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2
# Import your model architecturefrom cnn_multi import combine_4SC_2_1_V3
# Suppress warnings for cleaner outputos.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"tf.get_logger().setLevel('ERROR')
# ==============================================================================# 2. CONFIGURATION PARAMETERS# ==============================================================================DATASET_PATH = './Dataset/ThermalFire/'MODEL_NAME = "ProposedNetwork_StratifiedKFold_Final"NORM_SIZE = 224NUM_CLASSES = 2INPUT_SHAPE = (NORM_SIZE, NORM_SIZE, 3)BATCH_SIZE = 32EPOCHS = 150LEARNING_RATE = 0.001N_SPLITS = 5 # Number of folds for cross-validation
# --- Define Output Directories ---LOGS_DIR = "./Logs"MODEL_DIR = "./Model"PLOT_DIR = "./Plot"
# --- Create Output Directories if they don't exist ---os.makedirs(LOGS_DIR, exist_ok=True)os.makedirs(MODEL_DIR, exist_ok=True)os.makedirs(PLOT_DIR, exist_ok=True)
# Set seeds for reproducibilitynp.random.seed(42)tf.random.set_seed(42)
# ==============================================================================# 3. HELPER FUNCTIONS# ==============================================================================def calculate_gflops(model, batch_size=1): """Calculates GFLOPS for a Keras model.""" input_shape = (batch_size,) + model.input_shape[1:] inputs = tf.random.normal(input_shape) run_model = tf.function(lambda x: model(x)) concrete_func = run_model.get_concrete_function(inputs) frozen_func = convert_variables_to_constants_v2(concrete_func) graph_def = frozen_func.graph.as_graph_def() with tf.Graph().as_default() as graph: tf.import_graph_def(graph_def, name="") run_meta = tf.compat.v1.RunMetadata() opts = tf.compat.v1.profiler.ProfileOptionBuilder.float_operation() flops = tf.compat.v1.profiler.profile(graph=graph, run_meta=run_meta, cmd='op', options=opts) return flops.total_float_ops / 1e9
def get_model_parameters(model): """Counts the total parameters of a model.""" return model.count_params()
def getLabel(class_id): """Returns the string label for a given class ID.""" return ['NoFire', 'Fire'][class_id]
def plot_confusion_matrix_with_counts(cm, classes, title='Normalized Confusion Matrix', cmap=plt.cm.Blues, save_path=None): """Plots a detailed confusion matrix with both normalized values and absolute counts.""" cm_counts = cm.astype(int) cm_sum = cm_counts.sum(axis=1)[:, np.newaxis] cm_normalized = np.divide(cm_counts.astype('float'), cm_sum, out=np.zeros_like(cm_counts, dtype=float), where=(cm_sum!=0)) fig, ax = plt.subplots(figsize=(10, 10)) im = ax.imshow(cm_normalized, interpolation='nearest', cmap=cmap, vmin=0, vmax=1) ax.figure.colorbar(im, ax=ax, shrink=0.8) ax.set(xticks=np.arange(cm.shape[1]), yticks=np.arange(cm.shape[0]), xticklabels=classes, yticklabels=classes, title=title, ylabel='True label', xlabel='Predicted label') plt.setp(ax.get_xticklabels(), rotation=45, ha="right", rotation_mode="anchor") thresh = cm_normalized.max() / 2. for i in range(cm.shape[0]): for j in range(cm.shape[1]): ax.text(j, i, f"{cm_normalized[i, j]:.2f}\n({cm_counts[i, j]} images)", ha="center", va="center", color="white" if cm_normalized[i, j] > thresh else "black") fig.tight_layout() if save_path: plt.savefig(save_path, dpi=300) plt.show()
# ==============================================================================# 4. DATA PREPARATION# ==============================================================================print("[INFO] Loading image paths and labels...")imagePaths = sorted(list(paths.list_images(DATASET_PATH)))data = [(path, os.path.basename(os.path.dirname(path))) for path in imagePaths]df = pd.DataFrame(data, columns=['filepath', 'class']).sample(frac=1, random_state=42).reset_index(drop=True)print(f"[INFO] Found {len(df)} images. Class distribution:\n{df['class'].value_counts()}")
# ==============================================================================# 5. ONE-TIME MODEL ANALYSIS (GFLOPS & PARAMETERS)# ==============================================================================print("\n[INFO] Performing one-time model analysis...")temp_model = combine_4SC_2_1_V3(input_shape=INPUT_SHAPE, num_classes=NUM_CLASSES)total_params = get_model_parameters(temp_model)gflops = calculate_gflops(temp_model, batch_size=BATCH_SIZE)print(f"[INFO] Model Parameters: {total_params:,}")print(f"[INFO] GFLOPS: {gflops:.4f}")del temp_model # Clean up memory
# ==============================================================================# 6. STRATIFIED K-FOLD CROSS-VALIDATION# ==============================================================================skf = StratifiedKFold(n_splits=N_SPLITS, shuffle=True, random_state=42)all_scores = { 'accuracy': [], 'loss': [], 'precision_macro': [], 'recall_macro': [], 'f1_macro': [], 'mcc': [] }fold_num = 1history_last_fold = Nonebest_model_path_last_fold = ""val_index_last_fold = None
for train_index, val_index in skf.split(df['filepath'], df['class']): print(f"\n========== FOLD {fold_num}/{N_SPLITS} ==========") train_df, val_df = df.iloc[train_index], df.iloc[val_index]
train_datagen = ImageDataGenerator(rescale=1./255, rotation_range=20, width_shift_range=0.2, height_shift_range=0.2, zoom_range=0.2, horizontal_flip=True, fill_mode='nearest') val_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_dataframe(train_df, x_col='filepath', y_col='class', target_size=(NORM_SIZE, NORM_SIZE), batch_size=BATCH_SIZE, class_mode='categorical', shuffle=True) validation_generator = val_datagen.flow_from_dataframe(val_df, x_col='filepath', y_col='class', target_size=(NORM_SIZE, NORM_SIZE), batch_size=BATCH_SIZE, class_mode='categorical', shuffle=False)
model = combine_4SC_2_1_V3(input_shape=INPUT_SHAPE, num_classes=NUM_CLASSES) model.compile(loss='categorical_crossentropy', optimizer=Adam(learning_rate=LEARNING_RATE), metrics=['accuracy'])
# These paths are now unique for each fold model_filepath = f"{MODEL_DIR}/{MODEL_NAME}_fold_{fold_num}.hdf5" csv_log_path = f"{LOGS_DIR}/{MODEL_NAME}_fold_{fold_num}_training.csv" callbacks_list = [ ModelCheckpoint(model_filepath, monitor='val_loss', verbose=1, save_best_only=True, mode='min'), ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=10, verbose=1, min_lr=1e-6), EarlyStopping(monitor='val_loss', patience=15, verbose=1, restore_best_weights=True), CSVLogger(csv_log_path) # The CSVLogger will save the log for this fold here ]
print(f"[INFO] Training model for Fold {fold_num}...") history = model.fit(train_generator, epochs=EPOCHS, validation_data=validation_generator, callbacks=callbacks_list, verbose=1)
print(f"[INFO] Evaluating Fold {fold_num}...") loss, accuracy = model.evaluate(validation_generator, verbose=0) y_true, y_pred = validation_generator.classes, np.argmax(model.predict(validation_generator), axis=1) report = classification_report(y_true, y_pred, target_names=['NoFire', 'Fire'], output_dict=True) mcc = matthews_corrcoef(y_true, y_pred) all_scores['loss'].append(loss); all_scores['accuracy'].append(accuracy) all_scores['precision_macro'].append(report['macro avg']['precision']) all_scores['recall_macro'].append(report['macro avg']['recall']) all_scores['f1_macro'].append(report['macro avg']['f1-score']); all_scores['mcc'].append(mcc)
print(f"[RESULT] Fold {fold_num} -> Loss: {loss:.4f}, Accuracy: {accuracy:.4f}, MCC: {mcc:.4f}") if fold_num == N_SPLITS: # Save data from the last fold for final visualizations history_last_fold = history best_model_path_last_fold = model_filepath val_index_last_fold = val_index
fold_num += 1
# ==============================================================================# 7. AGGREGATE AND DISPLAY FINAL RESULTS# ==============================================================================print("\n========== CROSS-VALIDATION FINAL RESULTS ==========")print(f"Metrics reported as: Mean ± Standard Deviation over {N_SPLITS} folds.\n")for metric, scores in all_scores.items(): print(f"{metric.replace('_', ' ').title():<20}: {np.mean(scores):.4f} ± {np.std(scores):.4f}")print("======================================================")
# ==============================================================================# 8. VISUALIZATION (using the last trained fold as a representative example)# ==============================================================================print("\n[INFO] Generating visualizations for the last trained fold...")if history_last_fold: # --- Plot Accuracy and Loss Curves --- plt.style.use("seaborn-whitegrid") fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(18, 6)) ax1.plot(history_last_fold.history['accuracy'], label='Train Acc'); ax1.plot(history_last_fold.history['val_accuracy'], label='Val Acc') ax1.set_title('Model Accuracy'); ax1.set_xlabel('Epoch'); ax1.set_ylabel('Accuracy'); ax1.legend(loc='lower right') ax2.plot(history_last_fold.history['loss'], label='Train Loss'); ax2.plot(history_last_fold.history['val_loss'], label='Val Loss') ax2.set_title('Model Loss'); ax2.set_xlabel('Epoch'); ax2.set_ylabel('Loss'); ax2.legend(loc='upper right') plt.tight_layout(); plt.savefig(f"{PLOT_DIR}/{MODEL_NAME}_curves.png", dpi=300); plt.show()
# --- Plot Confusion Matrix --- model.load_weights(best_model_path_last_fold) val_df_last_fold = df.iloc[val_index_last_fold] validation_generator_last_fold = val_datagen.flow_from_dataframe(val_df_last_fold, x_col='filepath', y_col='class', target_size=(NORM_SIZE, NORM_SIZE), batch_size=BATCH_SIZE, class_mode='categorical', shuffle=False) y_true = validation_generator_last_fold.classes y_pred = np.argmax(model.predict(validation_generator_last_fold), axis=1) cm = confusion_matrix(y_true, y_pred) plot_confusion_matrix_with_counts(cm, classes=['NoFire', 'Fire'], save_path=f"{PLOT_DIR}/{MODEL_NAME}_cm.png")
# --- Plot Classification Report Table --- report = classification_report(y_true, y_pred, target_names=['NoFire', 'Fire'], output_dict=True) report_df = pd.DataFrame(report).transpose() fig, ax = plt.subplots(figsize=(8, 4)) ax.axis('tight'); ax.axis('off') table = ax.table(cellText=report_df.round(3).values, colLabels=report_df.columns, rowLabels=report_df.index, cellLoc = 'center', loc='center') table.auto_set_font_size(False); table.set_fontsize(10); table.scale(1.2, 1.2) ax.set_title("Classification Report (Last Fold)", pad=20, fontsize=16) plt.savefig(f"{PLOT_DIR}/{MODEL_NAME}_report.png", dpi=300, bbox_inches='tight'); plt.show()
# --- Plot Prediction Examples --- images, _ = next(validation_generator_last_fold) predictions = np.argmax(model.predict(images), axis=1) plt.figure(figsize=(15, 15)) for i in range(min(12, len(images))): plt.subplot(4, 3, i + 1) rgb_image = cv2.cvtColor((images[i]*255).astype(np.uint8), cv2.COLOR_BGR2RGB) plt.imshow(rgb_image) plt.title(f"Prediction: {getLabel(predictions[i])}") plt.axis('off') plt.tight_layout(); plt.savefig(f"{PLOT_DIR}/{MODEL_NAME}_predictions.png", dpi=300); plt.show()
print("[INFO] Script finished successfully.").gitignore.txtAdded+22
Attention.pyAdded+321
README.md+23-13
Self.pyAdded+62
aug.pyAdded+68
cnn_multi.pyAdded+759
curve.pyAdded+39
gen.pyAdded+154
generate_gradcam.pyAdded+166
new_report.pyAdded+181
packages.txtAdded+82
predict.pyAdded+74
report.pyAdded+161
requirements.txtAdded+87
train.pyAdded+239