Nur E Jannat PrachurjaWalley Erfan KhanTariq AhamedRafa
Published © LGPL

Early Lung Cancer detection using Deep learning

A project to detect lung cancer(which is quite hard to diagnose before the final stage) at an early stage by applying CNN on HRCT.

IntermediateWork in progressOver 17 days159
Early Lung Cancer detection using Deep learning

Things used in this project

Hardware components

AMD Ryzen AI-powered PC
×1

Software apps and online services

VS Code
Microsoft VS Code
MySQL
Microsoft 365

Story

Read more

Code

Training CNN for detection and evaluating the performance

Python
The code given below is for building the CNN model using PyTorch for the task of early lung cancer detection from medical images.
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, Dataset
import torchvision.transforms as transforms


class LungCancerCNN(nn.Module):
    def __init__(self):
        super(LungCancerCNN, self).__init__()
        self.conv1 = nn.Conv2d(in_channels=1, out_channels=32, kernel_size=3, padding=1)
        self.conv2 = nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, padding=1)
        self.pool = nn.MaxPool2d(kernel_size=2, stride=2)
        self.fc1 = nn.Linear(64 * 56 * 56, 128)
        self.fc2 = nn.Linear(128, 2)  

    def forward(self, x):
        x = self.pool(torch.relu(self.conv1(x)))
        x = self.pool(torch.relu(self.conv2(x)))
        x = x.view(-1, 64 * 56 * 56) 
        x = torch.relu(self.fc1(x))
        x = self.fc2(x)
        return x


class LungCancerDataset(Dataset):
    def __init__(self, data, targets, transform=None):
        self.data = data
        self.targets = targets
        self.transform = transform

    def __len__(self):
        return len(self.data)

    def __getitem__(self, index):
        sample = self.data[index]
        target = self.targets[index]

        if self.transform:
            sample = self.transform(sample)

        return sample, target


train_dataset = LungCancerDataset(train_data, train_targets, transform=transforms.ToTensor())
test_dataset = LungCancerDataset(test_data, test_targets, transform=transforms.ToTensor())

train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=64, shuffle=False)


model = LungCancerCNN()
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)


num_epochs = 10
for epoch in range(num_epochs):
    model.train()
    for images, labels in train_loader:
        optimizer.zero_grad()
        outputs = model(images)
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()
    print(f'Epoch [{epoch+1}/{num_epochs}], Loss: {loss.item()}')


model.eval()
correct = 0
total = 0
with torch.no_grad():
    for images, labels in test_loader:
        outputs = model(images)
        _, predicted = torch.max(outputs.data, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()

accuracy = 100 * correct / total
print(f'Accuracy on test set: {accuracy}%')

Database

MySQL
CREATE DATABASE IF NOT EXISTS lung_cancer_detection;

USE lung_cancer_detection;


CREATE TABLE IF NOT EXISTS Patients (
    PatientID INT PRIMARY KEY AUTO_INCREMENT,
    FirstName VARCHAR(50) NOT NULL,
    LastName VARCHAR(50) NOT NULL,
    Age INT,
    Gender ENUM('Male', 'Female', 'Other'),
    SSN CHAR(9),
    Pseudonym VARCHAR(100) NOT NULL,
    Address VARBINARY(255),
    PasswordHash VARBINARY(64),

    AccessLevel ENUM('Admin', 'Doctor', 'Nurse', 'Technician') DEFAULT 'Doctor',
    UNIQUE(Pseudonym)
);


CREATE TABLE IF NOT EXISTS ImagingData (
    ImageID INT PRIMARY KEY AUTO_INCREMENT,
    PatientID INT,
    ImagePath VARCHAR(255) NOT NULL,
    Diagnosis ENUM('Healthy', 'Cancerous'),
    AccessLevel ENUM('Admin', 'Doctor') DEFAULT 'Doctor',
    FOREIGN KEY (PatientID) REFERENCES Patients(PatientID)
);


CREATE TABLE IF NOT EXISTS Predictions (
    PredictionID INT PRIMARY KEY AUTO_INCREMENT,
    ImageID INT,
    Prediction ENUM('Healthy', 'Cancerous'),
    Confidence FLOAT,
    AccessLevel ENUM('Admin', 'Doctor') DEFAULT 'Doctor',
    FOREIGN KEY (ImageID) REFERENCES ImagingData(ImageID)
);


CREATE TABLE IF NOT EXISTS AccessLogs (
    LogID INT PRIMARY KEY AUTO_INCREMENT,
    UserID INT,
    Timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    Action VARCHAR(100) NOT NULL,
    FOREIGN KEY (UserID) REFERENCES Patients(PatientID)
);

Metrics Assessment

Python
import torch
from torch.utils.data import DataLoader
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score


true_labels = []
predicted_labels = []


model.eval()


torch.set_grad_enabled(False)


for images, labels in test_loader:
    outputs = model(images)
    _, predicted = torch.max(outputs, 1)
    
   
    true_labels.extend(labels.numpy())
    predicted_labels.extend(predicted.numpy())


accuracy = accuracy_score(true_labels, predicted_labels)
precision = precision_score(true_labels, predicted_labels)
recall = recall_score(true_labels, predicted_labels)
f1 = f1_score(true_labels, predicted_labels)


print("Accuracy:", accuracy)
print("Precision:", precision)
print("Recall:", recall)
print("F1-score:", f1)

Deployment

Python
from flask import Flask, request, jsonify
import torch
import torchvision.transforms as transforms
from PIL import Image
from io import BytesIO
import numpy as np
from model import LungCancerCNN 

app = Flask(__name__)


model = LungCancerCNN()
model.load_state_dict(torch.load("lung_cancer_model.pth", map_location=torch.device('cpu')))  
model.eval()


preprocess = transforms.Compose([
    transforms.Grayscale(num_output_channels=1),  
    transforms.Resize((224, 224)), 
    transforms.ToTensor(),  
])


class_labels = {0: 'Healthy', 1: 'Cancerous'}

@app.route("/predict", methods=["POST"])
def predict():
    
    file = request.files["image"]
    
    
    image_pil = Image.open(file)
    
    
    image_tensor = preprocess(image_pil).unsqueeze(0)  
    
   
    with torch.no_grad():
        outputs = model(image_tensor)
        _, predicted = torch.max(outputs, 1)
        class_label = class_labels[predicted.item()]
    
    return jsonify({"prediction": class_label})

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000)

Credits

Nur E Jannat Prachurja

Nur E Jannat Prachurja

1 project • 1 follower
I'm currently an undergrad student from Data science
Walley Erfan Khan

Walley Erfan Khan

2 projects • 8 followers
Engineer, developer, Inventor, Maker & Hacker.
Tariq Ahamed

Tariq Ahamed

0 projects • 2 followers
Passionate Data Scientist: Python, ML, predictive analytics expert. Insight from vast data.
Rafa

Rafa

0 projects • 1 follower
Rafa, mech. engineer ⚙️ passionate about #AI building a better future - she/her #STEM #diversity.
Thanks to .

Comments