The Wayback Machine - https://web.archive.org/web/20240903162610/https://www.geeksforgeeks.org/lung-cancer-detection-using-transfer-learning/
Open In App

Lung Cancer Detection Using Transfer Learning

Last Updated : 17 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Computer Vision is one of the applications of deep neural networks that enables us to automate tasks that earlier required years of expertise and one such use in predicting the presence of cancerous cells.

In this article, we will learn how to build a classifier using the Transfer Learning technique which can classify normal lung tissues from cancerous. This project has been developed using collab and the dataset has been taken from Kaggle whose link has been provided as well.

Transfer Learning

In a convolutional neural network, the main task of the convolutional layers is to enhance the important features of an image. If a particular filter is used to identify the straight lines in an image then it will work for other images as well this is particularly what we do in transfer learning. There are models which are developed by researchers by regress hyperparameter tuning and training for weeks on millions of images belonging to 1000 different classes like imagenet dataset. A model that works well for one computer vision task proves to be good for others as well. Because of this reason, we leverage those trained convolutional layers parameters and tuned hyperparameter for our task to obtain higher accuracy.

Importing Libraries

Python libraries make it very easy for us to handle the data and perform typical and complex tasks with a single line of code.

  • Pandas – This library helps to load the data frame in a 2D array format and has multiple functions to perform analysis tasks in one go.
  • Numpy – Numpy arrays are very fast and can perform large computations in a very short time.
  • Matplotlib – This library is used to draw visualizations.
  • Sklearn – This module contains multiple libraries having pre-implemented functions to perform tasks from data preprocessing to model development and evaluation.
  • OpenCV – This is an open-source library mainly focused on image processing and handling.
  • Tensorflow – This is an open-source library that is used for Machine Learning and Artificial intelligence and provides a range of functions to achieve complex functionalities with single lines of code.

Python3




import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from PIL import Image
from glob import glob
  
from sklearn.model_selection import train_test_split
from sklearn import metrics
  
import cv2
import gc
import os
  
import tensorflow as tf
from tensorflow import keras
from keras import layers
  
import warnings
warnings.filterwarnings('ignore')


Importing Dataset

This dataset includes 5000 images for three classes of lung conditions:

  • Normal Class
  • Lung Adenocarcinomas
  • Lung Squamous Cell Carcinomas

These images for each class have been developed from 250 images by performing Data Augmentation on them. That is why we won’t be using Data Augmentation further on these images.

Python3




from zipfile import ZipFile
data_path = 'lung-and-colon-cancer-histopa\
thological-images.zip'
  
with ZipFile(data_path,'r') as zip:
  zip.extractall()
  print('The data set has been extracted.')


Output:

The data set has been extracted.

Data Visualization

In this section, we will try to understand visualize some images which have been provided to us to build the classifier for each class.

Python3




path = '/lung_colon_image_set/lung_image_sets'
classes = os.listdir(path)
classes


Output:

['lung_n', 'lung_aca', 'lung_scc']

These are the three classes that we have here.

Python3




path = '/lung_colon_image_set/lung_image_sets'
  
for cat in classes:
    image_dir = f'{path}/{cat}'
    images = os.listdir(image_dir)
  
    fig, ax = plt.subplots(1, 3, figsize = (15, 5))
    fig.suptitle(f'Images for {cat} category . . . .', 
                 fontsize = 20)
  
    for i in range(3):
        k = np.random.randint(0, len(images))
        img = np.array(Image.open(f'{path}/{cat}/{images[k]}'))
        ax[i].imshow(img)
        ax[i].axis('off')
    plt.show()


Output:

Images for lung_n category

Images for lung_n category

Images for lung_aca category

Images for lung_aca category

Images for lung_scc category

Images for lung_scc category

The above output may vary if you will run this in your notebook because the code has been implemented in such a way that it will show different images every time you rerun the code.

Data Preparation for Training

In this section, we will convert the given images into NumPy arrays of their pixels after resizing them because training a Deep Neural Network on large-size images is highly inefficient in terms of computational cost and time.

