Python Project - Breast Cancer Classification with Deep Learning
Posted by Superadmin on August 22 2020 11:29:19

Python Project - Breast Cancer Classification with Deep Learning

BY  · UPDATED · AUGUST 6, 2020

 

If you want to master Python programming language then you can’t skip projects in Python. After publishing 4 advanced python projects, DataFlair today came with another one that is the Breast Cancer Classification project in Python. To crack your next Python Interview, practice these projects thoroughly and if you face any confusion, do comment, DataFlair is always ready to help you.

 

 

Breast Cancer Classification Project in Python

Get aware with the terms used in Breast Cancer Classification project in Python

 

What is Deep Learning?

An intensive approach to Machine Learning, Deep Learning is inspired by the workings of the human brain and its biological neural networks. Architectures as deep neural networks, recurrent neural networks, convolutional neural networks, and deep belief networks are made of multiple layers for the data to pass through before finally producing the output. Deep Learning serves to improve AI and make many of its applications possible; it is applied to many such fields of computer vision, speech recognition, natural language processing, audio recognition, and drug design.

What is Keras?

Keras is an open-source neural-network library written in Python. It is a high-level API and can run on top of TensorFlow, CNTK, and Theano. Keras is all about enabling fast experimentation and prototyping while running seamlessly on CPU and GPU. It is user-friendly, modular, and extensible.

Breast Cancer Classification – Objective

To build a breast cancer classifier on an IDC dataset that can accurately classify a histology image as benign or malignant.

Breast Cancer Classification – About the Python Project

In this project in python, we’ll build a classifier to train on 80% of a breast cancer histology image dataset. Of this, we’ll keep 10% of the data for validation. Using Keras, we’ll define a CNN (Convolutional Neural Network), call it CancerNet, and train it on our images. We’ll then derive a confusion matrix to analyze the performance of the model.

IDC is Invasive Ductal Carcinoma; cancer that develops in a milk duct and invades the fibrous or fatty breast tissue outside the duct; it is the most common form of breast cancer forming 80% of all breast cancer diagnoses. And histology is the study of the microscopic structure of tissues.

The Dataset

We’ll use the IDC_regular dataset (the breast cancer histology image dataset) from Kaggle. This dataset holds 2,77,524 patches of size 50×50 extracted from 162 whole mount slide images of breast cancer specimens scanned at 40x. Of these, 1,98,738 test negative and 78,786 test positive with IDC. The dataset is available in public domain and you can download it here. You’ll need a minimum of 3.02GB of disk space for this.

Filenames in this dataset look like this:

8863_idx5_x451_y1451_class0

Here, 8863_idx5 is the patient ID, 451 and 1451 are the x- and y- coordinates of the crop, and 0 is the class label (0 denotes absence of IDC).

Prerequisites

You’ll need to install some python packages to be able to run this advanced python project. You can do this with pip-

  1. pip install numpy opencv-python pillow tensorflow keras imutils scikit-learn matplotlib

Steps for Advanced Project in Python – Breast Cancer Classification

 

1. Download this zip. Unzip it at your preferred location, get there.

Screenshot:

breast cancer detection python project

 

2. Now, inside the inner breast-cancer-classification directory, create directory datasets- inside this, create directory original:

  1. mkdir datasets
  2. mkdir datasets\original

 

3. Download the dataset.

 

 

4. Unzip the dataset in the original directory. To observe the structure of this directory, we’ll use the tree command:

  1. cd breast-cancer-classification\breast-cancer-classification\datasets\original
  2. tree

Output Screenshot:

original structure project in python

We have a directory for each patient ID. And in each such directory, we have the 0 and 1 directories for images with benign and malignant content.

config.py:

This holds some configuration we’ll need for building the dataset and training the model. You’ll find this in the cancernet directory.

  1. import os
  2.  
  3. INPUT_DATASET = "datasets/original" 
  4.  
  5. BASE_PATH = "datasets/idc" 
  6. TRAIN_PATH = os.path.sep.join([BASE_PATH, "training"]) 
  7. VAL_PATH = os.path.sep.join([BASE_PATH, "validation"]) 
  8. TEST_PATH = os.path.sep.join([BASE_PATH, "testing"]) 
  9.  
  10. TRAIN_SPLIT = 0.8 
  11. VAL_SPLIT = 0.1

