Brain Tumor Detection and Classification from MRI Using Graph Neural Network code
- User
Brain Tumor Detection and Classification from MRI Using Graph Neural Network code
- Assistant
Brain Tumor Detection and Classification from MRI Using Graph Neural Network code
Certainly! Detecting and classifying brain tumors from MRI images using Graph Neural Networks (GNNs) is a sophisticated task that involves combining concepts from medical image processing and graph-based deep learning. Below, I'll provide a step-by-step guide along with example code snippets to help you implement this project using Python, PyTorch, and PyTorch Geometric (a library tailored for graph deep learning).
torch-geometric)Data Preparation
Graph Construction
Model Building
Training and Evaluation
Visualization and Interpretation
Load and Preprocess MRI Images
Start by loading your dataset of MRI images. If you don't have a dataset, you can use publicly available datasets like the Brain Tumor Segmentation (BraTS) dataset.
import os
import numpy as np
from PIL import Image
from sklearn.model_selection import train_test_split
# Directory containing images and labels
image_dir = 'path_to_images/'
label_file = 'path_to_labels.csv'
# Load image paths and labels
image_paths = []
labels = []
# Assuming labels are in a CSV file with 'image' and 'label' columns
import pandas as pd
label_df = pd.read_csv(label_file)
for idx, row in label_df.iterrows():
image_paths.append(os.path.join(image_dir, row['image']))
labels.append(row['label'])
Preprocess Images
from torchvision import transforms
# Define transformations
transform = transforms.Compose([
transforms.Resize((128, 128)),
transforms.ToTensor(), # Converts to [C x H x W] tensor and normalizes to [0, 1]
])
# Load and preprocess images
processed_images = []
for img_path in image_paths:
img = Image.open(img_path).convert('L') # Convert to grayscale
img = transform(img)
processed_images.append(img)
Split Data
X_train, X_test, y_train, y_test = train_test_split(
processed_images, labels, test_size=0.2, random_state=42)
Define Nodes and Edges
To use GNNs, we need to represent images as graphs.
Approach: Use superpixels to reduce computational complexity.
import torch
from torch_geometric.data import Data
from skimage.segmentation import slic
def create_graph(img_tensor, n_segments=250, compactness=10):
# Convert tensor to numpy array
img_np = img_tensor.numpy().squeeze()
# Apply SLIC superpixel segmentation
segments = slic(img_np, n_segments=n_segments, compactness=compactness)
# Get features for each superpixel
segment_ids = np.unique(segments)
num_nodes = len(segment_ids)
features = []
positions = []
for seg_id in segment_ids:
mask = segments == seg_id
pixel_values = img_np[mask]
# Use mean intensity as a feature
mean_intensity = np.mean(pixel_values)
features.append([mean_intensity])
# Use centroid as node position
coords = np.column_stack(np.nonzero(mask))
centroid = np.mean(coords, axis=0)
positions.append(centroid)
features = torch.tensor(features, dtype=torch.float)
positions = np.array(positions)
# Define edges based on proximity
from sklearn.neighbors import NearestNeighbors
nbrs = NearestNeighbors(n_neighbors=8, algorithm='ball_tree').fit(positions)
distances, indices = nbrs.kneighbors(positions)
edge_index = []
for idx, neighbors in enumerate(indices):
for neighbor in neighbors:
if idx != neighbor:
edge_index.append([idx, neighbor])
edge_index = torch.tensor(edge_index, dtype=torch.long).t().contiguous()
data = Data(x=features, edge_index=edge_index)
return data
Process All Images into Graphs
train_graphs = []
for img_tensor in X_train:
graph = create_graph(img_tensor)
train_graphs.append(graph)
test_graphs = []
for img_tensor in X_test:
graph = create_graph(img_tensor)
test_graphs.append(graph)
Add Labels to Graphs
for i, graph in enumerate(train_graphs):
graph.y = torch.tensor([y_train[i]], dtype=torch.long)
for i, graph in enumerate(test_graphs):
graph.y = torch.tensor([y_test[i]], dtype=torch.long)
Define the GNN Model
import torch.nn.functional as F
from torch_geometric.nn import GCNConv, TopKPooling, global_mean_pool
class BrainTumorGNN(torch.nn.Module):
def __init__(self, num_classes):
super(BrainTumorGNN, self).__init__()
self.conv1 = GCNConv(1, 64)
self.pool1 = TopKPooling(64, ratio=0.8)
self.conv2 = GCNConv(64, 128)
self.pool2 = TopKPooling(128, ratio=0.8)
self.fc1 = torch.nn.Linear(128*2, 256)
self.fc2 = torch.nn.Linear(256, num_classes)
def forward(self, data):
x, edge_index, batch = data.x, data.edge_index, data.batch
x = F.relu(self.conv1(x, edge_index))
x, edge_index, _, batch, _, _ = self.pool1(x, edge_index, None, batch)
x1 = torch.cat([global_mean_pool(x, batch), global_mean_pool(x, batch)], dim=1)
x = F.relu(self.conv2(x, edge_index))
x, edge_index, _, batch, _, _ = self.pool2(x, edge_index, None, batch)
x2 = torch.cat([global_mean_pool(x, batch), global_mean_pool(x, batch)], dim=1)
x = x1 + x2 # Combine representations
x = F.relu(self.fc1(x))
x = F.dropout(x, p=0.5, training=self.training)
x = self.fc2(x)
return F.log_softmax(x, dim=1)
Initialize the Model
num_classes = len(set(labels))
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = BrainTumorGNN(num_classes).to(device)
Prepare Data Loaders
from torch_geometric.data import DataLoader
batch_size = 16
train_loader = DataLoader(train_graphs, batch_size=batch_size, shuffle=True)
test_loader = DataLoader(test_graphs, batch_size=batch_size, shuffle=False)
Define Optimizer and Loss Function
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
criterion = torch.nn.NLLLoss()
Training Loop
def train():
model.train()
total_loss = 0
for data in train_loader:
data = data.to(device)
optimizer.zero_grad()
out = model(data)
loss = criterion(out, data.y)
loss.backward()
optimizer.step()
total_loss += loss.item() * data.num_graphs
return total_loss / len(train_loader.dataset)
Evaluation Function
def evaluate(loader):
model.eval()
correct = 0
total = 0
all_preds = []
all_labels = []
with torch.no_grad():
for data in loader:
data = data.to(device)
out = model(data)
pred = out.argmax(dim=1)
correct += (pred == data.y).sum().item()
total += data.num_graphs
all_preds.extend(pred.cpu().numpy())
all_labels.extend(data.y.cpu().numpy())
accuracy = correct / total
return accuracy, all_preds, all_labels
Run Training
num_epochs = 50
for epoch in range(1, num_epochs+1):
loss = train()
train_acc, _, _ = evaluate(train_loader)
test_acc, _, _ = evaluate(test_loader)
print(f'Epoch {epoch}, Loss: {loss:.4f}, Train Acc: {train_acc:.4f}, Test Acc: {test_acc:.4f}')
Plot Confusion Matrix
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
_, test_preds, test_labels = evaluate(test_loader)
cm = confusion_matrix(test_labels, test_preds)
disp = ConfusionMatrixDisplay(confusion_matrix=cm)
disp.plot()
Visualize Graph Example
import networkx as nx
from torch_geometric.utils import to_networkx
# Get a sample graph
sample_graph = test_graphs[0]
G = to_networkx(sample_graph, to_undirected=True)
pos = {i: sample_graph.pos[i].numpy() for i in range(sample_graph.num_nodes)}
plt.figure(figsize=(8, 8))
nx.draw(G, pos=pos, node_color=sample_graph.x.squeeze(), cmap='viridis', with_labels=False)
plt.show()
GATConv (Graph Attention Network) or GraphSAGE.Implementing brain tumor detection and classification using GNNs is a complex task that bridges medical imaging and advanced graph-based machine learning. By representing MRI images as graphs, you can capture spatial relationships and structural information that traditional CNNs might overlook.
Remember to carefully preprocess your data and understand the nature of your dataset. Validate your models thoroughly, and consider collaborating with medical professionals to interpret the results meaningfully.
If you have further questions or need clarification on any of the steps, feel free to ask!
Not yet included in a published release.