For this purpose, we will use the OpenCV library and Numpy library of python to serve the purpose. Also, after all the images are converted into the desired format we will split them into training and validation data so, that we can evaluate the performance of our model.

Python3




IMG_SIZE = 256
SPLIT = 0.2
EPOCHS = 10
BATCH_SIZE = 64


Some of the hyperparameters we can tweak from here for the whole notebook.

Python3




X = []
Y = []
  
for i, cat in enumerate(classes):
  images = glob(f'{path}/{cat}/*.jpeg')
  
  for image in images:
    img = cv2.imread(image)
      
    X.append(cv2.resize(img, (IMG_SIZE, IMG_SIZE)))
    Y.append(i)
  
X = np.asarray(X)
one_hot_encoded_Y = pd.get_dummies(Y).values


One hot encoding will help us to train a model which can predict soft probabilities of an image being from each class with the highest probability for the class to which it really belongs.

Python3




X_train, X_val, Y_train, Y_val = train_test_split(
  X, one_hot_encoded_Y, test_size = SPLIT, random_state = 2022)
print(X_train.shape, X_val.shape)


Output:

(12000, 256, 256, 3) (3000, 256, 256, 3)

In this step, we will achieve the shuffling of the data automatically because the train_test_split function split the data randomly in the given ratio.

Model Development

We will use pre-trained weight for an Inception network which is trained on imagenet dataset. This dataset contains millions of images for around 1000 classes of images.

Model Architecture

We will implement a model using the  Functional API of Keras which will contain the following parts:

  • The base model is the Inception model in this case.
  • The Flatten layer flattens the output of the base model’s output.
  • Then we will have two fully connected layers followed by the output of the flattened layer.
  • We have included some BatchNormalization layers to enable stable and fast training and a Dropout layer before the final layer to avoid any possibility of overfitting.
  • The final layer is the output layer which outputs soft probabilities for the three classes. 

Python3




from tensorflow.keras.applications.inception_v3 import InceptionV3
  
pre_trained_model = InceptionV3(
    input_shape = (IMG_SIZE, IMG_SIZE, 3),
    weights = 'imagenet',
    include_top = False
)


Output:

87916544/87910968 [==============================] – 2s 0us/step

87924736/87910968 [==============================] – 2s 0us/step

Python3




len(pre_trained_model.layers)


Output:

311

This is how deep this model is this also justifies why this model is highly effective in extracting useful features from images which helps us to build classifiers.

The parameters of a model we import are already trained on millions of images and for weeks so, we do not need to train them again.

Python3




for layer in pre_trained_model.layers:
  layer.trainable = False


‘Mixed7’ is one of the layers in the inception network whose outputs we will use to build the classifier.

Python3




last_layer = pre_trained_model.get_layer('mixed7')
print('last layer output shape: ', last_layer.output_shape)
last_output = last_layer.output


Output:

last layer output shape:  (None, 14, 14, 768)

Python3




x = layers.Flatten()(last_output)
  
x = layers.Dense(256,activation='relu')(x)
x = layers.BatchNormalization()(x)
  
x = layers.Dense(128,activation='relu')(x)
x = layers.Dropout(0.3)(x)
x = layers.BatchNormalization()(x)
  
output = layers.Dense(3, activation='softmax')(x)
  
model = keras.Model(pre_trained_model.input, output)


While compiling a model we provide these three essential parameters:

  • optimizer – This is the method that helps to optimize the cost function by using gradient descent.
  • loss – The loss function by which we monitor whether the model is improving with training or not.
  • metrics – This helps to evaluate the model by predicting the training and the validation data.

Python3




model.compile(
    optimizer='adam',
    loss='categorical_crossentropy',
    metrics=['accuracy']
)


Callback

Callbacks are used to check whether the model is improving with each epoch or not. If not then what are the necessary steps to be taken like ReduceLROnPlateau decreases the learning rate further? Even then if model performance is not improving then training will be stopped by EarlyStopping. We can also define some custom callbacks to stop training in between if the desired results have been obtained early.

Python3




from keras.callbacks import EarlyStopping, ReduceLROnPlateau
  