Screenshot:

breast cancer classification - python project

Here, we declare the path to the input dataset (datasets/original), that for the new directory (datasets/idc), and the paths for the training, validation, and testing directories using the base path. We also declare that 80% of the entire dataset will be used for training, and of that, 10% will be used for validation.

build_dataset.py:

This will split our dataset into training, validation, and testing sets in the ratio mentioned above- 80% for training (of that, 10% for validation) and 20% for testing. With the ImageDataGenerator from Keras, we will extract batches of images to avoid making space for the entire dataset in memory at once.

  1. from cancernet import config
  2. from imutils import paths
  3. import random, shutil, os
  4.  
  5. originalPaths=list(paths.list_images(config.INPUT_DATASET)) 
  6. random.seed(7) 
  7. random.shuffle(originalPaths)
  8. index=int(len(originalPaths)*config.TRAIN_SPLIT)
  9. trainPaths=originalPaths[:index]
  10. testPaths=originalPaths[index:]
  11. index=int(len(trainPaths)*config.VAL_SPLIT)
  12. valPaths=trainPaths[:index]
  13. trainPaths=trainPaths[index:]
  14. datasets=[("training", trainPaths, config.TRAIN_PATH),
  15. ("validation", valPaths, config.VAL_PATH),
  16. ("testing", testPaths, config.TEST_PATH)
  17. ]
  18. for (setType, originalPaths, basePath) in datasets:
  19. print(f'Building {setType} set')
  20. if not os.path.exists(basePath):
  21. print(f'Building directory {base_path}')
  22. os.makedirs(basePath)
  23. for path in originalPaths:
  24. file=path.split(os.path.sep)[-1]
  25. label=file[-5:-4]
  26. labelPath=os.path.sep.join([basePath,label])
  27. if not os.path.exists(labelPath):
  28. print(f'Building directory {labelPath}')
  29. os.makedirs(labelPath)
  30. newPath=os.path.sep.join([labelPath, file])
  31. shutil.copy2(inputPath, newPath)

Screenshot:

python machine learning project

In this, we’ll import from config, imutils, random, shutil, and os. We’ll build a list of original paths to the images, then shuffle the list. Then, we calculate an index by multiplying the length of this list by 0.8 so we can slice this list to get sublists for the training and testing datasets. Next, we further calculate an index saving 10% of the list for the training dataset for validation and keeping the rest for training itself.

Now, datasets is a list with tuples for information about the training, validation, and testing sets. These hold the paths and the base path for each. For each setType, path, and base path in this list, we’ll print, say, ‘Building testing set’. If the base path does not exist, we’ll create the directory. And for each path in originalPaths, we’ll extract the filename and the class label. We’ll build the path to the label directory(0 or 1)- if it doesn’t exist yet, we’ll explicitly create this directory. Now, we’ll build the path to the resulting image and copy the image here- where it belongs.

 

 

5. Run the script build_dataset.py:

  1. py build_dataset.py

Output Screenshot:
build dataset

cancernet.py:

