Certainly! You've already made significant progress in preprocessing your images and tabular data, performing data augmentation, and organizing your dataset into training, validation, and test splits. The next steps involve feature extraction from images, normalization of tabular data, and building a multimodal model that leverages both image and tabular data for osteoporosis classification.
Below is a comprehensive guide to completing your workflow, including detailed explanations and corresponding code snippets.
1. Overview of Next Steps
-
Feature Extraction from Images:
- Utilize a pre-trained Convolutional Neural Network (CNN) like EfficientNetB0 to extract deep features from images.
-
Normalization and Preparation of Tabular Data:
- Scale numerical features using techniques like
StandardScaler.
- Encode categorical variables if necessary.
-
Building the Multimodal Model:
- Combine image features and tabular data.
- Design a neural network that processes both modalities and performs classification.
-
Training and Evaluation:
- Train the model using the training set.
- Validate performance on the validation set.
- Evaluate final performance on the test set.
2. Import Necessary Libraries
Although you've already imported many libraries, ensure that all necessary ones for the subsequent steps are included.
import os
import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
import tensorflow as tf
from tensorflow.keras.applications import EfficientNetB0
from tensorflow.keras.models import Model, Model
from tensorflow.keras.layers import Input, Dense, Dropout, Concatenate, GlobalAveragePooling2D
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint
from tensorflow.keras.optimizers import Adam
import matplotlib.pyplot as plt
3. Load and Prepare the Data
3.1. Load CSV Files
Load the preprocessed CSV files for training, validation, and testing.
# Define paths to the CSV files
OUTPUT_DIR = '/content/gdrive/MyDrive/multimdal_osteoprosis_DATASET/final_images'
TRAIN_CSV = os.path.join(OUTPUT_DIR, 'train_data.csv')
VAL_CSV = os.path.join(OUTPUT_DIR, 'val_data.csv')
TEST_CSV = os.path.join(OUTPUT_DIR, 'test_data.csv')
# Load the datasets
train_df = pd.read_csv(TRAIN_CSV)
val_df = pd.read_csv(VAL_CSV)
test_df = pd.read_csv(TEST_CSV)
print(f"Train samples: {len(train_df)}")
print(f"Validation samples: {len(val_df)}")
print(f"Test samples: {len(test_df)}")
3.2. Data Inspection
Ensure that the data is correctly loaded and check for any anomalies.
# Display first few rows of the training data
print(train_df.head())
# Check for missing values
print(train_df.isnull().sum())
print(val_df.isnull().sum())
print(test_df.isnull().sum())
If there are missing values, you should handle them appropriately (e.g., imputation). For the sake of this guide, we'll assume there are no missing values.
4. Normalize Tabular Data
4.1. Identify Numerical and Categorical Features
From your preprocessing function, it seems you have the following features:
- Numerical Features:
Age, BMI
- Categorical Features:
Gender, Smoker, Diabetic, Daily Eating habits, Hypothyroidism, History of Fracture, Family History of Osteoporosis
4.2. Scaling Numerical Features
Use StandardScaler to normalize numerical features.
# Define numerical and categorical columns
numerical_features = ['Age', 'BMI']
categorical_features = ['Gender', 'Smoker', 'Diabetic',
'Daily Eating habits', 'Hypothyroidism',
'History of Fracture', 'Family History of Osteoporosis']
# Initialize the scaler
scaler = StandardScaler()
# Fit the scaler on training data
train_df[numerical_features] = scaler.fit_transform(train_df[numerical_features])
# Transform validation and test data
val_df[numerical_features] = scaler.transform(val_df[numerical_features])
test_df[numerical_features] = scaler.transform(test_df[numerical_features])
print("Numerical features scaled successfully.")
Note: If you have categorical variables that need encoding (e.g., one-hot encoding), you should handle them accordingly. However, since your categorical variables are already encoded as integers, and assuming they are ordinal or binary, you might not need additional encoding. If they are non-ordinal, consider using one-hot encoding.
5. Feature Extraction from Images
We'll use EfficientNetB0, a powerful CNN architecture, pre-trained on ImageNet, to extract features from your images. We'll remove the top layers and use the output of the last convolutional block as feature representations.
5.1. Define Image Parameters
# Image parameters
IMAGE_SIZE = (224, 224) # EfficientNetB0 expects at least 224x224
BATCH_SIZE = 32
5.2. Create Image Data Generators
Use ImageDataGenerator from Keras to preprocess images.
# Define data generators for training, validation, and testing
train_image_generator = ImageDataGenerator(
preprocessing_function=tf.keras.applications.efficientnet.preprocess_input,
horizontal_flip=True,
vertical_flip=True,
rotation_range=20,
zoom_range=0.2,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
fill_mode='nearest'
)
val_test_image_generator = ImageDataGenerator(
preprocessing_function=tf.keras.applications.efficientnet.preprocess_input
)
5.3. Create Image DataFrames with File Paths and Labels
Ensure that your CSV files contain the correct paths to images and their corresponding labels.
# Add full image paths to the DataFrames
train_df['image_path'] = train_df['Image Features'].apply(
lambda x: os.path.join(OUTPUT_DIR, 'train_images', x))
val_df['image_path'] = val_df['Image Features'].apply(
lambda x: os.path.join(OUTPUT_DIR, 'val_images', x))
test_df['image_path'] = test_df['Image Features'].apply(
lambda x: os.path.join(OUTPUT_DIR, 'test_images', x))
5.4. Create Data Generators
We'll use the flow_from_dataframe method to create generators that yield batches of images and corresponding labels.
# Define a helper function to create generators
def create_image_generator(df, generator):
return generator.flow_from_dataframe(
dataframe=df,
x_col='image_path',
y_col='Diagnosis',
target_size=IMAGE_SIZE,
color_mode='rgb',
class_mode='binary', # Assuming 'Diagnosis' is binary
batch_size=BATCH_SIZE,
shuffle=False # Important to set shuffle=False to keep data in order
)
# Create generators
train_image_gen = create_image_generator(train_df, train_image_generator)
val_image_gen = create_image_generator(val_df, val_test_image_generator)
test_image_gen = create_image_generator(test_df, val_test_image_generator)
Note: If your 'Diagnosis' column has more than two classes, adjust class_mode accordingly (e.g., categorical).
5.5. Load EfficientNetB0 Model for Feature Extraction
We'll load EfficientNetB0 without the top classification layers and use it as a feature extractor.
# Load EfficientNetB0 model without the top layers
base_model = EfficientNetB0(
include_top=False,
weights='imagenet',
input_shape=(IMAGE_SIZE[0], IMAGE_SIZE[1], 3),
pooling='avg' # Global Average Pooling
)
# Freeze the base model
base_model.trainable = False
print("EfficientNetB0 model loaded successfully.")
5.6. Extract Features
Instead of using a generator, we'll preprocess all images and extract features in batches.
def extract_features(generator, base_model, num_samples):
features = base_model.predict(generator, steps=np.ceil(num_samples / BATCH_SIZE), verbose=1)
return features
print("Extracting image features...")
train_features = extract_features(train_image_gen, base_model, len(train_df))
val_features = extract_features(val_image_gen, base_model, len(val_df))
test_features = extract_features(test_image_gen, base_model, len(test_df))
print("Image features extracted successfully.")
6. Prepare Tabular Data
6.1. Extract Tabular Features and Labels
Separate features and labels for each dataset split.
# Define feature columns (exclude 'image_path' and 'Diagnosis' from input features)
feature_columns = ['Gender', 'Age', 'Smoker', 'Diabetic',
'Daily Eating habits', 'Hypothyroidism',
'History of Fracture', 'Family History of Osteoporosis', 'BMI']
# Extract features and labels
X_train_tabular = train_df[feature_columns].values
X_val_tabular = val_df[feature_columns].values
X_test_tabular = test_df[feature_columns].values
y_train = train_df['Diagnosis'].values
y_val = val_df['Diagnosis'].values
y_test = test_df['Diagnosis'].values
print("Tabular data prepared successfully.")
Note: Ensure that the 'Diagnosis' column is binary (0 and 1). If not, convert it accordingly.
7. Combine Image and Tabular Features
Since we have already extracted the image features using EfficientNetB0, we can now combine these with the tabular data.
7.1. Concatenate Features
# Concatenate image features and tabular features
X_train_combined = np.concatenate([train_features, X_train_tabular], axis=1)
X_val_combined = np.concatenate([val_features, X_val_tabular], axis=1)
X_test_combined = np.concatenate([test_features, X_test_tabular], axis=1)
print("Image and tabular features combined successfully.")
print(f"Combined training features shape: {X_train_combined.shape}")
print(f"Combined validation features shape: {X_val_combined.shape}")
print(f"Combined test features shape: {X_test_combined.shape}")
8. Build the Multimodal Neural Network Model
Design a neural network that takes the combined features as input and outputs the classification.
8.1. Define the Model Architecture
from tensorflow.keras.layers import BatchNormalization, Activation
# Define input shape
input_shape = X_train_combined.shape[1]
# Define the model
model = Sequential([
Dense(512, input_shape=(input_shape,)),
BatchNormalization(),
Activation('relu'),
Dropout(0.5),
Dense(256),
BatchNormalization(),
Activation('relu'),
Dropout(0.5),
Dense(128),
BatchNormalization(),
Activation('relu'),
Dropout(0.5),
Dense(1, activation='sigmoid') # Binary classification
])
model.summary()
Alternative Approach: Alternatively, you can create a more customized model by separately processing image and tabular features before combining them. However, since we've already concatenated the features, a simple dense network suffices.
8.2. Compile the Model
Choose an appropriate loss function, optimizer, and evaluation metrics.
# Compile the model
model.compile(
optimizer=Adam(learning_rate=1e-4),
loss='binary_crossentropy',
metrics=['accuracy']
)
print("Model compiled successfully.")
9. Train the Model
9.1. Define Callbacks
Use callbacks like EarlyStopping and ModelCheckpoint to prevent overfitting and save the best model.
# Define callbacks
early_stop = EarlyStopping(
monitor='val_loss',
patience=10,
restore_best_weights=True
)
checkpoint = ModelCheckpoint(
filepath=os.path.join(OUTPUT_DIR, 'best_model.h5'),
monitor='val_loss',
save_best_only=True
)
9.2. Train the Model
# Train the model
history = model.fit(
X_train_combined,
y_train,
epochs=100,
batch_size=BATCH_SIZE,
validation_data=(X_val_combined, y_val),
callbacks=[early_stop, checkpoint],
verbose=1
)
print("Model training completed.")
10. Evaluate the Model
10.1. Plot Training History
Visualize the training and validation loss and accuracy over epochs.
# Plot training & validation accuracy and loss values
def plot_history(history):
# Accuracy
plt.figure(figsize=(14,6))
plt.subplot(1,2,1)
plt.plot(history.history['accuracy'], label='Train Accuracy')
plt.plot(history.history['val_accuracy'], label='Validation Accuracy')
plt.title('Model Accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(loc='lower right')
# Loss
plt.subplot(1,2,2)
plt.plot(history.history['loss'], label='Train Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.title('Model Loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(loc='upper right')
plt.show()
plot_history(history)
10.2. Load the Best Model
Ensure that you're evaluating the best model saved during training.
# Load the best saved model
best_model = tf.keras.models.load_model(os.path.join(OUTPUT_DIR, 'best_model.h5'))
10.3. Evaluate on Test Data
Evaluate the model's performance on the test set.
# Evaluate on test data
test_loss, test_accuracy = best_model.evaluate(X_test_combined, y_test, verbose=1)
print(f"Test Loss: {test_loss:.4f}")
print(f"Test Accuracy: {test_accuracy:.4f}")
10.4. Classification Report and Confusion Matrix
Generate detailed classification metrics.
from sklearn.metrics import classification_report, confusion_matrix
# Predict probabilities
y_pred_prob = best_model.predict(X_test_combined)
# Convert probabilities to class labels
y_pred = (y_pred_prob > 0.5).astype(int).flatten()
# Classification Report
print("Classification Report:")
print(classification_report(y_test, y_pred))
# Confusion Matrix
cm = confusion_matrix(y_test, y_pred)
plt.figure(figsize=(6,4))
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues')
plt.xlabel('Predicted')
plt.ylabel('Actual')
plt.title('Confusion Matrix')
plt.show()
Note: Ensure that you have seaborn installed for better visualization of the confusion matrix.
# Install seaborn if not already installed
!pip install seaborn
import seaborn as sns
11. Save the Final Model
After evaluation, save the model for future use.
# Save the final model
final_model_path = os.path.join(OUTPUT_DIR, 'final_multimodal_model.h5')
best_model.save(final_model_path)
print(f"Final model saved to {final_model_path}")
12. (Optional) Fine-Tuning the Base Model
If you wish to improve performance and have sufficient computational resources, consider unfreezing some layers of the EfficientNetB0 base model and fine-tuning.
# Unfreeze the base model
base_model.trainable = True
# Fine-tune from this layer onwards
fine_tune_at = 100 # Adjust based on experimentation
# Freeze all layers before the 'fine_tune_at' layer
for layer in base_model.layers[:fine_tune_at]:
layer.trainable = False
# Recompile the model with a lower learning rate
model.compile(
optimizer=Adam(learning_rate=1e-5),
loss='binary_crossentropy',
metrics=['accuracy']
)
# Continue training
fine_tune_epochs = 20
total_epochs = len(history.history['loss']) + fine_tune_epochs
history_fine = model.fit(
X_train_combined,
y_train,
epochs=fine_tune_epochs,
initial_epoch=history.epoch[-1],
validation_data=(X_val_combined, y_val),
callbacks=[early_stop, checkpoint],
verbose=1
)
# Plot the combined training history
plt.figure(figsize=(14,6))
plt.subplot(1,2,1)
plt.plot(history.history['accuracy'] + history_fine.history['accuracy'], label='Train Accuracy')
plt.plot(history.history['val_accuracy'] + history_fine.history['val_accuracy'], label='Validation Accuracy')
plt.title('Model Accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(loc='lower right')
plt.subplot(1,2,2)
plt.plot(history.history['loss'] + history_fine.history['loss'], label='Train Loss')
plt.plot(history.history['val_loss'] + history_fine.history['val_loss'], label='Validation Loss')
plt.title('Model Loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(loc='upper right')
plt.show()
Note: Fine-tuning requires careful monitoring to avoid overfitting. Adjust fine_tune_at and fine_tune_epochs based on validation performance.
Conclusion
You've successfully:
- Preprocessed and Augmented Images: Applied various image augmentation techniques to enhance your dataset.
- Processed Tabular Data: Cleaned and normalized numerical features.
- Extracted Image Features: Utilized EfficientNetB0 to extract deep features from images.
- Combined Features: Merged image and tabular features into a unified representation.
- Built and Trained a Multimodal Model: Designed a neural network that leverages both image and tabular data for classification.
- Evaluated the Model: Assessed model performance using various metrics and visualization techniques.
With this setup, your multimodal model should be well-equipped to classify osteoporosis based on both image and tabular data. Remember to experiment with different architectures, hyperparameters, and feature extraction techniques to further enhance performance.
Good luck with your project! If you encounter any issues or have further questions, feel free to ask.