Skin Cancer Classification with Machine Learning

skin cancer classification

Skin Cancer is one of the most common types of disease in the United States. Up to 4 Million cases have been reported dead due to skin cancer in the United States over the year. In this article, I will create a model for skin cancer classification with Machine Learning.

This is a huge number, really 4 million, people died just from Skin cancer in a country. As all those people have been dying, but half of those cases or maybe even more, didn’t have went to the doctor at the early stages of the disease when it might have been prevented.

If people are getting the symptoms of skin cancer, they still don’t reach out for a doctor, which is not a good signal because skin cancer can be cured at the early stages.

Also, read – Naive Bayes Classification with Machine Learning

Skin Cancer Classification with Machine Learning

So this is where a machine learning algorithm works in the classification of Skin Cancer. As I mentioned earlier Skin Cancer can be easily cured in the early stages of the disease, but it’s the people who don’t want to visit the doctor.

So here is a simple machine learning algorithm, which can help those people to identify if they are having skin cancer or not while sitting at their homes. This Machine Learning algorithm is based on Convolutional Neural Networks (CNN).

CNN Layers Classification for Skin Cancer Detection

Lets start with importing the libraries

import numpy as np
from skimage import io
import matplotlib.pyplot as pltCode language: Python (python)

Now I will simply upload images to train our machine learning model using the skimage library in python.

imgb = io.imread('bimg-1049.png')
imgm = io.imread('mimg-178.png')
imgb = io.imread('bimg-721.png')
imgm = io.imread('mimg-57.png')Code language: Python (python)

You can download these images from below

These images are sample images of Benign mole and Malign mole which are a type of skin problems.

Let’s visualize these images

plt.figure(figsize=(10,20))
plt.subplot(121)
plt.imshow(imgb)
plt.axis('off')
plt.subplot(122)
plt.imshow(imgm)
plt.axis('off')Code language: Python (python)
skin cancer

Now lets train our model for further classification

from keras.models import load_model
model = load_model('BM_VA_VGG_FULL_DA.hdf5')

from keras import backend as K

def activ_viewer(model, layer_name, im_put):
    layer_dict = dict([(layer.name, layer) for layer in model.layers])
    layer = layer_dict[layer_name]
    activ1 = K.function([model.layers[0].input, K.learning_phase()], [layer.output,])
    activations = activ1((im_put, False))
    return activations

def normalize(x):
    # utility function to normalize a tensor by its L2 norm
    return x / (K.sqrt(K.mean(K.square(x))) + 1e-5)

def deprocess_image(x):
    # normalize tensor: center on 0., ensure std is 0.1
    x -= x.mean()
    x /= (x.std() + 1e-5)
    x *= 0.1

    # clip to [0, 1]
    x += 0.5
    x = np.clip(x, 0, 1)

    # convert to RGB array
    x *= 255
    if K.image_data_format() == 'channels_first':
        x = x.transpose((1, 2, 0))
    x = np.clip(x, 0, 255).astype('uint8')
    return x

def plot_filters(filters):
    newimage = np.zeros((16*filters.shape[0],8*filters.shape[1]))
    for i in range(filters.shape[2]):
        y = i%8
        x = i//8
        newimage[x*filters.shape[0]:x*filters.shape[0]+filters.shape[0],
                 y*filters.shape[1]:y*filters.shape[1]+filters.shape[1]] = filters[:,:,i]
    plt.figure(figsize = (10,20))
    plt.imshow(newimage)
    plt.axis('off')Code language: Python (python)
layer_dict = dict([(layer.name, layer) for layer in model.layers])Code language: Python (python)

Skin Cancer Classification Model Summary

To see the summary of our trained model we will execute the code below

