mport os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import tensorflow as tf
from tensorflow import keras
for i in range(9):
plt.subplot(3, 3, i + 1)
img = plt.imread(os.path.join(pneumonia_dir, pneumonia[i]))
plt.imshow(img, cmap='gray')
plt.axis('off')
plt.tight_layout()
In[8]:
normal = os.listdir("chest_xray/train/NORMAL")
normal_dir = "chest_xray/train/NORMAL"
plt.figure(figsize=(20, 10))
for i in range(9):
plt.subplot(3, 3, i + 1)
img = plt.imread(os.path.join(normal_dir, normal[i]))
plt.imshow(img, cmap='gray')
plt.axis('off')
plt.tight_layout()
In[9]:
normal_img = os.listdir("chest_xray/train/NORMAL")[0]
normal_dir = "chest_xray/train/NORMAL"
sample_img = plt.imread(os.path.join(normal_dir, normal_img))
plt.imshow(sample_img, cmap='gray')
plt.colorbar()
plt.title('Raw Chest X Ray Image')
print(f"The dimensions of the image are {sample_img.shape[0]} pixels width and {sample_img.shape[1]} pixels height, one single color channel.")
print(f"The maximum pixel value is {sample_img.max():.4f} and the minimum is {sample_img.min():.4f}")
print(f"The mean value of the pixels is {sample_img.mean():.4f} and the standard deviation is {sample_img.std():.4f}")
In[23]:
sns.distplot(sample_img.ravel(),
label=f"Pixel Mean {np.mean(sample_img):.4f} & Standard Deviation {np.std(sample_img):.4f}", kde=False)
plt.legend(loc='upper center')
plt.title('Distribution of Pixel Intensities in the Image')
plt.xlabel('Pixel Intensity')
plt.ylabel('# Pixels in Image')
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.applications import ResNet101
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Dense, GlobalAveragePooling2D, BatchNormalization
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.callbacks import ReduceLROnPlateau
In[26]:
import os
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import roc_auc_score, roc_curve
Updated Keras/TensorFlow imports
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.applications import ResNet101
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Dense, GlobalAveragePooling2D, BatchNormalization
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.callbacks import ReduceLROnPlateau
Augmentation library
import albumentations as A
from albumentations.pytorch import ToTensorV2
import cv2
from sklearn.metrics import precision_score, recall_score, f1_score
In[27]:
pip install albumentations
In[28]:
pip install albumentations[imgaug] torchvision
In[29]:
from albumentations.pytorch import ToTensorV2
In[30]:
import os
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import roc_auc_score, roc_curve
Updated Keras/TensorFlow imports
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.applications import ResNet101
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Dense, GlobalAveragePooling2D, BatchNormalization
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.callbacks import ReduceLROnPlateau
Augmentation library
import albumentations as A
from albumentations.pytorch import ToTensorV2
import cv2
from sklearn.metrics import precision_score, recall_score, f1_score
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix
Load your dataset (assuming you've already set up your directory correctly)
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix
Load your dataset (assuming you've already set up your directory correctly)
for i, accuracy in enumerate(accuracies):
plt.text(i, accuracy + 0.01, f"{accuracy*100:.1f}%", ha='center')
plt.title('Model Accuracies')
plt.xlabel('Models')
plt.ylabel('Accuracy (%)')
plt.ylim(0.75, 1) # Set limits for y-axis for better visualization
plt.xticks(rotation=15)
plt.grid()
Draw a horizontal line at y=0.8 for reference
plt.axhline(y=0.8, color='gray', linestyle='--', linewidth=0.5) # Example horizontal line
Adjust x-axis limits to start from 0
plt.xlim(-0.5, len(models) - 0.5) # Set x limits based on number of models
plt.show()
In[2]:
def se_block(input_tensor, reduction=16):
filters = input_tensor.shape[-1] # Number of channels (filters)
code
se = layers.GlobalAveragePooling2D()(input_tensor) # Squeeze
se = layers.Reshape((1, 1, filters))(se) # Reshape to (1, 1, filters)
se = layers.Dense(filters // reduction, activation='relu')(se) # Reduce filters
se = layers.Dense(filters, activation='sigmoid')(se) # Scale
se = layers.multiply([input_tensor, se]) # Excitation
return se
In[4]:
from tensorflow.keras.applications import ResNet101
In[5]:
Necessary imports
import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.applications import ResNet101
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Dense, GlobalAveragePooling2D, BatchNormalization
from tensorflow.keras.optimizers import Adam
from tensorflow.keras import layers
from tensorflow.keras.callbacks import ReduceLROnPlateau
SE block function
def se_block(input_tensor, reduction=16):
filters = input_tensor.shape[-1] # Number of channels (filters)
code
se = layers.GlobalAveragePooling2D()(input_tensor) # Squeeze
se = layers.Reshape((1, 1, filters))(se) # Reshape to (1, 1, filters)
se = layers.Dense(filters // reduction, activation='relu')(se) # Reduce filters
se = layers.Dense(filters, activation='sigmoid')(se) # Scale
se = layers.multiply([input_tensor, se]) # Excitation
return se
From the above code , Explain each and every line of the code in
Certainly! Let's walk through the entire code step-by-step, explaining each line and its purpose. The code appears to be part of a Jupyter Notebook focused on building and evaluating machine learning models for classifying chest X-ray images as either "Normal" or "Pneumonia." The workflow includes data exploration, visualization, data augmentation, feature extraction using pre-trained models, training various classifiers, evaluating their performance, and visualizing the results.
We'll break down the explanation according to the different cells (In[ ]) as indicated in your code.
Initial Setup and Data Exploration
Cell In[1]: Importing Libraries and Listing Directory Contents
python
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import tensorflow as tf
from tensorflow import keras
os.listdir("chest_xray")
Explanation:
Importing Libraries:
os: Module for interacting with the operating system. Used here to list directories.
numpy as np: Fundamental package for numerical computations in Python.
pandas as pd: Library for data manipulation and analysis.
matplotlib.pyplot as plt: Plotting library for creating static, animated, and interactive visualizations.
seaborn as sns: Statistical data visualization library based on matplotlib.
tensorflow as tf and from tensorflow import keras: TensorFlow is a deep learning framework, and Keras is its high-level API for building and training models.
Listing Directory Contents:
os.listdir("chest_xray"): Lists all files and directories in the "chest_xray" directory. This is useful to verify the presence of subdirectories like train, test, and val.
Purpose:
Setting up the environment by importing necessary libraries and verifying the data directory structure.
Cell In[3]: Counting Normal Images in Training Set
python
len(os.listdir("chest_xray/train/normal"))
Explanation:
os.listdir("chest_xray/train/normal"): Lists all files (images) in the normal subdirectory of the training dataset.
len(...): Counts the number of files, indicating how many "Normal" chest X-ray images are present in the training set.
Purpose:
To determine the number of "Normal" cases in the training dataset, which helps in understanding class distribution.
Cell In[4]: Counting Pneumonia Images in Training Set
python
len(os.listdir("chest_xray/train/pnemonia"))
Explanation:
Similar to the previous cell, this counts the number of files in the pnemonia (likely a typo for "pneumonia") subdirectory of the training dataset.
Purpose:
To determine the number of "Pneumonia" cases in the training dataset, assessing class balance.
Cell In[7]: Detailed Directory Structure and Counts
train_dir, test_dir, val_dir: Paths to training, testing, and validation directories respectively.
Printing Dataset Statistics:
For each dataset split (train, test, validation), it prints out the number of "Pneumonia" and "Normal" images.
Uses os.path.join to construct the full path to the subdirectories.
Note: There's a typo in 'Pnemonia' which should likely be 'Pneumonia' unless the directory is indeed named 'Pnemonia'.
Purpose:
To provide a clear overview of the dataset's structure and the distribution of classes across training, testing, and validation sets. This is crucial for understanding potential class imbalance issues.
Data Visualization
Cell In[8]: Visualizing Pneumonia Images
python
pneumonia = os.listdir("chest_xray/train/Pnemonia")
pneumonia_dir = "chest_xray/train/Pnemonia"
plt.figure(figsize=(20, 10))
for i in range(9):
plt.subplot(3, 3, i + 1)
img = plt.imread(os.path.join(pneumonia_dir, pneumonia[i]))
plt.imshow(img, cmap='gray')
plt.axis('off')
plt.tight_layout()
Explanation:
Listing Pneumonia Images:
pneumonia = os.listdir("chest_xray/train/Pnemonia"): Retrieves a list of all pneumonia image filenames in the training set.
pneumonia_dir: Stores the directory path for pneumonia images.
Setting Up the Plot:
plt.figure(figsize=(20, 10)): Creates a new figure with specified size.
Displaying Images:
for i in range(9): Loop to display the first 9 images.
plt.subplot(3, 3, i + 1): Arranges the images in a 3x3 grid.
img = plt.imread(...): Reads the image file.
plt.imshow(img, cmap='gray'): Displays the image in grayscale.
plt.axis('off'): Hides the axis ticks and labels for a cleaner look.
Layout Adjustment:
plt.tight_layout(): Adjusts subplot params so that subplots fit into the figure area.
Purpose:
To visualize sample pneumonia images from the training set, helping to understand the data's visual characteristics.
Cell In[8]: Visualizing Normal Images
python
normal = os.listdir("chest_xray/train/NORMAL")
normal_dir = "chest_xray/train/NORMAL"
plt.figure(figsize=(20, 10))
for i in range(9):
plt.subplot(3, 3, i + 1)
img = plt.imread(os.path.join(normal_dir, normal[i]))
plt.imshow(img, cmap='gray')
plt.axis('off')
plt.tight_layout()
Explanation:
This cell is almost identical to the previous one but focuses on "Normal" images instead of "Pneumonia."
normal = os.listdir("chest_xray/train/NORMAL"): Retrieves a list of all normal image filenames.
The rest of the code displays the first 9 normal images in a 3x3 grid.
Purpose:
To visualize sample normal chest X-ray images, enabling comparison between normal and pneumonia cases.
Cell In[9]: Detailed Image Analysis
python
normal_img = os.listdir("chest_xray/train/NORMAL")[0]
normal_dir = "chest_xray/train/NORMAL"
sample_img = plt.imread(os.path.join(normal_dir, normal_img))
plt.imshow(sample_img, cmap='gray')
plt.colorbar()
plt.title('Raw Chest X Ray Image')
print(f"The dimensions of the image are {sample_img.shape[0]} pixels width and {sample_img.shape[1]} pixels height, one single color channel.")
print(f"The maximum pixel value is {sample_img.max():.4f} and the minimum is {sample_img.min():.4f}")
print(f"The mean value of the pixels is {sample_img.mean():.4f} and the standard deviation is {sample_img.std():.4f}")
Explanation:
Selecting a Sample Image:
normal_img = os.listdir("chest_xray/train/NORMAL")[0]: Selects the first image file in the "Normal" training set.
sample_img = plt.imread(...): Reads the selected image.
Displaying the Sample Image:
plt.imshow(sample_img, cmap='gray'): Displays the image in grayscale.
plt.colorbar(): Adds a color bar indicating pixel intensity values.
plt.title('Raw Chest X Ray Image'): Sets the title for the plot.
Printing Image Statistics:
sample_img.shape: Returns the dimensions of the image. shape[0] is height (pixels width), and shape[1] is width (pixels height). Note: The description "pixels width" and "pixels height" might be swapped depending on image orientation.
sample_img.max() and sample_img.min(): Find the maximum and minimum pixel intensity values.
sample_img.mean() and sample_img.std(): Calculate the mean and standard deviation of pixel intensities.
Purpose:
To examine a single image in detail, understanding its dimensions, pixel intensity distribution, and overall characteristics. This aids in assessing the quality and consistency of the data.
Cell In[23]: Distribution of Pixel Intensities
python
sns.distplot(sample_img.ravel(),
label=f"Pixel Mean {np.mean(sample_img):.4f} & Standard Deviation {np.std(sample_img):.4f}", kde=False)
plt.legend(loc='upper center')
plt.title('Distribution of Pixel Intensities in the Image')
plt.xlabel('Pixel Intensity')
plt.ylabel('# Pixels in Image')
Explanation:
Preparing Data for Distribution Plot:
sample_img.ravel(): Flattens the 2D image array into a 1D array of pixel intensities.
Plotting the Distribution:
sns.distplot(...): Plots the distribution of pixel intensities using Seaborn.
kde=False: Disables the Kernel Density Estimate (smooth curve) to show a histogram instead.
label=...: Adds a label indicating the mean and standard deviation of pixel intensities.
Enhancing the Plot:
plt.legend(loc='upper center'): Places the legend at the top center of the plot.
plt.title(...), plt.xlabel(...), plt.ylabel(...): Sets the title and axis labels for clarity.
Purpose:
To visualize how pixel intensities are distributed in the sample image, providing insights into the image's contrast, brightness, and variability. This information can inform preprocessing steps like normalization or thresholding.
Installs (or ensures the installation of) various Python packages necessary for data manipulation, visualization, machine learning, and image processing:
numpy, pandas: For data handling.
matplotlib, seaborn: For plotting and visualization.
To make sure all required libraries are available in the environment, facilitating the subsequent steps in the workflow.
Cell In[25]: Importing Additional Libraries
python
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.applications import ResNet101
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Dense, GlobalAveragePooling2D, BatchNormalization
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.callbacks import ReduceLROnPlateau
Explanation:
ImageDataGenerator: For generating batches of tensor image data with real-time data augmentation.
ResNet101: A pre-trained deep learning model with 101 layers, useful for feature extraction.
Model, Dense, GlobalAveragePooling2D, BatchNormalization: Classes and layers for building neural network architectures.
Adam: An optimizer algorithm used for training the model.
ReduceLROnPlateau: A callback to reduce the learning rate when a metric has stopped improving.
Purpose:
To import specific classes and functions from TensorFlow's Keras API that are essential for building, training, and optimizing deep learning models.
Cell In[26]: Importing More Libraries and Re-importing for Clarity
python
import os
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import roc_auc_score, roc_curve
# Updated Keras/TensorFlow imports
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.applications import ResNet101
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Dense, GlobalAveragePooling2D, BatchNormalization
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.callbacks import ReduceLROnPlateau
# Augmentation library
import albumentations as A
from albumentations.pytorch import ToTensorV2
import cv2
from sklearn.metrics import precision_score, recall_score, f1_score
Explanation:
Re-importing Libraries: Some libraries are re-imported, possibly for ensuring they are available in the current cell's scope.
Additional Imports:
classification_report, roc_auc_score, roc_curve: For evaluating model performance.
SVC, LogisticRegression, RandomForestClassifier: Machine learning classifiers from scikit-learn.
albumentations as A, ToTensorV2, cv2: For advanced image augmentation and processing.
To ensure all necessary libraries and modules are available for the subsequent data preprocessing, model training, and evaluation steps.
Cell In[27]: Installing Albumentations Library
python
pip install albumentations
Explanation:
Installs the albumentations library, which is a fast and flexible image augmentation library.
Purpose:
To install albumentations, which provides a wide range of augmentations that can be applied to image datasets to improve model generalization.
Cell In[28]: Installing Albumentations with Extra Dependencies and TorchVision
python
pip install albumentations[imgaug] torchvision
Explanation:
albumentations[imgaug]: Installs albumentations along with the imgaug backend, which allows for more complex augmentations.
torchvision: A package from PyTorch containing popular datasets, model architectures, and image transformations for computer vision.
Purpose:
To enhance the image augmentation capabilities by installing additional dependencies (imgaug) and torchvision, which provides integration with PyTorch-based models and transformations.
Cell In[29]: Importing ToTensorV2 from Albumentations
python
from albumentations.pytorch import ToTensorV2
Explanation:
ToTensorV2: A transformation from albumentations that converts images to PyTorch tensors.
Purpose:
To include ToTensorV2 for converting augmented images into tensor format, which is required for PyTorch models. However, since the rest of the code uses TensorFlow/Keras, this import might not be necessary unless there's a mix of frameworks.
Cell In[30]: Repeating Imports (Possibly for Clarity)
python
import os
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import roc_auc_score, roc_curve
# Updated Keras/TensorFlow imports
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.applications import ResNet101
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Dense, GlobalAveragePooling2D, BatchNormalization
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.callbacks import ReduceLROnPlateau
# Augmentation library
import albumentations as A
from albumentations.pytorch import ToTensorV2
import cv2
from sklearn.metrics import precision_score, recall_score, f1_score
Explanation:
This cell repeats the import statements from Cell In[26], ensuring all necessary modules are available.
Purpose:
Possibly to ensure that all required libraries are imported in the current cell's scope, especially if this cell will contain additional code that relies on these imports.
These augmentations help in increasing the diversity of the training data, reducing overfitting.
Testing & Validation Data Generator (test_datagen):
Only rescale=1./255 is applied, as augmentations are typically not used during validation/testing to ensure consistency.
Creating Data Generators:
train_generator:
Reads images from train_dir.
target_size=(224, 224): Resizes all images to 224x224 pixels, matching typical input sizes for models like ResNet101.
batch_size=32: Number of samples per gradient update.
class_mode='binary': For binary classification (Normal vs. Pneumonia).
validation_generator:
Similar to train_generator but reads from val_dir.
test_generator:
Similar setup but reads from test_dir.
shuffle=False: Disables shuffling to maintain order, which is important for evaluation and metrics computation.
Purpose:
To prepare data generators for training, validation, and testing phases with appropriate augmentations and preprocessing. This setup is essential for feeding data into the neural network in batches and ensuring consistent input dimensions.
Feature Extraction and Training Traditional Classifiers
Cell In[32]: Feature Extraction with VGG16 and Training Classifiers
python
from keras.applications.vgg16 import VGG16
# Load a pre-trained VGG16 model for feature extraction
base_model = VGG16(weights='imagenet', include_top=False, input_shape=(224, 224, 3))
x = base_model.output
x = GlobalAveragePooling2D()(x)
feature_model = Model(inputs=base_model.input, outputs=x)
# Extract features for the training set
train_features = feature_model.predict(train_generator)
train_labels = train_generator.classes
# Extract features for the test set
test_features = feature_model.predict(test_generator)
test_labels = test_generator.classes
# Train Logistic Regression
lr_model = LogisticRegression(max_iter=1000)
lr_model.fit(train_features, train_labels)
lr_predictions = lr_model.predict(test_features)
# Train SVM
svm_model = SVC(kernel='linear', probability=True)
svm_model.fit(train_features, train_labels)
svm_predictions = svm_model.predict(test_features)
# Train Random Forest
rf_model = RandomForestClassifier(n_estimators=100)
rf_model.fit(train_features, train_labels)
rf_predictions = rf_model.predict(test_features)
Explanation:
Importing VGG16:
from keras.applications.vgg16 import VGG16: Imports the VGG16 model architecture pre-trained on ImageNet.
weights='imagenet': Loads pre-trained weights from ImageNet.
include_top=False: Excludes the fully connected layers at the top of the network, retaining only convolutional base for feature extraction.
input_shape=(224, 224, 3): Specifies the input shape matching the data generators.
Building the Feature Extraction Model:
x = base_model.output: Gets the output of the last layer of the base model.
x = GlobalAveragePooling2D()(x): Applies global average pooling to reduce each feature map to a single value, simplifying the feature representation.
feature_model = Model(inputs=base_model.input, outputs=x): Defines a new model that outputs the pooled features.
Extracting Features:
train_features = feature_model.predict(train_generator): Passes all training images through the feature extraction model to obtain feature vectors.
train_labels = train_generator.classes: Retrieves the labels corresponding to the training images.
Similarly, features and labels are extracted for the test set.
Training Classifiers:
Logistic Regression (lr_model):
max_iter=1000: Sets the maximum number of iterations for the solver to converge.
lr_model.fit(train_features, train_labels): Trains the model on the training features.
lr_predictions = lr_model.predict(test_features): Predicts labels for the test features.
Support Vector Machine (svm_model):
kernel='linear': Uses a linear kernel for classification.
probability=True: Enables probability estimates.
Trained and predictions made similarly to Logistic Regression.
Purpose:
To leverage a pre-trained convolutional neural network (VGG16) for feature extraction from images and then train traditional machine learning classifiers (Logistic Regression, SVM, Random Forest) on these features. This approach allows for effective classification without training a deep neural network from scratch.
precision: Proportion of positive identifications that were actually correct (TP / (TP + FP)).
npv (Negative Predictive Value): Proportion of negative identifications that were actually correct (TN / (TN + FN)).
f1: Harmonic mean of precision and recall.
fpr (False Positive Rate): Proportion of negatives incorrectly identified as positives (FP / (FP + TN)).
fnr (False Negative Rate): Proportion of positives incorrectly identified as negatives (FN / (FN + TP)).
Return: A dictionary containing all the computed metrics.
Evaluating Each Classifier:
lr_metrics, svm_metrics, rf_metrics: Stores evaluation metrics for Logistic Regression, SVM, and Random Forest respectively by calling evaluate_model with their predictions and true labels.
Printing Metrics:
Prints out the metrics for each classifier in a readable format.
Purpose:
To assess the performance of each classifier quantitatively using various evaluation metrics. This comprehensive evaluation helps in understanding the strengths and weaknesses of each model beyond just accuracy.
Cell In[34]: Enhanced Printing of Metrics
python
def print_metrics(model_name, metrics):
print(f"\n{model_name} Metrics:")
for metric, value in metrics.items():
print(f"{metric}: {value:.4f}")
# Evaluate each model and print metrics one by one
lr_metrics = evaluate_model(lr_predictions, test_labels)
svm_metrics = evaluate_model(svm_predictions, test_labels)
rf_metrics = evaluate_model(rf_predictions, test_labels)
print_metrics("Logistic Regression", lr_metrics)
print_metrics("SVM", svm_metrics)
print_metrics("Random Forest", rf_metrics)
Explanation:
Defining Enhanced Print Function (print_metrics):
Inputs:
model_name: Name of the model (e.g., "Logistic Regression").
Prints the model name followed by each metric formatted to four decimal places.
Re-Evaluating Models:
Recalculates lr_metrics, svm_metrics, and rf_metrics using evaluate_model.
Printing Metrics:
Calls print_metrics for each classifier to display metrics in a structured and readable format.
Purpose:
To present the evaluation metrics in a cleaner and more organized manner, making it easier to compare the performance of different classifiers.
Using Mock Data and Hardcoded Metrics for Demonstration
Cell In[7]: Creating a Mock Dataset and Training Classifiers with Hardcoded Metrics
Note: There seems to be a misnumbering of cells, as "In[7]" appears again. We'll treat this as a separate cell.
python
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix
# Load your dataset (assuming you've already set up your directory correctly)
# data = pd.read_csv('path_to_your_dataset.csv')
# For demonstration, let's create a mock dataset
np.random.seed(42)
data = pd.DataFrame({
'feature1': np.random.rand(1000),
'feature2': np.random.rand(1000),
'target': np.random.randint(0, 2, 1000) # Binary classification
})
# Define features and labels
X = data.drop(columns=['target'])
y = data['target']
# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Train Random Forest
rf_clf = RandomForestClassifier(n_estimators=100, random_state=42)
rf_clf.fit(X_train, y_train)
rf_preds = rf_clf.predict(X_test)
# Hardcoded metrics for Random Forest (as percentages)
rf_metrics = {
'Accuracy': 85.0,
'Precision': 80.0,
'Recall': 78.0,
'F1-Score': 79.0,
'Confusion Matrix': [[80, 10], [5, 75]]
}
# Print Random Forest metrics one by one as percentages
print("Random Forest Metrics:")
print(f"Accuracy: {rf_metrics['Accuracy']}%")
print(f"Precision: {rf_metrics['Precision']}%")
print(f"Recall: {rf_metrics['Recall']}%")
print(f"F1-Score: {rf_metrics['F1-Score']}%")
print("Confusion Matrix:")
print(rf_metrics['Confusion Matrix'])
print("\n" + "="*40 + "\n") # Separator
# Train Logistic Regression
lr_clf = LogisticRegression(random_state=42)
lr_clf.fit(X_train, y_train)
lr_preds = lr_clf.predict(X_test)
# Hardcoded metrics for Logistic Regression (as percentages)
lr_metrics = {
'Accuracy': 82.0,
'Precision': 76.0,
'Recall': 74.0,
'F1-Score': 75.0,
'Confusion Matrix': [[78, 12], [6, 74]]
}
# Print Logistic Regression metrics one by one as percentages
print("Logistic Regression Metrics:")
print(f"Accuracy: {lr_metrics['Accuracy']}%")
print(f"Precision: {lr_metrics['Precision']}%")
print(f"Recall: {lr_metrics['Recall']}%")
print(f"F1-Score: {lr_metrics['F1-Score']}%")
print("Confusion Matrix:")
print(lr_metrics['Confusion Matrix'])
print("\n" + "="*40 + "\n") # Separator
# Train Support Vector Machine (SVM)
svm_clf = SVC(random_state=42)
svm_clf.fit(X_train, y_train)
svm_preds = svm_clf.predict(X_test)
# Hardcoded metrics for SVM (as percentages)
svm_metrics = {
'Accuracy': 83.0,
'Precision': 79.0,
'Recall': 76.0,
'F1-Score': 77.0,
'Confusion Matrix': [[79, 11], [7, 73]]
}
# Print SVM metrics one by one as percentages
print("Support Vector Machine Metrics:")
print(f"Accuracy: {svm_metrics['Accuracy']}%")
print(f"Precision: {svm_metrics['Precision']}%")
print(f"Recall: {svm_metrics['Recall']}%")
print(f"F1-Score: {svm_metrics['F1-Score']}%")
print("Confusion Matrix:")
print(svm_metrics['Confusion Matrix'])
Explanation:
Importing Libraries:
Similar imports as before for data manipulation and machine learning.
Creating a Mock Dataset:
Seed for Reproducibility:
np.random.seed(42): Ensures that the random numbers generated are reproducible.
Dataframe Creation:
feature1 and feature2: Random float values between 0 and 1.
target: Random binary values (0 or 1) for binary classification.
Defining Features and Labels:
X: All columns except 'target'.
y: The 'target' column.
Splitting the Dataset:
train_test_split: Splits the data into training (80%) and testing (20%) sets.
random_state=42: Ensures reproducibility of the split.
Training Random Forest Classifier:
RandomForestClassifier(n_estimators=100, random_state=42): Initializes the classifier with 100 trees.
rf_clf.fit(...): Trains the classifier.
rf_preds = rf_clf.predict(...): Generates predictions on the test set.
Hardcoding Metrics for Random Forest:
Since this is a mock demonstration, metrics are hardcoded instead of being computed from actual predictions.
This includes Accuracy, Precision, Recall, F1-Score, and Confusion Matrix.
Printing Metrics:
Prints the metrics for Random Forest in a formatted manner.
Repeating the Process for Logistic Regression and SVM:
Logistic Regression:
Trains the model, generates predictions, hardcodes metrics, and prints them.
Support Vector Machine (SVM):
Same steps as above.
Purpose:
To demonstrate how different classifiers can be trained and evaluated on a dataset. However, since this is a mock dataset, the evaluation metrics are hardcoded for illustrative purposes. This section seems to serve as a template or placeholder for actual evaluation with real data.
Cell In[8]: Repeating Similar Mock Training with Additional Classifier (ResNet-101)
Again, cell numbering seems inconsistent.
python
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix
# Load your dataset (assuming you've already set up your directory correctly)
# data = pd.read_csv('path_to_your_dataset.csv')
# For demonstration, let's create a mock dataset
np.random.seed(42)
data = pd.DataFrame({
'feature1': np.random.rand(1000),
'feature2': np.random.rand(1000),
'target': np.random.randint(0, 2, 1000) # Binary classification
})
# Define features and labels
X = data.drop(columns=['target'])
y = data['target']
# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Train Random Forest
rf_clf = RandomForestClassifier(n_estimators=100, random_state=42)
rf_clf.fit(X_train, y_train)
rf_preds = rf_clf.predict(X_test)
# ResNet-101 (Dummy metrics since it requires model training and evaluation)
resnet_metrics = {
'Accuracy': 90,
'Precision': 85,
'Recall': 88,
'F1-Score': 86,
'Confusion Matrix': [[85, 5], [3, 77]]
}
# Print ResNet-101 metrics
print("ResNet-101 Metrics:")
print(f"Accuracy: {resnet_metrics['Accuracy']}%")
print(f"Precision: {resnet_metrics['Precision']}%")
print(f"Recall: {resnet_metrics['Recall']}%")
print(f"F1-Score: {resnet_metrics['F1-Score']}%")
print("Confusion Matrix:")
print(resnet_metrics['Confusion Matrix'])
Explanation:
Repeating the Mock Dataset Creation and Classifier Training:
Similar steps as in the previous cell: creating a dataset, splitting, training Random Forest, etc.
Adding ResNet-101 Metrics:
Since ResNet-101 is a deep learning model requiring substantial training time and resources, the metrics are hardcoded as dummy values.
Metrics include Accuracy, Precision, Recall, F1-Score, and Confusion Matrix.
Printing ResNet-101 Metrics:
Displays the dummy evaluation metrics for the ResNet-101 model.
Purpose:
To illustrate how metrics for a deep learning model like ResNet-101 would be handled alongside traditional classifiers. The hardcoded metrics simulate expected performance, acknowledging that actual training and evaluation would be more complex and time-consuming.
Visualizing Model Accuracies
Cell In[10]: Plotting Model Accuracies as a Line Plot
python
import numpy as np
import matplotlib.pyplot as plt
# Specified accuracies
models = ['Random Forest', 'Logistic Regression', 'SVM', 'ResNet-101']
accuracies = [0.85, 0.82, 0.84, 0.90] # Given accuracies in decimal
# Plotting
plt.figure(figsize=(10, 6))
plt.plot(models, accuracies, marker='o', linestyle='-', color='b')
# Annotating the accuracy values
for i, accuracy in enumerate(accuracies):
plt.text(i, accuracy + 0.01, f"{accuracy*100:.1f}%", ha='center')
plt.title('Model Accuracies')
plt.xlabel('Models')
plt.ylabel('Accuracy (%)')
plt.ylim(0.75, 1) # Set limits for y-axis for better visualization
plt.xticks(rotation=15)
plt.grid()
# Draw a horizontal line at y=0.8 for reference
plt.axhline(y=0.8, color='gray', linestyle='--', linewidth=0.5) # Example horizontal line
# Adjust x-axis limits to start from 0
plt.xlim(-0.5, len(models) - 0.5) # Set x limits based on number of models
plt.show()
Explanation:
Importing Libraries:
numpy and matplotlib.pyplot for numerical operations and plotting.
Defining Models and Their Accuracies:
models: List of model names.
accuracies: Corresponding accuracy values in decimal form (e.g., 0.85 represents 85%).
Creating the Plot:
plt.figure(figsize=(10, 6)): Initializes a new figure with specified size.
plt.plot(...): Plots the model accuracies as a line graph with:
marker='o': Circular markers at data points.
linestyle='-': Solid line connecting the markers.
color='b': Blue color for the line.
Annotating Accuracy Values:
Loops through each accuracy value and places a text label above the corresponding marker indicating the percentage.
Enhancing the Plot:
plt.title(...), plt.xlabel(...), plt.ylabel(...): Setting the title and axis labels.
plt.ylim(0.75, 1): Sets the y-axis limits to range from 75% to 100% for better visualization.
plt.xticks(rotation=15): Rotates x-axis labels by 15 degrees to prevent overlap.
plt.grid(): Adds grid lines to the plot for easier reading.
Adding Reference Line:
plt.axhline(...): Draws a horizontal dashed gray line at 80% accuracy as a benchmark.
Adjusting X-axis Limits:
plt.xlim(-0.5, len(models) - 0.5): Adjusts the x-axis to start slightly before the first model and end slightly after the last one, ensuring markers are well-placed.
Displaying the Plot:
plt.show(): Renders and displays the plot.
Purpose:
To visually compare the accuracies of different models, making it easier to identify which models perform better or worse relative to each other and a predefined benchmark.
Cell In[2]: Defining SE Block and Training Modified ResNet-101
There's a jump in cell numbering and a switch to defining a SE (Squeeze-and-Excitation) block.
python
def se_block(input_tensor, reduction=16):
filters = input_tensor.shape[-1] # Number of channels (filters)
se = layers.GlobalAveragePooling2D()(input_tensor) # Squeeze
se = layers.Reshape((1, 1, filters))(se) # Reshape to (1, 1, filters)
se = layers.Dense(filters // reduction, activation='relu')(se) # Reduce filters
se = layers.Dense(filters, activation='sigmoid')(se) # Scale
se = layers.multiply([input_tensor, se]) # Excitation
return se
Explanation:
Defining the SE (Squeeze-and-Excitation) Block Function:
Inputs:
input_tensor: Tensor from the previous layer.
reduction=16: Reduction ratio for channel dimensionality.
Implementation Steps:
Squeeze:
se = layers.GlobalAveragePooling2D()(input_tensor): Performs global average pooling to squeeze spatial dimensions, resulting in a tensor of shape (batch_size, channels).
Reshape:
se = layers.Reshape((1, 1, filters))(se): Reshapes the tensor to (batch_size, 1, 1, channels) for compatibility with convolutional layers.
Excitation:
se = layers.Dense(filters // reduction, activation='relu')(se): Reduces the number of channels by the reduction ratio and applies ReLU activation.
se = layers.Dense(filters, activation='sigmoid')(se): Restores the number of channels and applies sigmoid activation to obtain scaling factors between 0 and 1.
Scaling:
se = layers.multiply([input_tensor, se]): Multiplies the original input tensor with the scaling factors achieved through the SE block, effectively recalibrating channel-wise feature responses.
Return Value:
Returns the tensor after applying the SE block.
Purpose:
To enhance the representational power of the network by enabling it to perform dynamic channel-wise feature recalibration. The SE block helps the model focus on the most informative features, potentially improving performance.
Cell In[4]: Importing ResNet101
python
from tensorflow.keras.applications import ResNet101
Explanation:
Imports the ResNet101 model from TensorFlow Keras applications, which is a deep convolutional neural network with 101 layers.
Purpose:
To prepare for building a modified ResNet101 model that includes the SE block for enhanced performance in feature extraction.
Cell In[5]: Combining Imports and Defining the SE-modified ResNet101 Model
python
# Necessary imports
import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.applications import ResNet101
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Dense, GlobalAveragePooling2D, BatchNormalization
from tensorflow.keras.optimizers import Adam
from tensorflow.keras import layers
from tensorflow.keras.callbacks import ReduceLROnPlateau
# SE block function
def se_block(input_tensor, reduction=16):
filters = input_tensor.shape[-1] # Number of channels (filters)
se = layers.GlobalAveragePooling2D()(input_tensor) # Squeeze
se = layers.Reshape((1, 1, filters))(se) # Reshape to (1, 1, filters)
se = layers.Dense(filters // reduction, activation='relu')(se) # Reduce filters
se = layers.Dense(filters, activation='sigmoid')(se) # Scale
se = layers.multiply([input_tensor, se]) # Excitation
return se
# Load the base ResNet101 model
base_model = ResNet101(weights='imagenet', include_top=False, input_shape=(224, 224, 3))
# Modify the ResNet model
x = base_model.output # Extract the feature maps
# Apply SE block before pooling
x = se_block(x)
# Apply Global Average Pooling
x = GlobalAveragePooling2D()(x)
# Apply BatchNormalization (can also substitute with GroupNormalization if required)
x = BatchNormalization()(x)
# Final output layer for binary classification
predictions = Dense(1, activation='sigmoid')(x)
# Define the model
model = Model(inputs=base_model.input, outputs=predictions)
# Compile the model with an optimizer
optimizer = Adam(learning_rate=0.001)
model.compile(optimizer=optimizer, loss='binary_crossentropy', metrics=['accuracy'])
# Summary of the model
model.summary()
# Now you can train the model as before
history = model.fit(
train_generator,
epochs=10,
validation_data=validation_generator
)
# Evaluate the model
test_loss, test_accuracy = model.evaluate(test_generator)
print(f"ResNet-101 Modified Model Accuracy: {test_accuracy}")
Explanation:
Importing Necessary Modules:
Similar imports as before for building and training the model.
Defining the SE Block Function:
Repeats the se_block function defined earlier.
Loading the Base ResNet101 Model:
base_model = ResNet101(...): Loads the ResNet101 model without the top classification layers and with pre-trained ImageNet weights.
Modifying the ResNet101 Model:
x = base_model.output: Retrieves the output tensor from the ResNet101 base model.
x = se_block(x): Applies the SE block to the feature maps.
x = GlobalAveragePooling2D()(x): Further reduces the feature maps to a single vector per feature map.
x = BatchNormalization()(x): Normalizes the output to stabilize and accelerate training.
predictions = Dense(1, activation='sigmoid')(x): Adds a dense layer with a sigmoid activation for binary classification.
Defining and Compiling the Model:
model = Model(inputs=base_model.input, outputs=predictions): Defines the complete model with the ResNet101 base and the added layers.
optimizer = Adam(...): Initializes the Adam optimizer with a learning rate of 0.001.
model.compile(...): Compiles the model with the optimizer, binary cross-entropy loss, and accuracy as the metric.
Model Summary:
model.summary(): Prints a summary of the model architecture, including layers, output shapes, and parameter counts.
Training the Model:
model.fit(...): Trains the model using the training data generator for 10 epochs and validates on the validation data generator.
Evaluating the Model:
model.evaluate(test_generator): Evaluates the trained model on the test dataset, returning loss and accuracy.
print(...): Displays the test accuracy of the modified ResNet101 model.
Purpose:
To create and train a modified version of ResNet101 enhanced with an SE block for improved feature recalibration, aiming to achieve better performance in binary classification of chest X-ray images.
Cell In[6]: Simulating Metrics for Modified ResNet-101
Used to generate random numbers for simulating metrics.
Defining Function to Generate Simulated Metrics (generate_resnet_metrics):
Accuracy: Random float between 90% and 95%.
Precision: Random float between 85% and 90%.
Recall: Random float between 85% and 90%.
F1-Score: Calculated using the harmonic mean formula based on precision and recall.
Confusion Matrix: Generates a 2x2 matrix with random integers:
True Negatives (TN): 70 to 100.
False Positives (FP): 0 to 10.
False Negatives (FN): 0 to 10.
True Positives (TP): 70 to 100.
Generating and Printing Metrics:
resnet_metrics = generate_resnet_metrics(): Calls the function to obtain simulated metrics.
Prints the metrics in a structured format.
Purpose:
To simulate realistic evaluation metrics for the modified ResNet-101 model without performing an actual evaluation, possibly for demonstration or testing purposes.
Updating the Accuracy Plot with Modified ResNet-101
Cell In[13]: Adding Modified ResNet-101 to the Accuracy Plot
python
import numpy as np
import matplotlib.pyplot as plt
# Specified accuracies
models = ['Random Forest', 'Logistic Regression', 'SVM', 'ResNet-101','Modifyed ResNet-101']
accuracies = [0.85, 0.82, 0.84, 0.90,0.9244] # Given accuracies in decimal
# Plotting
plt.figure(figsize=(10, 6))
plt.plot(models, accuracies, marker='o', linestyle='-', color='b')
# Annotating the accuracy values
for i, accuracy in enumerate(accuracies):
plt.text(i, accuracy + 0.01, f"{accuracy*100:.1f}%", ha='center')
plt.title('Model Accuracies')
plt.xlabel('Models')
plt.ylabel('Accuracy (%)')
plt.ylim(0.75, 1) # Set limits for y-axis for better visualization
plt.xticks(rotation=15)
plt.grid()
# Draw a horizontal line at y=0.8 for reference
plt.axhline(y=0.8, color='gray', linestyle='--', linewidth=0.5) # Example horizontal line
# Adjust x-axis limits to start from 0
plt.xlim(-0.5, len(models) - 0.5) # Set x limits based on number of models
plt.show()
Explanation:
Importing Libraries:
numpy and matplotlib.pyplot for numerical operations and plotting.
Defining Models and Their Accuracies:
models: List of model names, including the newly added 'Modifyed ResNet-101' (likely a typo for "Modified").
accuracies: Corresponding accuracy values, with the modified ResNet-101 having an accuracy of 92.44%.
Creating the Plot:
Similar to the previous accuracy plot but now includes the modified ResNet-101.
Annotating Accuracy Values:
As before, each accuracy is labeled above its corresponding marker.
Enhancing the Plot:
Includes title, axis labels, y-axis limits, rotated x-axis labels, grid lines, and a horizontal reference line at 80% accuracy.
Adjusting X-axis Limits:
Ensures that all models are well-placed within the plot area.
Displaying the Plot:
plt.show(): Renders and displays the updated plot.
Purpose:
To visualize the improvement in accuracy achieved by the modified ResNet-101 model compared to other classifiers, illustrating its superior performance.
Cell In[14]: Plotting Model Accuracies as a Bar Graph
python
import matplotlib.pyplot as plt
# Specified accuracies
models = ['Random Forest', 'Logistic Regression', 'SVM', 'ResNet-101', 'Modified ResNet-101']
accuracies = [0.85, 0.82, 0.84, 0.90, 0.924] # Given accuracies in decimal
# Create the bar graph
plt.figure(figsize=(10, 6))
# Bar plot for the accuracies
plt.bar(models, accuracies, color='skyblue')
# Annotating the accuracy values on top of bars
for i, accuracy in enumerate(accuracies):
plt.text(i, accuracy + 0.01, f"{accuracy*100:.1f}%", ha='center')
# Adding title and labels
plt.title('Model Accuracies')
plt.xlabel('Models')
plt.ylabel('Accuracy (%)')
plt.ylim(0.75, 1) # Set limits for y-axis for better visualization
plt.xticks(rotation=15)
# Adding a horizontal reference line at 80%
plt.axhline(y=0.8, color='gray', linestyle='--', linewidth=0.5)
# Show the plot
plt.show()
Explanation:
Importing Libraries:
matplotlib.pyplot for plotting.
Defining Models and Their Accuracies:
models: List of model names, now corrected to 'Modified ResNet-101'.
accuracies: Corresponding accuracy values in decimal form.
Creating the Bar Graph:
plt.figure(figsize=(10, 6)): Initializes a new figure with specified size.
plt.bar(...): Creates a bar chart with:
models: Labels for the x-axis.
accuracies: Heights of the bars representing accuracy.
color='skyblue': Sets the color of the bars.
Annotating Accuracy Values:
Loops through each accuracy value and places a text label above the corresponding bar indicating the percentage.
Enhancing the Plot:
Sets the title and axis labels.
Rotates x-axis labels by 15 degrees for better readability.
Sets y-axis limits from 75% to 100% to focus on the relevant range.
Adds a horizontal dashed gray line at 80% accuracy as a benchmark.
Displaying the Plot:
plt.show(): Renders and displays the bar chart.
Purpose:
To provide an alternative visualization (bar graph) for comparing model accuracies, which can be more intuitive for some audiences compared to line plots.
Summary and Final Remarks
Throughout the provided code, you've built a comprehensive workflow for classifying chest X-ray images using both traditional machine learning classifiers and deep learning models. Here's a high-level overview of the steps involved:
Environment Setup: Import necessary libraries and verify data directories.
Data Exploration and Visualization: Assess the dataset's structure, class distribution, and visualize sample images and their pixel intensity distributions.
Data Preprocessing and Augmentation: Use ImageDataGenerator for real-time data augmentation to enhance model generalization.
Feature Extraction with Pre-trained Models: Utilize VGG16 (and later ResNet101) as feature extractors to obtain meaningful representations of images.
Training Traditional Classifiers: Train Logistic Regression, SVM, and Random Forest classifiers on the extracted features and evaluate their performance using various metrics.
Building and Training Deep Learning Models: Implement a modified ResNet101 with an SE block for improved feature recalibration, train it on the dataset, and evaluate its performance.
Visualization of Results: Plot the accuracies of different models using both line plots and bar charts for easy comparison.
Simulating Metrics: In some cells, you've demonstrated how to handle evaluation metrics, even using hardcoded or simulated values for illustrative purposes.
Recommendations and Best Practices:
Consistency in Directory Naming: Ensure that directory names are consistent (e.g., 'Pneumonia' vs. 'Pnemonia') to prevent potential bugs.
Avoid Redundant Imports: Streamline import statements to avoid repetition across cells, which can help in maintaining and reading the code.
Actual vs. Simulated Metrics: While dummy metrics are useful for demonstration, it's crucial to rely on actual evaluation metrics derived from model predictions for real-world applications.
Error Handling: Incorporate error handling when reading files or directories to manage scenarios where files might be missing or corrupted.
Model Saving and Loading: Implement mechanisms to save trained models for future inference without re-training.
Hyperparameter Tuning: Experiment with different hyperparameters for classifiers and neural networks to optimize performance further.
Cross-Validation: Use cross-validation techniques to obtain more robust estimates of model performance, especially if the dataset is limited.
Documentation: Add comments and documentation throughout the code to clarify the purpose of each section, making it more maintainable and understandable for others.
By following these steps and recommendations, you can build robust and efficient machine learning models for medical image classification tasks.