The network we’ll build will be a CNN (Convolutional Neural Network) and call it CancerNet. This network performs the following operations:

  1. from keras.models import Sequential
  2. from keras.layers.normalization import BatchNormalization
  3. from keras.layers.convolutional import SeparableConv2D
  4. from keras.layers.convolutional import MaxPooling2D
  5. from keras.layers.core import Activation
  6. from keras.layers.core import Flatten
  7. from keras.layers.core import Dropout
  8. from keras.layers.core import Dense
  9. from keras import backend as K
  10. class CancerNet:
  11. @staticmethod
  12. def build(width,height,depth,classes):
  13. model=Sequential()
  14. shape=(height,width,depth)
  15. channelDim=-1
  16. if K.image_data_format()=="channels_first":
  17. shape=(depth,height,width)
  18. channelDim=1
  19. model.add(SeparableConv2D(32, (3,3), padding="same",input_shape=shape))
  20. model.add(Activation("relu"))
  21. model.add(BatchNormalization(axis=channelDim))
  22. model.add(MaxPooling2D(pool_size=(2,2)))
  23. model.add(Dropout(0.25))
  24. model.add(SeparableConv2D(64, (3,3), padding="same"))
  25. model.add(Activation("relu"))
  26. model.add(BatchNormalization(axis=channelDim))
  27. model.add(SeparableConv2D(64, (3,3), padding="same"))
  28. model.add(Activation("relu"))
  29. model.add(BatchNormalization(axis=channelDim))
  30. model.add(MaxPooling2D(pool_size=(2,2)))
  31. model.add(Dropout(0.25))
  32. model.add(SeparableConv2D(128, (3,3), padding="same"))
  33. model.add(Activation("relu"))
  34. model.add(BatchNormalization(axis=channelDim))
  35. model.add(SeparableConv2D(128, (3,3), padding="same"))
  36. model.add(Activation("relu"))
  37. model.add(BatchNormalization(axis=channelDim))
  38. model.add(SeparableConv2D(128, (3,3), padding="same"))
  39. model.add(Activation("relu"))
  40. model.add(BatchNormalization(axis=channelDim))
  41. model.add(MaxPooling2D(pool_size=(2,2)))
  42. model.add(Dropout(0.25))
  43. model.add(Flatten())
  44. model.add(Dense(256))
  45. model.add(Activation("relu"))
  46. model.add(BatchNormalization())
  47. model.add(Dropout(0.5))
  48. model.add(Dense(classes))
  49. model.add(Activation("softmax"))
  50. return model

Screenshot:

cancernet CNN python mini project

Screenshot:

cancernet CNN interesting python project

We use the Sequential API to build CancerNet and SeparableConv2D to implement depthwise convolutions. The class CancerNet has a static method build that takes four parameters- width and height of the image, its depth (the number of color channels in each image), and the number of classes the network will predict between, which, for us, is 2 (0 and 1).

In this method, we initialize model and shape. When using channels_first, we update the shape and the channel dimension.

Now, we’ll define three DEPTHWISE_CONV => RELU => POOL layers; each with a higher stacking and a greater number of filters. The softmax classifier outputs prediction percentages for each class. In the end, we return the model.

train_model.py:

This trains and evaluates our model. Here, we’ll import from keras, sklearn, cancernet, config, imutils, matplotlib, numpy, and os.

  1. import matplotlib
  2. matplotlib.use("Agg")
  3. from keras.preprocessing.image import ImageDataGenerator
  4. from keras.callbacks import LearningRateScheduler
  5. from keras.optimizers import Adagrad
  6. from keras.utils import np_utils
  7. from sklearn.metrics import classification_report
  8. from sklearn.metrics import confusion_matrix
  9. from cancernet.cancernet import CancerNet
  10. from cancernet import config
  11. from imutils import paths
  12. import matplotlib.pyplot as plt
  13. import numpy as np
  14. import os
  15. NUM_EPOCHS=40; INIT_LR=1e-2; BS=32
  16. trainPaths=list(paths.list_images(config.TRAIN_PATH))
  17. lenTrain=len(trainPaths)
  18. lenVal=len(list(paths.list_images(config.VAL_PATH)))
  19. lenTest=len(list(paths.list_images(config.TEST_PATH)))
  20. trainLabels=[int(p.split(os.path.sep)[-2]) for p in trainPaths]
  21. trainLabels=np_utils.to_categorical(trainLabels)
  22. classTotals=trainLabels.sum(axis=0)
  23. classWeight=classTotals.max()/classTotals
  24. trainAug = ImageDataGenerator(
  25. rescale=1/255.0,
  26. rotation_range=20,
  27. zoom_range=0.05,
  28. width_shift_range=0.1,
  29. height_shift_range=0.1,
  30. shear_range=0.05,
  31. horizontal_flip=True,
  32. vertical_flip=True,
  33. fill_mode="nearest")
  34. valAug=ImageDataGenerator(rescale=1 / 255.0)
  35. trainGen = trainAug.flow_from_directory(
  36. config.TRAIN_PATH,
  37. class_mode="categorical",
  38. target_size=(48,48),
  39. color_mode="rgb",
  40. shuffle=True,
  41. batch_size=BS)
  42. valGen = valAug.flow_from_directory(
  43. config.VAL_PATH,
  44. class_mode="categorical",
  45. target_size=(48,48),
  46. color_mode="rgb",
  47. shuffle=False,
  48. batch_size=BS)
  49. testGen = valAug.flow_from_directory(
  50. config.TEST_PATH,
  51. class_mode="categorical",
  52. target_size=(48,48),
  53. color_mode="rgb",
  54. shuffle=False,
  55. batch_size=BS)
  56. model=CancerNet.build(width=48,height=48,depth=3,classes=2)
  57. opt=Adagrad(lr=INIT_LR,decay=INIT_LR/NUM_EPOCHS)
  58. model.compile(loss="binary_crossentropy",optimizer=opt,metrics=["accuracy"])
  59. M=model.fit_generator(
  60. trainGen,
  61. steps_per_epoch=lenTrain//BS,
  62. validation_data=valGen,
  63. validation_steps=lenVal//BS,
  64. class_weight=classWeight,
  65. epochs=NUM_EPOCHS)
  66. print("Now evaluating the model")
  67. testGen.reset()
  68. pred_indices=model.predict_generator(testGen,steps=(lenTest//BS)+1)
  69. pred_indices=np.argmax(pred_indices,axis=1)
  70. print(classification_report(testGen.classes, pred_indices, target_names=testGen.class_indices.keys()))
  71. cm=confusion_matrix(testGen.classes,pred_indices)
  72. total=sum(sum(cm))
  73. accuracy=(cm[0,0]+cm[1,1])/total
  74. specificity=cm[1,1]/(cm[1,0]+cm[1,1])
  75. sensitivity=cm[0,0]/(cm[0,0]+cm[0,1])
  76. print(cm)
  77. print(f'Accuracy: {accuracy}')
  78. print(f'Specificity: {specificity}')
  79. print(f'Sensitivity: {sensitivity}')
  80. N = NUM_EPOCHS
  81. plt.style.use("ggplot")
  82. plt.figure()
  83. plt.plot(np.arange(0,N), M.history["loss"], label="train_loss")
  84. plt.plot(np.arange(0,N), M.history["val_loss"], label="val_loss")
  85. plt.plot(np.arange(0,N), M.history["acc"], label="train_acc")
  86. plt.plot(np.arange(0,N), M.history["val_acc"], label="val_acc")
  87. plt.title("Training Loss and Accuracy on the IDC Dataset")
  88. plt.xlabel("Epoch No.")
  89. plt.ylabel("Loss/Accuracy")
  90. plt.legend(loc="lower left")
  91. plt.savefig('plot.png')

Screenshot:

python open source projects

Screenshot:

intermediate python projects

Screenshot:

python project example

In this script, first, we set initial values for the number of epochs, the learning rate, and the batch size. We’ll get the number of paths in the three directories for training, validation, and testing. Then, we’ll get the class weight for the training data so we can deal with the imbalance.

Now, we initialize the training data augmentation object. This is a process of regularization that helps generalize the model. This is where we slightly modify the training examples to avoid the need for more training data. We’ll initialize the validation and testing data augmentation objects.

We’ll initialize the training, validation, and testing generators so they can generate batches of images of size batch_size. Then, we’ll initialize the model using the Adagrad optimizer and compile it with a binary_crossentropy loss function. Now, to fit the model, we make a call to fit_generator().

We have successfully trained our model. Now, let’s evaluate the model on our testing data. We’ll reset the generator and make predictions on the data. Then, for images from the testing set, we get the indices of the labels with the corresponding largest predicted probability. And we’ll display a classification report.

Now, we’ll compute the confusion matrix and get the raw accuracy, specificity, and sensitivity, and display all values. Finally, we’ll plot the training loss and accuracy.

Output Screenshot:

learning python projects

Output Screenshot:

advanced python projects

Output:

Python project with source code

Summary

In this project in python, we learned to build a breast cancer classifier on the IDC dataset (with histology images for Invasive Ductal Carcinoma) and created the network CancerNet for the same. We used Keras to implement the same. Hope you enjoyed this Python project.