Build CNN Model for Detect Skin Cancer and Deploy The Model.

Mohamed Bakrey
10 min readJan 20, 2023

--

Introduction

When we look at the current time, we will find that cancer is greatly increasing, and in general, it is on a severe increase. The numbers are increasing every day from the day before, so this type of cancer, which is skin cancer, which we will address in this article, is one of the most dangerous types of cancer that has increased cases of Infection with it at the present time, especially in people with white bulimia, and that some countries spend a lot of money to treat it in the recent period, so at the present time I have touched on the use of deep learning and artificial intelligence to solve this problem or help solve that problem.

An overview of skin cancer

Skin cancer is one of the most dangerous types that afflict humans, as this disease is one of the most dangerous diseases that we see at the present time, especially in North America, where people have white skin, like this type of people. They have white skin, and that skin is very much known as sensitive skin and that is why, when we look at these people, we will find that they are the most susceptible to this disease. There are many types of this disease that are prevalent, and it also appears after other conditions, as it can be benign and it can be malignant, and for this reason, I have made an application that is entirely based on artificial intelligence and neural networks. The application helps to solve this problem as this model has been trained on many images affected by this disease. Pictures contain two types of diseases, benign and malignant. Come to You is an application on a website that you can access through the link, then you upload the image that you have from your device, and from here the form or application tells you what kind of disease the image contains.

The image we have:

Benign cancer:

Malignant cancer:

What is skin cancer?

Skin cancer occurs when skin cells grow and multiply in an uncontrolled and disorderly manner.