class myCallback(tf.keras.callbacks.Callback):
  def on_epoch_end(self, epoch, logs = {}):
    if logs.get('val_accuracy') > 0.90:
      print('\n Validation accuracy has reached upto 90%\
      so, stopping further training.')
      self.model.stop_training = True
  
es = EarlyStopping(patience = 3,
                   monitor = 'val_accuracy',
                   restore_best_weights = True)
  
lr = ReduceLROnPlateau(monitor = 'val_loss',
                       patience = 2,
                       factor = 0.5,
                       verbose = 1)


Now we will train our model:

Python3




history = model.fit(X_train, Y_train,
                    validation_data = (X_val, Y_val),
                    batch_size = BATCH_SIZE,
                    epochs = EPOCHS,
                    verbose = 1,
                    callbacks = [es, lr, myCallback()])


Output:

Model training progress

Model training progress

Let’s visualize the training and validation accuracy with each epoch.

Python3




history_df = pd.DataFrame(history.history)
history_df.loc[:,['loss','val_loss']].plot()
history_df.loc[:,['accuracy','val_accuracy']].plot()
plt.show()


Output:

Graph of loss and accuracy epoch by epoch for training and validation data.loss

Graph of loss and accuracy epoch by epoch for training and validation data.loss

From the above graphs, we can certainly say that the model has not overfitted the training data as the difference between the training and validation accuracy is very low.

Model Evaluation

Now as we have our model ready let’s evaluate its performance on the validation data using different metrics. For this purpose, we will first predict the class for the validation data using this model and then compare the output with the true labels.

Python3




Y_pred = model.predict(X_val)
  
Y_val = np.argmax(Y_val, axis=1)
Y_pred = np.argmax(Y_pred, axis=1)


Let’s draw the confusion metrics and classification report using the predicted labels and the true labels.

Python3




metrics.confusion_matrix(Y_val, Y_pred)


Output:

Confusion matrix for the validation data

Confusion matrix for the validation data

Python3




print(metrics.classification_report(Y_val, Y_pred,
                                    target_names=classes))


Output:

Classification report for the validation data

Classification report for the validation data

Conclusion: Indeed the performance of our model using the Transfer Learning Technique has achieved higher accuracy without overfitting which is very good as the f1-score for each class is also above 0.90 which means our model’s prediction is correct 90% of the time.



Previous Article
Next Article

Similar Reads