model.summary()Code language: Python (python)
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
input_1 (InputLayer)         (None, 128, 128, 3)       0         
_________________________________________________________________
block1_conv1 (Conv2D)        (None, 128, 128, 64)      1792      
_________________________________________________________________
block1_conv2 (Conv2D)        (None, 128, 128, 64)      36928     
_________________________________________________________________
block1_pool (MaxPooling2D)   (None, 64, 64, 64)        0         
_________________________________________________________________
block2_conv1 (Conv2D)        (None, 64, 64, 128)       73856     
_________________________________________________________________
block2_conv2 (Conv2D)        (None, 64, 64, 128)       147584    
_________________________________________________________________
block2_pool (MaxPooling2D)   (None, 32, 32, 128)       0         
_________________________________________________________________
block3_conv1 (Conv2D)        (None, 32, 32, 256)       295168    
_________________________________________________________________
block3_conv2 (Conv2D)        (None, 32, 32, 256)       590080    
_________________________________________________________________
block3_conv3 (Conv2D)        (None, 32, 32, 256)       590080    
_________________________________________________________________
block3_pool (MaxPooling2D)   (None, 16, 16, 256)       0         
_________________________________________________________________
block4_conv1 (Conv2D)        (None, 16, 16, 512)       1180160   
_________________________________________________________________
block4_conv2 (Conv2D)        (None, 16, 16, 512)       2359808   
_________________________________________________________________
block4_conv3 (Conv2D)        (None, 16, 16, 512)       2359808   
_________________________________________________________________
block4_pool (MaxPooling2D)   (None, 8, 8, 512)         0         
_________________________________________________________________
block5_conv1 (Conv2D)        (None, 8, 8, 512)         2359808   
_________________________________________________________________
block5_conv2 (Conv2D)        (None, 8, 8, 512)         2359808   
_________________________________________________________________
block5_conv3 (Conv2D)        (None, 8, 8, 512)         2359808   
_________________________________________________________________
block5_pool (MaxPooling2D)   (None, 4, 4, 512)         0         
_________________________________________________________________
sequential_3 (Sequential)    (None, 1)                 2097665   
=================================================================
Total params: 16,812,353
Trainable params: 16,812,353
Non-trainable params: 0

Now lets visualize the output of our trained model

activ_benign = activ_viewer(model,'block2_conv1',imgb.reshape(1,128,128,3))
img_benign = deprocess_image(activ_benign[0])
plot_filters(img_benign[0])
plt.figure(figsize=(20,20))
for f in range(128):
    plt.subplot(8,16,f+1)
    plt.imshow(img_benign[0,:,:,f])
    plt.axis('off')Code language: Python (python)
machine learning
activ_malign = activ_viewer(model,'block2_conv1',imgm.reshape(1,128,128,3))
img_malign = deprocess_image(activ_malign[0])
plot_filters(img_malign[0])
plt.figure(figsize=(20,20))
for f in range(128):
    plt.subplot(8,16,f+1)
    plt.imshow(img_malign[0,:,:,f])
    plt.axis('off')Code language: Python (python)
skin cancer

Now lets zoom and visualize some of the filters

plt.figure(figsize=(10,10))
plt.subplot(121)
plt.imshow(img_benign[0,:,:,49])
plt.axis('off')
plt.subplot(122)
plt.imshow(img_malign[0,:,:,49])
plt.axis('off')Code language: Python (python)
skin cancer classification
plt.figure(figsize=(10,10))
plt.subplot(121)
plt.imshow(img_benign[0,:,:,94])
plt.axis('off')
plt.subplot(122)
plt.imshow(img_malign[0,:,:,94])
plt.axis('off')Code language: Python (python)
skin cancer

Testing the Model

Now let’s visualize and test the actual ability of our trained model

def plot_filters32(filters):
    newimage = np.zeros((16*filters.shape[0],16*filters.shape[1]))
    for i in range(filters.shape[2]):
        y = i%16
        x = i//16
        newimage[x*filters.shape[0]:x*filters.shape[0]+filters.shape[0],
                 y*filters.shape[1]:y*filters.shape[1]+filters.shape[1]] = filters[:,:,i]
    plt.figure(figsize = (15,25))
    plt.imshow(newimage)    
    
activ_benign = activ_viewer(model,'block3_conv3',imgb.reshape(1,128,128,3))
img_benign = deprocess_image(activ_benign[0])
plot_filters32(img_benign[0])Code language: Python (python)
machine learning
activ_malign = activ_viewer(model,'block3_conv3',imgm.reshape(1,128,128,3))
img_malign = deprocess_image(activ_malign[0])
plot_filters32(img_malign[0])Code language: Python (python)
classification
Aman Kharwal
Aman Kharwal

I'm a writer and data scientist on a mission to educate others about the incredible power of data📈.

Articles: 1536

Leave a Reply