Normally, new skin cells are formed when cells grow and die or become damaged. When this process does not work as it should, it results in the rapid growth of cells, some of which may be abnormal cells. This group of cells may be noncancerous (benign, which does not spread or cause damage, or cancerous, which may spread to nearby tissues or other areas of your body if

It is not detected early and treated.

The reason for its production:

Skin cancer is most often caused by exposure to ultraviolet rays from the sun.

How common is skin cancer?

This type of cancer is very common in the United States of America.

Other facts about skin cancer:

  • About 20% of Americans will develop skin cancer at some time in their lives.
  • Nearly 9,500 Americans are diagnosed with skin cancer each day.
  • Having five or more sunburns in your lifetime doubles your chance of developing skin cancer.
  • The five-year survival rate is 99% if caught and treated early.
  • Non-Hispanic white people have a skin cancer rate about 30 times higher than non-Hispanic white people
  • Non-Hispanic or Asian/Pacific Islander.
  • Skin cancer in people of color is often diagnosed at later stages when it is more difficult to treat. About 25% of skin cancer cases in African Americans are diagnosed when cancer has spread to nearby lymph nodes.

Most skin cancer deaths are caused by skin cancer. If you have been diagnosed with skin cancer:

  • The five-year survival rate if it is caught before it has spread to the lymph nodes is 99%.
  • The five-year survival rate if it spreads to nearby lymph nodes is 66%.
  • The five-year survival rate if it spreads to distant lymph nodes and other organs is 27%

Where does skin cancer develop?

Skin cancer develops primarily on areas of sun-exposed skin, including the scalp, face, lips, ears, neck, chest, arms, and hands, and on the legs in women. But it can also form on areas that rarely see the light of day — your palms, beneath your fingernails or toenails, and your genital area

Skin cancer affects people of all skin tones, including those with darker complexions. When melanoma occurs in people with dark skin tones, it’s more likely to occur in areas not normally exposed to the sun, such as the palms of the hands and soles of the feet.

Basal cell carcinoma signs and symptoms

Basal cell carcinoma usually occurs in sun-exposed areas of your body, such as your neck or face.

Basal cell carcinoma may appear as:

  • A pearly or waxy bump
  • A flat, flesh-colored, or brown scar-like lesion
  • A bleeding or scabbing sore that heals and returns

How is skin cancer treated?

Here we can say that the need for cancer treatment depends on the stage of cancer. Where the stages of skin cancer range from the stage from the zero stage to the fourth stage, and this is the stage in which the disease is in its most severe condition. The higher the number, the greater the spread of cancer.

Sometimes a biopsy alone can remove all of the cancerous tissue if the cancer is small and confined to only the surface of the skin. Other common skin cancer treatments, used alone or in combination, include:

Here are a few of the many ways:

Cryotherapy:

Here liquid nitrogen cryotherapy is used to freeze skin cancer. This is one of the difficult methods, but it seems to be effective, as it fades away dead cells after treatment. Possibly precancerous skin lesions called actinic keratoses, and other small early cancers that are confined to the top layer of the skin can be treated with this method. Excisional surgery. This surgery involves removing the tumor and some surrounding healthy skin to make sure all cancer is removed.

Mohs surgery:

Also, this is one of the most important ways in which work is done on that point, which is working on it. With this procedure, the visible and elevated area of ​​the tumor is removed first. Then the surgeon uses a scalpel to remove a thin layer of skin cancer cells. The layer is examined under a microscope immediately after its removal. Additional layers of tissue continue to be removed, one layer at a time until no more cancer cells are seen

Under the microscope:

Mohs surgery removes only the diseased tissue, sparing as much of the surrounding normal tissue as possible. It is often used to treat basal cell and squamous cell carcinomas and areas close to sensitivity or of cosmetic importance, such as the eyelids, ears, lips, forehead, scalp, fingers, or genital area.

Abrasiveness and electrocautery:

This technique uses an instrument with a sharp, circular edge to remove cancer cells as they scratch across the tumor. The area is then treated with an electric needle to destroy any remaining cancer cells. This technique is often used in basal cell and squamous cell carcinomas and melanomas.

Chemotherapy and immunotherapy

Chemotherapy uses medicines to kill cancer cells. Anti-cancer drugs may be applied directly to the skin (topical chemotherapy) if they are confined to the top layer of the skin or delivered through pills or an IV if cancer has spread to other parts of the body. Immunotherapy uses your body’s immune system to kill cancer cells.

radiation therapy

Radiation therapy: This is a form of cancer treatment that uses radiation (strong beams of energy) to kill cancer cells or stop them from growing and dividing.

Phototherapy

In this treatment, your skin is covered with medication and a blue or red fluorescent light then activates the medication. Photodynamic therapy destroys precancerous cells while leaving normal cells alone.

How does the CNN model help treat skin cancer?

Here, the neural network model was used to solve this problem, and we have presented its solution, as the model works to help it detect the disease at the required speed, which we should realize here so that the disease does not progress and becomes in an advanced state. To study and store it in the form of weights for each of its forms. Hence, the model classifies and defines the disease and its type.

What causes non-melanoma skin cancer?

Overexposure to ultraviolet (UV) light is the main cause of non-melanoma skin cancer. UV light comes from the sun, as well as from artificial tanning sunbeds and sunlamps.

Other risk factors that can increase your chances of developing non-melanoma skin cancer include:

  • a previous non-melanoma skin cancer
  • a family history of skin cancer
  • pale skin that burns easily
  • a large number of moles or freckles
  • taking medicine that suppresses your immune system
  • a co-existing medical condition that suppresses your immune system

Steps For Working On Project and provided solution.

1. Import Library

Here, work has been done to read the Library in our netbook so that we can work on them:

import os
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import os
from glob import glob
import seaborn as sns
from PIL import Image
np.random.seed(11) # It's my lucky number
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split, KFold, cross_val_score, GridSearchCV
from sklearn.metrics import accuracy_score
import itertools
import keras
from keras.utils.np_utils import to_categorical # used for converting labels to one-hot-encoding
from keras.models import Sequential, Model
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D
from keras import backend as K
from tensorflow.keras.layers import BatchNormalization
from tensorflow.keras.optimizers import Adam, RMSprop
from keras.preprocessing.image import ImageDataGenerator
from keras.callbacks import ReduceLROnPlateau
from keras.wrappers.scikit_learn import KerasClassifier
from keras.applications.inception_v3 import InceptionV3
from keras import backend as K
import random
import urllib.request
import matplotlib.image as mpimg
from skimage.filters import rank, threshold_otsu
from skimage import io
from skimage.color import rgb2gray
from sklearn.cluster import KMeans
from skimage.morphology import closing, square, disk

Here, work was done to read the writings that are used to help in the work and to build the neural network that was based on the discovery and classification of the disease.

2. Read the Data

Here, work has been done to read the images we obtained in the network feed.

Here, the images are divided into two types, the first being ‘Benign’ and ‘Malignant’.

# Train image
train='/kaggle/input/skin-cancer-malignant-vs-benign/train'
# test image
test='/kaggle/input/skin-cancer-malignant-vs-benign/test'

3. Make some of the processes for data

Here, work was done on image processing, and also the images were converted into matrices, the label was extracted, and it was placed in a data frame, and converted into one hot encoder, and the appropriate image size was set to the neural network.

# Here we have two class.
dataset_path_train = os.listdir(train)
print (dataset_path_train)
print("Types of classes labels found: ", len(dataset_path_train))
OutPut:
['benign', 'malignant']
Types of classes labels found: 2
# Extract the label  for every image
class_labels = []
for item in dataset_path_train: 
#
all_classes = os.listdir(train + '/' +item+'/')
# Add them to the list
for room in all_classes:
class_labels.append((item, str('dataset_path' + '/' +item) + '/' + room))
# Creat DataFrame for image and label
df_train = pd.DataFrame(data=class_labels, columns=['Labels', 'image'])
df_train.head()
im_size =224
images = []
labels = []
for i in dataset_path:
data_path = path + str(i)
filenames = [i for i in os.listdir(data_path) ]
## Append label names accordingly
for f in filenames:
img = cv2.imread(data_path + '/' + f)
img = cv2.resize(img, (im_size, im_size))
images.append(img)
labels.append(i)
Labelsimage0benigndataset_path/benign/764.jpg1benigndataset_path/benign/1700.jpg2benigndataset_path/benign/1786.jpg3benigndataset_path/benign/1075.jpg4benigndataset_path/benign/771.jpg
print("Total number of images in the dataset: ", len(df_train))
print("Here we have count of class in kind of image.")
label_count = df_train['Labels'].value_counts()
print(label_count)
Total number of images in the dataset:  2637
Here we have count of class in kind of image.
benign 1440
malignant 1197
Name: Labels, dtype: int64
import cv2
path = '/kaggle/input/skin-cancer-malignant-vs-benign/train/'
dataset_path = os.listdir('/kaggle/input/skin-cancer-malignant-vs-benign/train/')
## converting python list into numpy array
images = np.array(images)
images = images.astype('float32') / 255.0
print("Shape of Image :", images.shape)
# One Hot Encoding
from sklearn.preprocessing import LabelEncoder , OneHotEncoder
y=df_train['Labels'].values
print(y)
y_labelencoder = LabelEncoder ()
y = y_labelencoder.fit_transform(y)

4. Apply the model to this image

Here, work was done to build a neural network suitable for the data until a wonderful result was obtained

Set parameter:

input_shape = (image_size, image_size, 3)
batch_size = 128
kernel_size = 3
pool_size = 2
filters = 64
dropout = 0.5
# Model is a stack of CNN-ReLU-MaxPooling
model = Sequential()
model.add(Conv2D(filters=filters,kernel_size=kernel_size, activation='relu', input_shape=input_shape))model.add(MaxPooling2D(pool_size))
model.add(Conv2D(filters=filters, kernel_size=kernel_size, activation='relu'))
model.add(MaxPooling2D(pool_size))
model.add(Conv2D(filters=filters,kernel_size=kernel_size,activation='relu'))
model.add(Flatten())# dropout added as regularizer
model.add(Dropout(dropout))
# output layer is 10-dim one-hot vector
model.add(Dense(num_labels))
model.add(Activation('softmax'))
# Plot Model

Model Plot Prediction:

5. Make Deployment and web applications.

In this part, an application was made for the project by using the Flask tool, which was built with Python, and HTML and CSS were also used for structuring. Here it was built on two pages, the first uploading the image and the second for the result.

Here you can see the application: https://skine-cancer-begin-and-melgin.mohamedbakery.repl.co

This Video Explain the Project: YouTube

Conclusion

If we look, we will find that cancer is one of the most dangerous diseases that affect humans and that many people suffer from. Here in this article, we have dealt with one of the most difficult types, which is skin cancer. In this part, work has been done to create an application based on artificial intelligence. This application is a web page, and it works to classify and detect skin cancer patients, and here the essence of the article revolves around presenting a solution or one Hence, we learn a new point, which is a new method based on deep learning and the neural network, through which new points and a new idea are added in the form of a web application that works in a large and guaranteed manner. of the solutions with a new idea that facilitates and speeds up the provision of aid in that part.

--

--