Lung Cancer Detection using Convolutional Neural Network (CNN)
Computer Vision is one of the applications of deep neural networks that enables us to automate tasks that earlier required years of expertise and one such use in predicting the presence of cancerous cells. In this article, we will learn how to build a classifier using a simple Convolution Neural Network which can classify normal lung tissues from c
8 min read
Skin Cancer Detection using TensorFlow
In this article, we will learn how to implement a Skin Cancer Detection model using Tensorflow. We will use a dataset that contains images for the two categories that are malignant or benign. We will use the transfer learning technique to achieve better results in less amount of training. We will use EfficientNet architecture as the backbone of our
5 min read
Real-Time Edge Detection using OpenCV in Python | Canny edge detection method
Edge detection is one of the fundamental image-processing tasks used in various Computer Vision tasks to identify the boundary or sharp changes in the pixel intensity. It plays a crucial role in object detection, image segmentation and feature extraction from the image. In Real-time edge detection, the image frame coming from a live webcam or video
5 min read
ML | Cancer cell classification using Scikit-learn
Machine Learning is a sub-field of Artificial Intelligence that gives systems the ability to learn themselves without being explicitly programmed to do so. Machine Learning can be used in solving many real world problems. Let's classify cancer cells based on their features, and identifying them if they are 'malignant' or 'benign'. We will be using
10 min read
Breast Cancer predictions using catboost
CatBoost is a gradient boosting algorithm that deals with the categorical features during the training process. In the article, we are going to perform prediction analysis on breast cancer dataset using CatBoost. Breast Cancer Detection using CatBoost We aim to provide a comprehensive pipeline for training a CatBoostClassifier model on the Breast C
7 min read
ML | Kaggle Breast Cancer Wisconsin Diagnosis using Logistic Regression
Dataset:It is given by Kaggle from UCI Machine Learning Repository, in one of its challenge. It is a dataset of Breast Cancer patients with Malignant and Benign tumor. Logistic Regression is used to predict whether the given patient is having Malignant or Benign tumor based on the attributes in the given dataset. Code : Loading Libraries C/C++ Code
5 min read
ML | Kaggle Breast Cancer Wisconsin Diagnosis using KNN and Cross Validation
Dataset : It is given by Kaggle from UCI Machine Learning Repository, in one of its challenges. It is a dataset of Breast Cancer patients with Malignant and Benign tumor. K-nearest neighbour algorithm is used to predict whether is patient is having cancer (Malignant tumour) or not (Benign tumour). Implementation of KNN algorithm for classification.
3 min read
Dog Breed Classification using Transfer Learning
In this article, we will learn how to build a classifier using the Transfer Learning technique which can classify among different breeds of dogs. This project has been developed using collab and the dataset has been taken from Kaggle whose link has been provided as well. Transfer Learning In a convolutional neural network, the main task of the conv
8 min read
Transfer learning & fine-tuning using Keras
Transfer learning is a powerful technique used in deep learning tasks. Here, a model developed for a particular task is reused as a starting point for a model on the second task. Thus, transfer learning uses the knowledge gained from a pre-trained model and allows faster convergence with better performance, especially when the data is limited. On t
7 min read
Multiclass image classification using Transfer learning
Image classification is one of the supervised machine learning problems which aims to categorize the images of a dataset into their respective categories or labels. Classification of images of various dog breeds is a classic image classification problem. So, we have to classify more than one class that's why the name multi-class classification, and
8 min read
Comparing anomaly detection algorithms for outlier detection on toy datasets in Scikit Learn
Anomaly is a deviation from the expected or normal behavior or pattern. Anomaly detection is the process of identifying these unusual patterns or behaviors in data. It is important because anomalies can indicate important events or problems, such as fraudulent activity, equipment failure, or security breaches. Anomaly detection is used in a variety
9 min read
Sobel Edge Detection vs. Canny Edge Detection in Computer Vision
Both Sobel and Canny algorithms are popular methods for edge detection in images, but they are suited for different purposes based on their characteristics and the nature of the application. Understanding when to use each can help you achieve better results for specific tasks in image processing. In this article, we are going to explore the differe
9 min read
Leukaemia Cell Classification For Paediatric Cancer Diagnosis
In the world of children's cancer, especially leukaemia, our focus is on using the latest technology to help battle pediatric cancer. We are using deep learning techniques to build a model that will increase the precision with which medical professionals identify childhood leukaemia. Leukaemia Cell Classification For Paediatric Cancer DiagnosisWhat
11 min read
Breast Cancer Wisconsin (Diagnostic) Dataset
The Breast Cancer Wisconsin (Diagnostic) dataset is a renowned collection of data used extensively in machine learning and medical research. Originating from digitized images of fine needle aspirates (FNA) of breast masses, this dataset facilitates the analysis of cell nuclei characteristics to aid in the diagnosis of breast cancer. In this article
6 min read
Can Artificial Intelligence Help in Curing Cancer?
What would happen if your own body turned against you? That is the question cancer patients have to deal with. Cancer is basically just a mutation of the normal body cells into tumor cells that can eventually kill the patient. In fact, Cancer is the second leading cause of death globally with an estimated 9.6 million deaths in 2018 only. And the un
6 min read
Deep Transfer Learning - Introduction
Deep transfer learning is a machine learning technique that utilizes the knowledge learned from one task to improve the performance of another related task. This technique is particularly useful when there is a shortage of labeled data for the target task, as it allows the model to leverage the knowledge learned from a similar task with a larger da
8 min read
What Is the Difference Between Fine-Tuning and Transfer-Learning?
Answer: Fine-tuning adapts a pre-trained model on a specific task with modest changes, while transfer learning employs knowledge gained from a pre-trained model to enhance performance on a different but related task.Fine Tuning vs Transfer Learning: ComparisonAspectFine-TuningTransfer LearningObjectiveAdapt pre-trained model to a specific new taskL
1 min read
What Are the Consequences of Not Freezing Layers in Transfer Learning?
Answer: Not freezing layers in transfer learning can lead to the loss of valuable pre-trained knowledge and may result in overfitting to the new dataset.When not freezing layers in transfer learning, several consequences may arise: Loss of Pre-trained Knowledge: The primary purpose of transfer learning is to leverage knowledge learned from a source
2 min read
Transfer Learning with Fine-tuning
Transfer learning is a machine learning approach that involves utilizing pre-trained models to address specific tasks. The knowledge acquired from one task is utilized to enhance the performance on a related task. In natural language processing, transfer learning techniques have revolutionized the way language models are developed. For example, kno
9 min read
ML | Transfer Learning with Convolutional Neural Networks
Transfer learning as a general term refers to reusing the knowledge learned from one task for another. Specifically for convolutional neural networks (CNNs), many image features are common to a variety of datasets (e.g. lines, edges are seen in almost every image). It is for this reason that, especially for large structures, CNNs are very rarely tr
7 min read
How to implement transfer learning in PyTorch?
What is Transfer Learning?Transfer learning is a technique in deep learning where a pre-trained model on a large dataset is reused as a starting point for a new task. This approach significantly reduces training time and improves performance, especially when dealing with limited datasets. It is very popular in computer vision and natural language p
15+ min read
Transfer Learning for Computer Vision
Transfer learning is a powerful technique in the field of computer vision, where a pre-trained model on a large dataset is fine-tuned for a different but related task. This approach leverages the knowledge gained from the initial training to improve performance and reduce training time for the new task. Here’s an overview of transfer learning for c
7 min read
What is Transfer Learning?
We, humans, are very good at applying the transfer of knowledge between tasks. This means that whenever we encounter a new problem or a task. Similarly Transfer learning is a smart method in machine learning where a model uses knowledge from one task to help with a different, but related, task. Instead of learning from zero, the model uses what it
12 min read
Enhancing Natural Language Processing with Transfer Learning: Techniques, Models, and Applications
Transfer learning in NLP involves utilizing pre-trained models on large text corpora and adapting them to specific language tasks. This technique harnesses the model's pre-acquired linguistic knowledge, significantly reducing the data and computational effort required for new tasks. This article aims to explore the concept of transfer learning, pre
12 min read
Transfer Learning in NLP
Transfer learning is an important tool in natural language processing (NLP) that helps build powerful models without needing massive amounts of data. This article explains what transfer learning is, why it's important in NLP, and how it works. Table of Content Why Transfer Learning is important in NLP?Benefits of Transfer Learning in NLP tasksHow D
15+ min read
Explain the concept of transfer learning and its application in computer vision.
Transfer learning is a machine learning technique where a model developed for a particular task is reused as the starting point for a model on a second task. This approach is particularly effective in fields where labelled data is scarce, allowing the transfer of knowledge from a domain with abundant data to a domain with limited data. Transfer lea
9 min read
Tumor Detection using classification - Machine Learning and Python
In this article, we will be making a project through Python language which will be using some Machine Learning Algorithms too. It will be an exciting one as after this project you will understand the concepts of using AI & ML with a scripting language. The following libraries/packages will be used in this project: numpy: It's a Python library t
9 min read
Age Detection using Deep Learning in OpenCV
In this tutorial, we are going to see the entire process of creating an Age predictor and Gender classifier project using OpenCV. Age Detection Our goal here is to create a program that will predict the gender and age of the person using an image. But predicting age might not be as simple as you think, why? You might be thinking that age prediction
5 min read
Fake News Detection using Machine Learning
Fake news on different platforms is spreading widely and is a matter of serious concern, as it causes social wars and permanent breakage of the bonds established among people. A lot of research is already going on focused on the classification of fake news. Here we will try to solve this issue with the help of machine learning in Python. Before sta
4 min read
Hate Speech Detection using Deep Learning
There must be times when you have come across some social media post whose main aim is to spread hate and controversies or use abusive language on social media platforms. As the post consists of textual information to filter out such Hate Speeches NLP comes in handy. This is one of the main applications of NLP which is known as Sentence Classificat
7 min read