<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Zulfikar Irham on Medium]]></title>
        <description><![CDATA[Stories by Zulfikar Irham on Medium]]></description>
        <link>https://medium.com/@zulfikarirham02?source=rss-e6477f2e2e73------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wHPPekGG8fCmncwKLjP9Vw.jpeg</url>
            <title>Stories by Zulfikar Irham on Medium</title>
            <link>https://medium.com/@zulfikarirham02?source=rss-e6477f2e2e73------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 17:17:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@zulfikarirham02/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Image Classification for Prediction of Lung Cancer]]></title>
            <link>https://python.plainenglish.io/image-classification-for-prediction-of-lung-cancer-66b3ab5e7d04?source=rss-e6477f2e2e73------2</link>
            <guid isPermaLink="false">https://medium.com/p/66b3ab5e7d04</guid>
            <category><![CDATA[image-classification]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[medicine]]></category>
            <dc:creator><![CDATA[Zulfikar Irham]]></dc:creator>
            <pubDate>Sat, 13 Jan 2024 06:45:39 GMT</pubDate>
            <atom:updated>2024-01-15T01:58:23.866Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*mXkThtOwoOjJjf84UkaeDA.jpeg" /></figure><h3>Introduction</h3><p>Abnormal cell growth in the lung can be called lung cancer. Lung cancer is one of the most serious diseases in this decade. Based on data Global Cancer Statistics 2020: GLOBOCAN Estimates of Incidence and Mortality Worldwide for 36 Cancers in 185 Countries lung cancer is globally the second most commonly diagnosed cancer with over 2,2 million new cases and the leading cause of cancer death, with an estimated 1.8 million deaths in 2020.</p><p>In the medical world, accuracy is required in dealing with a problem to prevent the loss of a person’s life. The use of images such as CT scans is very commonly used to detect lung cancer. It’s just that if humans do it, it is very difficult to differentiate between those who have cancer or not. This could happen because the resulting image is less clear. After all, there is noise. Therefore, technology is needed to predict lung cancer using CT-scan images to produce a fast and accurate diagnosis, namely by using the Deep Learning Convolutional Neural Network (CNN) algorithm for image classification.</p><p>In this article, we focus on using CNN for the prediction of CT scan images to identify benign, malignant, or normal. We focus on three algorithms in this article such as custom CNN and transfer learning using pre-trained models InceptionV3 and VGG16.</p><h3>Dataset</h3><p>The dataset can be obtained from <a href="https://www.kaggle.com/datasets/adityamahimkar/iqothnccd-lung-cancer-dataset">here</a>. The lung cancer dataset was collected in three months of fall in 2019 by the hospital specialist in The Iraq-Oncology Teaching Hospital/National Center for Cancer Diseases (IQ-OTH/NCCD). The IQ-OTH/NCCD lung cancer dataset contains a total of 1190 images representing CT scan slices of 110 cases. These cases are grouped into three classes: normal, benign, and malignant. Out of these, 40 cases are diagnosed as malignant; 15 cases are diagnosed as benign; and 55 cases are classified as normal cases.</p><p>The dataset is from Kaggle so the platform to code is Kaggle Notebook.</p><h3>Import Libraries</h3><p>In this article to create CNN and some of the pre-trained models use library Tensorflow and Keras. For image processing use OpenCV2 and for data visualization use Matplotlib and Plotly. Then, to balance the class of data we use scikit-learn.</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>import pandas as pd<br>import plotly.express as px<br>import plotly.graph_objects as go<br>from plotly.subplots import make_subplots<br>from sklearn.utils import class_weight<br>from sklearn.model_selection import train_test_split<br>import tensorflow as tf<br>from keras.preprocessing.image import ImageDataGenerator<br>from keras.models import Sequential<br>from keras.layers import Conv2D, MaxPool2D,Flatten, Dense, Dropout, BatchNormalization, Input<br>from tensorflow.keras.callbacks import Callback, EarlyStopping, ModelCheckpoint, ReduceLROnPlateau<br>from tensorflow.keras.optimizers import Adam<br>from tensorflow.keras.applications.inception_v3 import InceptionV3<br>from keras.applications.vgg16 import VGG16<br>import os<br>import cv2</pre><h3>Load Dataset</h3><p>The dataset is stored in directory form as shown in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5apiXOVbEl3ZzYE_PIWdqg.png" /><figcaption>Directory dataset of images</figcaption></figure><p>The total image is 1097 and then has three classes Benign cases, Malignant cases, and Normal cases. We will load the dataset and create a data frame with two features img_path and label.</p><pre>bengin_path = r&quot;/kaggle/input/iqothnccd-lung-cancer-dataset/The IQ-OTHNCCD lung cancer dataset/The IQ-OTHNCCD lung cancer dataset/Bengin cases&quot;<br>malignant_path = r&quot;/kaggle/input/iqothnccd-lung-cancer-dataset/The IQ-OTHNCCD lung cancer dataset/The IQ-OTHNCCD lung cancer dataset/Malignant cases&quot;<br>normal_path = r&quot;/kaggle/input/iqothnccd-lung-cancer-dataset/The IQ-OTHNCCD lung cancer dataset/The IQ-OTHNCCD lung cancer dataset/Normal cases&quot;<br><br>img_classes = [&quot;Bengin cases&quot;, &quot;Malignant cases&quot;, &quot;Normal cases&quot;]<br>path_list = [bengin_path, malignant_path, normal_path]<br><br>img_path = []<br>class_labels = []<br>for i, dir_list in enumerate(path_list):<br>    name_img = os.listdir(dir_list)<br>    for name_file in name_img:<br>        img = os.path.join(dir_list,name_file)<br>        img_path.append(img)<br>        class_labels.append(img_classes[i])<br><br>df = pd.DataFrame({&quot;img_path&quot; : img_path,<br>                  &quot;label&quot; : class_labels})<br><br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*jEFTaeDbKkCMXWryI-gULg.png" /></figure><p>So, from the data frame above we can visualize each class of images</p><pre>for category, group in df.groupby(&quot;label&quot;):<br>    fig, ax = plt.subplots(1,3, figsize = (5,5))<br>    ax = ax.ravel()<br>    for i, (_,r) in enumerate(group.sample(3).iterrows()):<br>        img = cv2.imread(r.img_path)<br>        ax[i].imshow(img)<br>        ax[i].axis(&quot;off&quot;)<br>        ax[i].set_title(r.label)<br>    plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*1PYeSJjhVhZ54ZBC9bIAtg.png" /></figure><h3>Exploratory Data Analysis</h3><p>Check the number of images in each three classes using a histogram plot.</p><pre>countData = df[&quot;label&quot;].value_counts().reset_index()<br>fig = px.histogram(data_frame = countData, x = &quot;label&quot;, y = &quot;count&quot;)<br>fig.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cS9myFx4K-WqKuKgr7xsVA.png" /></figure><p>If we look at the image above, we can get the conclusion that the dataset is imbalanced because the three classes are not equally distributed. To handle it, we will use balancing each weight class for training data.</p><h4>Analyzing Image Properties</h4><p>To get insights from image data we can extract some of the properties such as size, resolution, and color distribution of images. This analysis can help to get detection of anomalies from images and valuable information on the characteristics of images.</p><pre>sizes = []<br>resolutions = []<br>color_distributions = []<br><br>for img_path in df[&quot;img_path&quot;]:<br>    #load image<br>    img = cv2.imread(img_path)<br>    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)<br>    #Get image size<br>    size = os.path.getsize(img_path)<br>    sizes.append(size)<br>    #Extract the resolution of images<br>    resolution = img.shape[:2]<br>    resolutions.append(resolution)<br>    #Extract color distribution<br>    mean_color_distributions = np.bincount(img.flatten(), minlength = 256)<br>    color_distributions.append(mean_color_distributions)<br>sizes = np.array(sizes)<br>resolutions = np.array(resolutions)<br>color_distributions = np.array(color_distributions)</pre><h4><strong>Distribution Size of Images</strong></h4><pre>#Sizes in MB<br>sizes_MB = []<br>for img_path in df[&quot;img_path&quot;]:<br>    #load image<br>    img = cv2.imread(img_path)<br>    #Get image size<br>    size = os.path.getsize(img_path)<br>    sizes_MB.append(size/1_000_000)<br>    <br>fig = px.histogram(x=sizes_MB, nbins = 50, title = &quot;Distribution of Image Sizes&quot;)<br>fig.update_layout(xaxis_title = &quot;File Size (MB)&quot;,<br>                 yaxis_title = &quot;Number of Images&quot;,<br>                 showlegend = False,<br>                 bargap = 0.1,<br>                 bargroupgap = 0.1)<br>fig.update_traces(marker = dict(color = &quot;green&quot;))<br>fig.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AfIN-iW2iup57rJsRSbNaQ.png" /></figure><p>From the histogram above we can see the distribution of image size is the image with size 0.1–0.15 MB is higher for the size of other.</p><h4>Distribution of Image Resolution</h4><pre>fig = px.scatter(x = resolutions[:,0], y = resolutions[:,1], title = &quot;Distribution of Image Resolution&quot;)<br>fig.update_layout(<br>    xaxis_title = &quot;Width (Pixel)&quot;,<br>    yaxis_title = &quot;Height (Pixel)&quot;,<br>    showlegend = False,<br>    hovermode = &quot;closest&quot;<br>)<br>fig.update_traces(marker = dict(color=&quot;red&quot;))<br>fig.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*wfgqSzmyStaY3WU3CdWVCQ.png" /></figure><p>That scatter plot is for visualizing the distribution of image resolution in the x-axis as width and the y-axis as height in the unit pixel. So, we can see that all images just have five resolutions in distribution. This scatter plot is usually used to identify relationships, patterns, or clusters in the image resolution.</p><h4>Mean Color Distribution</h4><pre>import plotly.graph_objects as go<br>mean_color_distributions = np.mean(color_distributions, axis = 0)<br>fig = go.Figure(<br>    go.Bar(x = np.arange(256), y = mean_color_distributions, name = &quot;Mean Color Distributions&quot;<br>))<br>fig.update_layout(<br>    title = &quot;Mean Color Distribution&quot;,<br>    xaxis_title = &quot;Color Values&quot;,<br>    yaxis_title = &quot;Number of Pixel&quot;<br>)<br>fig.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*3zaIyUveU7g97SRV2Hc7oQ.png" /></figure><p>Calculating the mean color distribution of all images is used to understand the dominant color distribution. From the plot, we can see the image has color values 0 and 255 which means black and white image pixels. Then, the pixel more distributed is around 50 color value so the image approaches black, and has a pixel of around 200 color value so the image approaches white. From the visualization and the mean color distribution, all of the images are grayscale.</p><h3>Train Test Split</h3><p>In this step, we will split the dataset into 70% data training, 15% data validation, and 15% data testing. Data training is used to teach the model for learning from data. Data validation to test the model and compare the accuracy and loss when teaching the model. Data testing is used to measure whether the accuracy of the model is good or not.</p><pre>train_ratio = 0.70<br>test_ratio = 0.15<br>val_ratio = 0.15<br><br>df_train, df_test_val = train_test_split(df, train_size = train_ratio, random_state = 42)<br>df_test, df_val = train_test_split(df_test_val, train_size = test_ratio/(test_ratio+val_ratio), random_state = 42)<br><br>print(f&quot;Train shape = {df_train.shape}&quot;)<br>print(f&quot;Test shape = {df_test.shape}&quot;)<br>print(f&quot;Validation shape = {df_val.shape}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*DtRcE5hEhaIfWMHNKlxIYA.png" /></figure><h3>Denoise Image Using Median Blur</h3><p>The real image from real-world comes with noise. These noises might emerge from a variety of causes, including instabilities in electric signals, malfunctioning camera sensors, bad lighting conditions, faults in data transfer over vast distances, and so on. The median blur is good for handling salt-and-pepper noise. Function <strong>cv2.medianBlur()</strong> takes the median of all the pixels under the kernel area, and the central element is replaced with this median value. In the code below we create the function <strong>preprocessing_denoise()</strong> for input to the <strong>ImageDataGenerator</strong> in the next step.</p><pre>def preprocessing_denoise(img):<br>    denoise_img = cv2.medianBlur(img, 1)<br>    denoise_img = cv2.cvtColor(denoise_img, cv2.COLOR_BGR2RGB)<br>    return denoise_img</pre><h3>Image Data Augmentation using ImageDataGenerator</h3><p>Image augmentation is the expansion of image data using transformations such as rotation, width shift, height shift, shearing, zoom, and horizontal flip. We use image augmentation when we lack of training dataset and to handle problem overfitting. The <strong>ImageDataGenerator </strong>generates batches of tensor image data with real-time augmentation. The data will be looped over in batches.</p><pre>IMG_WIDTH = 224<br>IMG_HEIGHT = 224<br><br>image_size = (IMG_WIDTH, IMG_HEIGHT)<br>batch_size = 32<br><br>TRAIN_DATAGEN = ImageDataGenerator(rescale = 1./255.,<br>                                   preprocessing_function = preprocessing_denoise,<br>                                  rotation_range = 30,<br>                                  width_shift_range = 0.1,<br>                                  height_shift_range = 0.2,<br>                                  shear_range = 0.1,<br>                                  zoom_range = 0.2,<br>                                  horizontal_flip = True)<br><br>TEST_DATAGEN = ImageDataGenerator(rescale = 1./255.)<br><br>train_generator = TRAIN_DATAGEN.flow_from_dataframe(<br>    df_train,<br>    x_col = &quot;img_path&quot;,<br>    y_col = &quot;label&quot;,<br>    target_size = image_size,<br>    batch_size = batch_size,<br>    color_mode = &quot;rgb&quot;,<br>    class_mode = &quot;categorical&quot;,<br>    shuffle = True<br>)<br><br>val_generator = TEST_DATAGEN.flow_from_dataframe(<br>    df_val,<br>    x_col = &quot;img_path&quot;,<br>    y_col = &quot;label&quot;,<br>    target_size = image_size,<br>    batch_size = batch_size,<br>    color_mode = &quot;rgb&quot;,<br>    class_mode = &quot;categorical&quot;,<br>    shuffle = True<br>)<br><br>test_generator = TEST_DATAGEN.flow_from_dataframe(<br>    df_test,<br>    x_col = &quot;img_path&quot;,<br>    y_col = &quot;label&quot;,<br>    target_size = image_size,<br>    batch_size = batch_size,<br>    color_mode = &quot;rgb&quot;,<br>    class_mode = &quot;categorical&quot;,<br>    shuffle = True<br>)</pre><h3>Class Weights</h3><p>Because the data is imbalanced we can modify the class weight to the skewed distribution of the classes. To achieve this we can use the scikit-learn library and call the class_weight. This can be work by giving different weights to both the majority and minority classes. The majority class has more data compared to the minority class. In the step of training if given the difference weights it can influence result classification. The overall goal is to penalize the minority class for misclassification by increasing class weight while decreasing weight for the majority class.</p><pre>#Weight Class<br>class_weights = class_weight.compute_class_weight(<br>           class_weight = &#39;balanced&#39;,<br>            classes = np.unique(train_generator.classes), <br>            y = train_generator.classes)<br><br>train_class_weights = dict(enumerate(class_weights))<br><br>for idx, weight, in train_class_weights.items():<br>    class_name = classes[idx]<br>    print(f&quot;{class_name} : {weight}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*oQWr9t1uQFDqpWHGFUeoUQ.png" /></figure><h3>Modeling and Evaluate Model</h3><p>For the modeling process, we use three different models that are CNN (Custom), and using transfer learning InceptionV3 and VGG16.</p><h4>CNN (Custom)</h4><p>In the CNN (Custom) model, we create six layers of Conv2D with MaxPool2D and BatchNormalization after each convolutional layer for the feature extraction from the images. The activation function used is ReLU. The fully connected layer has three layers and the last layer has three output classes (Benign, Malignant, and Normal) with the activation function softmax.</p><pre>model1 = Sequential([<br>    Conv2D(filters = 64, kernel_size = (3,3), strides = (1,1), input_shape = (224, 224, 3), activation = &quot;relu&quot;, padding = &quot;same&quot;),<br>    MaxPool2D(pool_size = (2,2)),<br>    BatchNormalization(),<br>    <br>    Conv2D(filters = 64, kernel_size = (3,3), strides = (1,1), padding = &quot;valid&quot;),<br>    MaxPool2D(pool_size = (2,2)),<br>    BatchNormalization(),<br>    <br>    Conv2D(filters = 128, kernel_size = (3,3), strides = (1,1), padding = &quot;valid&quot;),<br>    MaxPool2D(pool_size = (2,2)),<br>    BatchNormalization(),<br>    <br>    Conv2D(filters = 128, kernel_size = (3,3), strides = (1,1), padding = &quot;valid&quot;),<br>    MaxPool2D(pool_size = (2,2)),<br>    BatchNormalization(),<br>    <br>    Conv2D(filters = 256, kernel_size = (3,3), strides = (1,1), padding = &quot;valid&quot;),<br>    MaxPool2D(pool_size = (2,2)),<br>    BatchNormalization(),<br>    <br>    Conv2D(filters = 256, kernel_size = (3,3), strides = (1,1), padding = &quot;valid&quot;),<br>    MaxPool2D(pool_size = (2,2)),<br>    BatchNormalization(),<br>    <br>    Flatten(),<br>    Dense(4096, activation = &quot;relu&quot;),<br>    Dropout(0.5),<br>    Dense(256),<br>    Dropout(0.25),<br>    Dense(3, activation = &quot;softmax&quot;)<br>])<br><br>model1.summary()</pre><h4>Compile and Training Model</h4><p>We use the loss function categorical cross entropy and the optimizer is Adam with a learning rate is 0.0005. Then, when the training phase we use callbacks for early stopping monitoring. We use the val_loss to monitor when does not change over time so the training process stops. Then, we call the function ReduceLROnPlateau to reduce the learning rate when val_loss has stopped improving.</p><pre>model1.compile(<br>    loss = &quot;categorical_crossentropy&quot;,<br>    optimizer = Adam(learning_rate = 0.0005),<br>    metrics = [&quot;accuracy&quot;],<br>)<br><br>epochs = 50<br>history = model1.fit(train_generator,<br>                   steps_per_epoch = len(train_generator),<br>                   batch_size = 32,<br>                   validation_data = val_generator,<br>                   validation_steps = len(val_generator),<br>                   class_weight = train_class_weights,<br>                   callbacks=[<br>                               EarlyStopping(monitor = &quot;val_loss&quot;, # watch the val loss metric<br>                               patience = 5,<br>                               restore_best_weights = True), <br>                               ReduceLROnPlateau(monitor=&#39;val_loss&#39;, factor=0.2, patience=4, mode=&#39;min&#39;) <br>                              ],<br>                   epochs = epochs)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Af9C28yCaXh1qPucD45jQ.png" /></figure><h4>Accuracy and Loss</h4><p>Accuracy and loss are used to evaluate model performance, so we can plot the history of results accuracy and loss for data training and validation.</p><pre>def history_plot(epochs, history):<br>    fig1 = make_subplots()<br>    fig1.add_trace(go.Scatter(x = np.arange(1,epochs+1), y = history.history[&quot;accuracy&quot;], name = &quot;Training Accuracy&quot;))<br>    fig1.add_trace(go.Scatter(x = np.arange(1,epochs+1), y = history.history[&quot;val_accuracy&quot;], name = &quot;Validation Accuracy&quot;))<br>    fig1.update_layout(title = &quot;Training and Validation Accuracy&quot;, xaxis_title = &quot;Epoch&quot;, yaxis_title = &quot;Accuracy&quot;)<br>    fig1.show()<br><br>    fig2 = make_subplots()<br>    fig2.add_trace(go.Scatter(x = np.arange(1,epochs+1), y = history.history[&quot;loss&quot;], name = &quot;Training Loss&quot;))<br>    fig2.add_trace(go.Scatter(x = np.arange(1,epochs+1), y = history.history[&quot;val_loss&quot;], name = &quot;Validation Loss&quot;))<br>    fig2.update_layout(title = &quot;Training and Validation Loss&quot;, xaxis_title = &quot;Epoch&quot;, yaxis_title = &quot;Loss&quot;)<br>    fig2.show()<br><br>history_plot(epochs, history)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-4VxaxLEirTpThM8wF-z1w.png" /><figcaption>The Plot Graph Accuracy and Loss Custom CNN Model</figcaption></figure><p>The next step is to evaluate the loss and accuracy of the testing dataset</p><pre>def evaluate_model(model, test_generator):<br>    #Calculate test loss and accuracy<br>    results = model.evaluate(test_generator, verbose = 0)<br>    print(f&quot;Test Loss = {results[0]}&quot;)<br>    print(f&quot;Test Accuracy = {results[1]}&quot;)<br><br>evaluate_model(model1, test_generator)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*P7Q47d4IXTJa34mi6xhRJw.png" /></figure><p>The results are not good so we will train the transfer learning model for the next step to get the accuracy and loss better.</p><h4>Training Transfer Learning Models</h4><p>Besides the custom CNN model, we will explore the power of transfer learning. Using pre-trained mode InceptionV3 and VGG16 to transfer learning to improve the performance model. We will train our model more efficiently by using TensorFlow’s InceptionV3 and VGG16 models using transfer learning techniques. To modify the pre-trained model to fit our classification task, we must add custom layers, freeze some layers, and fine-tune the model.</p><h4>Training Model InceptionV3</h4><pre>#Define base_model of InceptionV3<br>base_model = InceptionV3(input_shape = (IMG_WIDTH, IMG_HEIGHT, 3), include_top = False, weights = &quot;imagenet&quot;)<br><br>#Freeze all layers<br>for layer in base_model.layers:<br>    layer.trainable = False<br><br>#Add Custom layers<br>model2 = Sequential()<br>model2.add(Input(shape = (IMG_WIDTH, IMG_HEIGHT, 3)))<br>model2.add(base_model)<br>model2.add(Flatten())<br>model2.add(Dense(1024, activation = &quot;relu&quot;))<br>model2.add(Dropout(0.4))<br>model2.add(Dense(3, activation = &quot;softmax&quot;))<br><br>#Compile and Training the model<br>epochs = 50<br>model2.compile(optimizer = Adam(0.0005),<br>             loss = &quot;categorical_crossentropy&quot;,<br>             metrics = [&quot;accuracy&quot;])<br>history = model2.fit(train_generator,<br>                   steps_per_epoch = len(train_generator),<br>                   batch_size = 64,<br>                   validation_data = val_generator,<br>                   validation_steps = len(val_generator),<br>                   class_weight = train_class_weights,<br>                   callbacks=[<br>                               EarlyStopping(monitor = &quot;val_loss&quot;, # watch the val loss metric<br>                               patience = 5,<br>                               restore_best_weights = True), <br>                               ReduceLROnPlateau(monitor=&#39;val_loss&#39;, factor=0.2, patience=2, mode=&#39;min&#39;) <br>                              ],<br>                   epochs = epochs)</pre><pre>#Plot the graph<br>history_plot(epochs, history)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r3dKGl_h6-K6ZD-eDWf6DA.png" /><figcaption>The Plot of Accuracy and Loss InceptionV3 Before Fine Tuning</figcaption></figure><p>Testing the model for getting accuracy and loss for data testing</p><pre>evaluate_model(model2, test_generator)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*OQx--GK2puegFrbPRydwSA.png" /></figure><p>The accuracy and loss of the value rose significantly from the custom CNN model.</p><h4>Fine Tuning InceptionV3 Model</h4><p>When fine-tuning we use all of the layers of InceptionV3. So the layers do not freeze.</p><pre># All layers does not freeze<br>base_model.trainable = True<br>#Compile the model<br>model2.compile(optimizer = Adam(0.00001),<br>              loss = &quot;categorical_crossentropy&quot;,<br>              metrics = [&quot;accuracy&quot;])<br>#Training the model<br>epochs = 50<br>history = model2.fit(train_generator,<br>                   steps_per_epoch = len(train_generator),<br>                   batch_size = 64,<br>                   validation_data = val_generator,<br>                   validation_steps = len(val_generator),<br>                   class_weight = train_class_weights,<br>                   callbacks=[<br>                               EarlyStopping(monitor = &quot;val_loss&quot;, # watch the val loss metric<br>                               patience = 5,<br>                               restore_best_weights = True), <br>                               ReduceLROnPlateau(monitor=&#39;val_loss&#39;, factor=0.2, patience=2, mode=&#39;min&#39;) <br>                              ],<br>                   epochs = epochs)</pre><pre>history_plot(epochs, history)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Ij-JC1S39Ihc9mAgd_59A.png" /><figcaption>The Plot of Accuracy and Loss InceptionV3 After Fine Tuning</figcaption></figure><p>Testing the model uses data testing.</p><pre>evaluate_model(model2, test_generator)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*BGoeypIwXIsrpk1uM2l81w.png" /></figure><h4>Training Model VGG16</h4><pre>#Define base mode of VGG16<br>base_model_vgg16 = VGG16(input_shape = (IMG_WIDTH, IMG_HEIGHT, 3), include_top = False, weights = &quot;imagenet&quot;)<br><br>#Freeze all layers VGG16 model<br>for layer in base_model_vgg16.layers:<br>    layer.trainable = False<br><br>#Add custom layers<br>model3 = Sequential()<br>model3.add(Input(shape = (IMG_WIDTH, IMG_HEIGHT, 3)))<br>model3.add(base_model)<br>model3.add(Flatten())<br>model3.add(Dense(1024, activation = &quot;relu&quot;))<br>model3.add(Dropout(0.4))<br>model3.add(Dense(3, activation = &quot;softmax&quot;))<br><br>#Compile model<br>model3.compile(optimizer = Adam(0.0005),<br>             loss = &quot;categorical_crossentropy&quot;,<br>             metrics = [&quot;accuracy&quot;])<br><br>#Training the model<br>epochs = 50<br>history = model3.fit(train_generator,<br>                   steps_per_epoch = len(train_generator),<br>                   batch_size = 64,<br>                   validation_data = val_generator,<br>                   validation_steps = len(val_generator),<br>                   class_weight = train_class_weights,<br>                   callbacks=[<br>                               EarlyStopping(monitor = &quot;val_loss&quot;, # watch the val loss metric<br>                               patience = 5,<br>                               restore_best_weights = True), <br>                               ReduceLROnPlateau(monitor=&#39;val_loss&#39;, factor=0.2, patience=4, mode=&#39;min&#39;) <br>                              ],<br>                   epochs = epochs)</pre><pre>history_plot(epochs, history)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wGzpdv6VfAKgR-bRJcspnA.png" /><figcaption>The Plot Accuracy and Loss VGG16 Before Fine Tuning</figcaption></figure><pre>evaluate_model(model3,test_generator)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*bRF71rrnWGeZ26s1oS7WFA.png" /></figure><h4>Fine Tuning VGG16 Model</h4><pre>#Set the training layer jus block_conv1<br>base_model_vgg16.trainable = True<br>set_trainable = False<br>for layer in base_model_vgg16.layers:<br>    if layer.name == &#39;block5_conv1&#39;:<br>        set_trainable = True<br>    if set_trainable:<br>        layer.trainable = True<br>    else:<br>        layer.trainable = False<br><br>#Compile the model<br>model3.compile(optimizer = Adam(0.00001),<br>              loss = &quot;categorical_crossentropy&quot;,<br>              metrics = [&quot;accuracy&quot;])<br><br>#Training the model<br>epochs = 50<br>history = model3.fit(train_generator,<br>                   steps_per_epoch = len(train_generator),<br>                   batch_size = 64,<br>                   validation_data = val_generator,<br>                   validation_steps = len(val_generator),<br>                   class_weight = train_class_weights,<br>                   callbacks=[<br>                               EarlyStopping(monitor = &quot;val_loss&quot;, # watch the val loss metric<br>                               patience = 5,<br>                               restore_best_weights = True), <br>                               ReduceLROnPlateau(monitor=&#39;val_loss&#39;, factor=0.2, patience=4, mode=&#39;min&#39;) <br>                              ],<br>                   epochs = epochs)</pre><pre>history_plot(epochs,history)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ANy0a9HpdA82mmUCyvZyow.png" /><figcaption>The Plot Accuracy and Loss for VGG Model After Fune Tuning</figcaption></figure><pre>evaluate_model(model3, test_generator)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*8TsTlY5eGAKzZgQxAjUl9Q.png" /></figure><h3>Results of All Models</h3><pre>models = [model1, model2, model3]<br>loss = []<br>accuracy = []<br>for model in models:<br>    results = model.evaluate(test_generator, verbose = 0)<br>    loss.append(results[0])<br>    accuracy.append(results[1])<br><br>name_models = [&quot;CNN (Custom)&quot;, &quot;InceptionV3&quot;, &quot;VGG16&quot;]<br>df_loss_acc = pd.DataFrame(data = {&quot;Name_Models&quot; : name_models,<br>                                  &quot;Loss&quot; : loss,<br>                                  &quot;Accuracy&quot; : accuracy})<br><br>fig = px.bar(data_frame = df_loss_acc, x = &quot;Name_Models&quot;, y = [&quot;Accuracy&quot;, &quot;Loss&quot;],<br>            barmode = &quot;group&quot;,<br>            text_auto = &quot;.3f&quot;)<br>fig.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*1LHfLy1o1u2lsnzNGqUt9g.png" /></figure><p>The best model for classification from image lung cancer is the VGG16 pre-trained model. The model gives accuracy and the loss is 0.927 and 0.213. Then, we will save the best model.</p><pre>model3.save(&quot;VGG16.keras&quot;)</pre><h3>Conclusion</h3><p>In this article, we can predict lung cancer from CT scan images with three different classes Benign cases, Malignant cases, and Normal cases. In the beginning, we can load the dataset and visualization of them. Next, we do an EDA process such as creating graphs to know the size distribution of images, resolution of images, and mean color distribution of images. Then, we create image augmentation using ImageDataGenerator and create the class weights to handle the imbalanced training dataset. We created three models such as the Custom CNN model and transfer learning using pre-trained models InceptionV3 and VGG16. For the results get the VGG16 the great model gives accuracy and loss is 0.927 and 0.213.</p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a><strong> | </strong><a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://stackademic.com/"><strong>Stackademic</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66b3ab5e7d04" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/image-classification-for-prediction-of-lung-cancer-66b3ab5e7d04">Image Classification for Prediction of Lung Cancer</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Telco Customer Churn Prediction Using Machine Learning and Deep Learning]]></title>
            <link>https://medium.com/@zulfikarirham02/telco-customer-churn-prediction-using-machine-learning-and-deep-learning-8d1905b04980?source=rss-e6477f2e2e73------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d1905b04980</guid>
            <category><![CDATA[telecommunication]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Zulfikar Irham]]></dc:creator>
            <pubDate>Sun, 27 Aug 2023 08:04:22 GMT</pubDate>
            <atom:updated>2023-08-27T08:04:22.256Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*NzumQdp6mQaaKWKEs9Eosg.jpeg" /><figcaption>Photo by Fernan Rahadi on Republika</figcaption></figure><p>Customer churn is a significant issue for big business companies. Companies are attempting to create methods for predicting customer churn to get a direct impact on getting more revenues, particularly in telecom companies. Finding these characteristics is crucial to ensure appropriate steps can be taken to reduce customer churn.</p><p>In this article, we will make machine learning and deep learning models to predict customers who churn and not churn. We will analyze three characteristics (1) <strong>services that the customer signed up for</strong>, (2) <strong>account information about the customer</strong>, and (3) <strong>demographic info</strong>. We use two machine learning models, K-Nearest Neighbors and Logistic Regression. In Deep Learning models, we use a Neural Network. Then we will evaluate the model using some evaluation metrics.</p><h3>Dataset</h3><p>The data set used for this article&#39;s classification problem is taken from Kaggle and IBM sample data set collection. <a href="https://www.kaggle.com/datasets/blastchar/telco-customer-churn">https://www.kaggle.com/datasets/blastchar/telco-customer-churn</a></p><p>This data set contains nineteen columns (independent variables) and one column (dependent variable) as a target feature for predicting. First, we import some packages in use in this case for data visualization and classification problem</p><pre>import pandas as pd<br>import numpy as np<br>import matplotlib.ticker as mtick<br>import seaborn as sns<br>import matplotlib.pyplot as plt<br>import math<br>from sklearn.preprocessing import OneHotEncoder, MinMaxScaler<br>from sklearn.model_selection import train_test_split, RandomizedSearchCV<br>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.metrics import accuracy_score, confusion_matrix, classification_report, roc_curve, roc_auc_score<br>from sklearn.metrics import precision_recall_curve, auc, f1_score, ConfusionMatrixDisplay, precision_score, recall_score</pre><h4>Load Data</h4><p>The data set in this article uses (.csv format) so we use pandas.read_csv to load the data set.</p><pre># Import dataset and make a CustomerID column to index<br>df = pd.read_csv(&quot;/kaggle/input/telco-customer-churn/WA_Fn-UseC_-Telco-Customer-Churn.csv&quot;,<br>                        index_col = &#39;customerID&#39;)<br><br>df.head()</pre><pre>df.shape</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/112/1*2Sy1SclswnsGs5I2TbSZ-Q.png" /></figure><p>The data set contains 7043 rows and 20 columns. Next, we will check for unique values from each column in the data.</p><pre>df_columns = df.columns.tolist()<br>for column in df_columns:<br>    print(f&quot;{column} unique values : {df[column].unique()}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*Z9iij_lZaWnpMBGTPM31bw.png" /></figure><h4><strong>Data Understanding</strong></h4><p><strong>Classification Label</strong></p><ul><li>Churn — Whether the customer churned or not (Yes or No)</li></ul><p><strong>Services Each Customer Has to Sign Up</strong></p><ul><li>PhoneService — Whether the customer has a phone service or not (Yes or No)</li><li>MultipleLines — Whether the customer has multiple lines or not (Yes, No, No phone service)</li><li>InternetService — A type of internet service the customer has (DSL, Fiber Optic, No)</li><li>OnlineSecurity — Whether the customer has online security or not (Yes, No, No Internet Service)</li><li>OnlineBackup — Whether the customer has online backup or not (Yes, No, No Internet Service)</li><li>DeviceProtection — Whether the customer has device protection or not (Yes, No, No Internet Service)</li><li>TechSupport — Whether the customer has tech support or not (Yes, No, No Internet Service)</li><li>StreamingTV—Whether the customer has a streaming TV (Yes, No, No Internet Service)</li><li>StreamingMovies — Whether the customer has a streaming movie (Yes, No, No Internet Service)</li></ul><p><strong>Customer Account Information</strong></p><ul><li>Tenure — How long customer has stayed in the company</li><li>Contract — The type of contract the customer has (Month-to-Month, One year, Two years)</li><li>PaperlessBilling — Whether the customer has a paperless billing (Yes, No)</li><li>PaymentMethod — payment method used by the customer (Electronic check, Mailed check, Bank transfer (automatic), Credit card (automatic))</li><li>MonthlyCharges — Amount charged to the customer monthly</li><li>TotalCharges — The total amount charged to the customer</li></ul><p><strong>Customer Demographic Info</strong></p><ul><li>CustomerID — Unique value for each customer</li><li>gender — The type of gender each customer (Female, Male)</li><li>SeniorCitizen — Whether the customer is a senior citizen (Yes, No)</li><li>Partner — Whether the customer has a partner or not (Yes, No)</li><li>Dependents — Whether the customer has a dependent or not (Yes, No)</li></ul><h3>Exploratory Data Analysis (EDA)</h3><h4>Data Overview</h4><p>In this section, we will learn about statistic description and info about data type</p><pre># Statistic descriptive<br>df.describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*_XBxPp2ERkLTJVh1iQFoIg.png" /></figure><p>We can take a conclusion from that is :</p><ul><li>SeniorCitizen must be categorical data because has minimum value is 0 and the maximum value is 1.</li><li>The average customer stayed in the company is 32 months and 75% of customer has a tenure of 55 month</li><li>Average monthly charges are USD 64.76 and 25% of customers pay more than USD 89.85</li></ul><pre>df.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*ljiCZpYrnHlL-ovRLoPWyA.png" /></figure><p>There is something wrong with the data set on the TotalCharges column it must be float not object so we will change it to float.</p><pre># Change TotalCharges to float<br>df[&quot;TotalCharges&quot;] = pd.to_numeric(df[&quot;TotalCharges&quot;], errors=&quot;coerce&quot;)</pre><h4>Payment Method Check</h4><pre>df[&quot;PaymentMethod&quot;].unique()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*qcauiTOILZqi4VFjQfIC3A.png" /></figure><p>In the payment method, there is the word automatic and we will delete it because if we visualize a tick label is so long.</p><pre># Delete &quot;automatic&quot; from PaymentMethod<br>df[&quot;PaymentMethod&quot;] = df[&quot;PaymentMethod&quot;].str.replace(&quot; (automatic)&quot;, &quot;&quot;, regex=False)</pre><h4>Missing Values</h4><pre>features_na = [feature for feature in df.columns if df[feature].isnull().sum() &gt; 1]<br><br>for feature in features_na:<br>    print(f&quot;{feature}, {round(df[feature].isnull().mean(), 4)} % Missing values&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*Q4Boya6NKcHN9AOacHqYXQ.png" /></figure><p>The data set has missing values in TotalCharges is 0.0016% which is so a small percentage</p><pre># Check observation of missing values<br>df[df[features_na[0]].isnull()]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0VKao46k3z_v11jGzFeV6w.png" /></figure><p>As shown above, we see all of the tenures are zero so we will drop the missing values</p><pre># Drop missing values<br>df.dropna(inplace=True)</pre><h4>Target Variable Visualization</h4><pre>#Apply the ggplot style<br>plt.style.use(&quot;ggplot&quot;)</pre><pre>plt.figure(figsize=(5,5))<br>ax = sns.countplot(x = df[&quot;Churn&quot;],palette=&quot;Blues&quot;)<br>ax.bar_label(ax.containers[0])<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*CfS8llBV4edv5vq6zKdpmA.png" /></figure><p>The following bar plot shows the target variable of churn yes and no. The proportion of churn is an imbalanced data set because both classes are not equally distributed. To handle it, resampling would be a suitable approach. To keep this simple, we will keep the imbalanced data set and uses many evaluation matrices to evaluate models.</p><h4>Analysis Services Each Customer</h4><pre>#Make a function to plot categorical data according to target<br>def plot_categorical_to_target(df,categorical_values, target):<br>    number_of_columns = 2<br>    number_of_rows = math.ceil(len(categorical_values)/2)<br>    <br>    fig = plt.figure(figsize = (12, 5*number_of_rows))<br>    <br>    for index, column in enumerate(categorical_values, 1):<br>        ax = fig.add_subplot(number_of_rows,number_of_columns,index)<br>        ax = sns.countplot(x = column, data = df, hue = target, palette=&quot;Blues&quot;)<br>        ax.set_title(column)<br>    return plt.show()</pre><p>We will evaluate a percentage target for each customer services column (PhoneService, MultipleLines, InternetService, OnlineSecurity, OnlineBackup, DeviceProtection, TechSupport, StreamingTV, StreamingMovies)</p><pre>customer_services = [&quot;PhoneService&quot;,&quot;MultipleLines&quot;,&quot;InternetService&quot;,&quot;OnlineSecurity&quot;,&quot;OnlineBackup&quot;,<br>                    &quot;DeviceProtection&quot;,&quot;TechSupport&quot;,&quot;StreamingTV&quot;,&quot;StreamingMovies&quot;]<br>plot_categorical_to_target(df,customer_services, &quot;Churn&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1yLaxAIVJOnVE9G0gJgcMw.png" /></figure><p>We can extract the following conclusions by evaluating service attributes</p><ul><li>The moderately higher churn rate for customers who has the phone service.</li><li>Customers with internet service fiber optic have a higher churn rate compared with DSL and No.</li><li>The much higher churn rate for customers without online security.</li><li>Customers who don’t have access to tech support tend to leave more frequently than those who do.</li><li>Customers without online backup and device protection have a higher churn rate.</li></ul><h4>Analysis Customer Account Information — Categorical Variables</h4><p>We will evaluate the percentage of churn for each customer account information (Contract, PaperlessBilling, PaymentMethod)</p><pre>customer_account_cat = [&quot;Contract&quot;,&quot;PaperlessBilling&quot;,&quot;PaymentMethod&quot;]<br>plot_categorical_to_target(df,customer_account_cat,&quot;Churn&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XkXkNWwVptFenmiI40VoZQ.png" /></figure><p>The following bar plot shown above can make conclusions from that:</p><ul><li>Customers are more likely to churn with month-to-month contracts.</li><li>Moderately higher churn rate with electronic check payment method.</li><li>Customers with paperless billing have higher churn rates.</li></ul><h4>Analysis Customer Account Information — Numerical Variables</h4><p>We will evaluate the distribution for each numerical variable from customer account information (tenure, MonthlyCharges, TotalCharges).</p><pre>def histogram_plots(df, numerical_values, target):<br>    number_of_columns = 2<br>    number_of_rows = math.ceil(len(numerical_values)/2)<br>    <br>    fig = plt.figure(figsize=(12,5*number_of_rows))<br>    <br>    for index, column in enumerate(numerical_values,1):<br>        ax = fig.add_subplot(number_of_rows, number_of_columns, index)<br>        ax = sns.kdeplot(df[column][df[target]==&quot;Yes&quot;] ,fill = True)<br>        ax = sns.kdeplot(df[column][df[target]==&quot;No&quot;], fill = True)<br>        ax.set_title(column)<br>        ax.legend([&quot;Churn&quot;,&quot;No Churn&quot;], loc=&#39;upper right&#39;)<br>    plt.savefig(&quot;numerical_variables.png&quot;, dpi=300)<br>    return plt.show()</pre><pre>customer_account_num = [&quot;tenure&quot;, &quot;MonthlyCharges&quot;,&quot;TotalCharges&quot;]<br>histogram_plots(df,customer_account_num, &quot;Churn&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5l5g32O7Ur6MxzSp64iepw.png" /></figure><p>The following histograms above we can get conclusions that:</p><ul><li>Customers with short tenure are more churn.</li><li>Customers with paid more on monthly charges have higher churn rates.</li><li>Customers with high total charges tend to churn.</li></ul><h4>Analysis of Customer&#39;s Demographic Info</h4><p>We will evaluate the percentage of churn rate from the customer is demographic info (gender, SeniorCitizen, Partner, Dependents)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DfemT-JlPzG_i8hurr3wgg.png" /></figure><p>The following bar plot above we can draw some conclusions:</p><ul><li>Churn and no churn no have differences for each gender.</li><li>Young customers are more likely to churn rather than old customers.</li><li>Customers with a partner are less than churn if compared with a partner.</li></ul><h4>Outlier Checking with Boxplot for Numerical Variables</h4><p>Outlier is an observation data set with significantly differs from others&#39; observations of the data set. Outliers can make machine learning models with low accuracy so it is important to check them. We will check outliers from each numerical variable such as tenure, MonthlyCharges, and TotalCharges.</p><pre>def outlier_check_boxplot(df,numerical_values):<br>    number_of_columns = 2<br>    number_of_rows = math.ceil(len(numerical_values)/2)<br>    <br>    fig = plt.figure(figsize=(12,5*number_of_rows))<br>    for index, column in enumerate(numerical_values, 1):<br>        ax = fig.add_subplot(number_of_rows, number_of_columns, index)<br>        ax = sns.boxplot(x = column, data = df, palette = &quot;Blues&quot;)<br>        ax.set_title(column)<br>    plt.savefig(&quot;Outliers_check.png&quot;, dpi=300)<br>    return plt.show()</pre><pre>numerical_values = [&quot;tenure&quot;,&quot;MonthlyCharges&quot;,&quot;TotalCharges&quot;]<br>outlier_check_boxplot(df,numerical_values)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pz3NeY_lAB4hHNz2NWOevg.png" /></figure><p>From boxplots, we can take a conclusion that each numerical variable doesn’t have an outlier.</p><h3><strong>Feature Engineering</strong></h3><p>Raw data can be transformed into features that are suitable for machine learning models that process called feature engineering. The aim of feature engineering is to make a machine learning model for better learning and get more accuracy. In this article, we will label encoding for categorical variables that have two values, one hot encoding for categorical variables that have more than two values, and feature calling for numerical variables.</p><h4>Label Encoding</h4><p>Label encoding aims to convert categorical variables to numerical format. In this article, we will change categorical variables that have two values such as (Partner, Dependents, PhoneService, Churn, PaperlessBilling, and gender). Values of them just have Yes or No and we will change to 1 and 0 except gender is Female to 1 and Male to 0.</p><pre>feature_le = [&quot;Partner&quot;,&quot;Dependents&quot;,&quot;PhoneService&quot;, &quot;Churn&quot;,&quot;PaperlessBilling&quot;]<br>def label_encoding(df,features):<br>    for i in features:<br>        df[i] = df[i].map({&quot;Yes&quot;:1, &quot;No&quot;:0})<br>    return df<br><br>df = label_encoding(df,feature_le)<br>df[&quot;gender&quot;] = df[&quot;gender&quot;].map({&quot;Female&quot;:1, &quot;Male&quot;:0})</pre><h4>One Hot Encoding</h4><p>Same with label encoding, one hot encoding also changes categorical variables to numerical variables. But, one hot encoding takes more than two values. One hot encoding creates a new binary integer (1 or 0) column for each level of the categorical variable. Categorical variables that have more than two values are (MultipleLines, InternetService, OnlineSecurity, OnlineBackup, DeviceProtection, TechSupport, StreamingTV, StreamingMovies, Contract, PaymentMethod).</p><pre>features_ohe = [&quot;MultipleLines&quot;,&quot;InternetService&quot;,&quot;OnlineSecurity&quot;,&quot;OnlineBackup&quot;,<br>                &quot;DeviceProtection&quot;,&quot;TechSupport&quot;,&quot;StreamingTV&quot;,&quot;StreamingMovies&quot;,&quot;Contract&quot;,&quot;PaymentMethod&quot;]<br>df_ohe = pd.get_dummies(df, columns=features_ohe)</pre><h4>Feature Scaling</h4><p>In this article, we use MinMaxScaler for feature scaling. MinMaxScaler can make numerical variables scaled from the range 0 to 1. Feature scaling is important to interpret machine learning models to have features on the same scale. We will be scaling numerical variables such as MonthlyCharges, TotalCharges, and tenure.</p><pre>features_mms = [&quot;tenure&quot;,&quot;MonthlyCharges&quot;,&quot;TotalCharges&quot;]<br><br>df_mms = pd.DataFrame(df_ohe, columns=features_mms)<br>df_remaining = df_ohe.drop(columns=features_mms)<br><br>mms = MinMaxScaler(feature_range=(0,1))<br>rescaled_feature = mms.fit_transform(df_mms)<br><br>rescaled_feature_df = pd.DataFrame(rescaled_feature, columns=features_mms, index=df_remaining.index)<br>df = pd.concat([rescaled_feature_df,df_remaining],axis=1)</pre><h3>Correlation Analysis</h3><pre>plt.figure(figsize=(10,6))<br>df.corr()[&quot;Churn&quot;].sort_values(ascending=False).plot(kind=&quot;bar&quot;)<br>plt.savefig(&quot;correlation.png&quot;, dpi=300)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*7_6zadBdlZUwKiG7kuB5_g.png" /></figure><p>Correlation is a statistical method for testing the relationship between numerical or categorical variables. The following plot above is to know the correlation between some variables to target variable churn. The highest correlation is the Contract_Month-to-month variable so that variable is so related to churn rate. Tenure is had a negative correlation with churn so higher values from tenure make a lower churn.</p><h3>Train Test Split</h3><p>Train test split is a process to validate the data set and simulate how the model performs with new data. In this article, we create 80% of train data and 20% of testing data. The “Churn” column we rename (the “y”) and the features column we rename (the “X”).</p><pre>X = df.drop(columns = &quot;Churn&quot;)<br>y = df.Churn<br><br>X_train,X_test, y_train, y_test = train_test_split(X,y,test_size=0.2,random_state=42,stratify=y)<br>X_train.shape, X_test.shape, y_train.shape, y_test.shape</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*Ki9fWjmdw4mmhJD5a1pAwQ.png" /></figure><h3><strong>Model Selection and Evaluation Model</strong></h3><h4>Model Selection</h4><p>We use three models for churn classification, model that we use is:</p><ul><li><strong>K-Nearest Neighbors </strong>— quick, easy, and instance-based</li><li>Logistic Regression — This linear model</li><li>Neural Network — More complicated like neurons in the human brain.</li></ul><h4>Metric Evaluation</h4><p>For evaluating the model we use some metrics evaluation such as:</p><ul><li>Feature Weights — List the top weight of the features to make a prediction. Feature weights are used for the logistic regression model</li><li>Confusion Matrix — Show the true and false then compare to prediction and actual values.</li><li>Accuracy Score — Show the accuracy model from training and testing to measure that a model is suitable for prediction.</li><li>ROC Curve — Show the curve of True Positive Rate (TPR) against False Positive Rate (FPR) for different thresholds and the ROC curve is used for the diagnostic machine learning model.</li><li>AUC (for ROC) — Area Under Curve (AUC) is used to calculate the area of the ROC Curve and increasing area is better for the model.</li><li>Precision-Recall-Curve — Show the curve to compare the False Positive Rate (FPR) and False Negative Rate (FNR) for different thresholds and this metric is used to demonstrate the diagnostic model capability. This metric is suitable for imbalanced target data sets due to the focus on precision and recall and not dependent on the number of true negatives.</li><li>F1 Score — This metric is usually better for accuracy, especially if it has an imbalanced data set target distribution.</li><li>AUC (for PRC) — Measure the overall area under the curve of PRC.</li></ul><h4>Creates Function For Displaying Evaluation Metrics</h4><pre># For logistic Regression<br>def feature_weights(X_df, classifier, classifier_name):<br>    weights = pd.Series(classifier.coef_[0], index = X_df.columns.values).sort_values(ascending=False)<br>    <br>    top_10_weights = weights[:10]<br>    plt.figure(figsize=(7,6))<br>    plt.title(f&quot;{classifier_name} - Top 10 Features&quot;)<br>    top_10_weights.plot(kind=&quot;bar&quot;)<br>    <br>    bottom_10_weights = weights[len(weights)-10:]<br>    plt.figure(figsize=(7,6))<br>    plt.title(f&quot;{classifier_name} - Bottom 10 Features&quot;)<br>    bottom_10_weights.plot(kind=&quot;bar&quot;)<br>    print(&quot;&quot;)</pre><pre>def confusion_matrix_plot(X_train, y_train, X_test, y_test, y_pred, classifier, classifier_name):<br>    cm = confusion_matrix(y_pred,y_test)<br>    disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=[&quot;No Churn&quot;, &quot;Churn&quot;])<br>    disp.plot()<br>    plt.title(f&quot;Confusion Matrix - {classifier_name}&quot;)<br>    plt.show()<br>    <br>    print(f&quot;Accuracy Score Test = {accuracy_score(y_pred,y_test)}&quot;)<br>    print(f&quot;Accuracy Score Train = {classifier.score(X_train,y_train)}&quot;)<br>    return print(&quot;\n&quot;)</pre><pre>def roc_curve_auc_score(X_test, y_test, y_pred_probabilities,classifier_name):<br>    y_pred_prob = y_pred_probabilities[:,1]<br>    fpr,tpr,thresholds = roc_curve(y_test, y_pred_prob)<br>    <br>    plt.plot([0,1],[0,1],&quot;k--&quot;)<br>    plt.plot(fpr,tpr,label=f&quot;{classifier_name}&quot;)<br>    plt.title(f&quot;{classifier_name} - ROC Curve&quot;)<br>    plt.xlabel(&quot;False Positive Rate&quot;)<br>    plt.ylabel(&quot;True Positive Rate&quot;)<br>    plt.show()<br>    return print(f&quot;AUC Score (ROC):{roc_auc_score(y_test,y_pred_prob)}&quot;)</pre><pre>def precision_recall_curve_and_scores(X_test, y_test, y_pred, y_pred_probabilities, classifier_name):<br>    y_pred_prob = y_pred_probabilities[:,1]<br>    precision, recall, thresholds = precision_recall_curve(y_test, y_pred_prob)<br>    plt.plot(recall,precision, label=f&quot;{classifier_name}&quot;)<br>    plt.title(f&quot;{classifier_name}-ROC Curve&quot;)<br>    plt.xlabel(&quot;Recall&quot;)<br>    plt.ylabel(&quot;Precision&quot;)<br>    plt.show()<br>    f1_score_result, auc_score = f1_score(y_test,y_pred), auc(recall,precision)<br>    return print(f&quot;f1 Score : {f1_score_result} \n AUC Score (PR) : {auc_score}&quot;)</pre><h4>K-Nearest Neighbor</h4><pre>from sklearn.neighbors import KNeighborsClassifier<br>knn = KNeighborsClassifier()<br>knn.fit(X_train, y_train)<br>y_pred_knn = knn.predict(X_test)<br>y_pred_knn_proba = knn.predict_proba(X_test)</pre><pre>confusion_matrix_plot(X_train,y_train,X_test, y_test, y_pred_knn, knn, &quot;K-Nearest Neighbors&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*WdahRckrcfBW-W9vBdeZZw.png" /></figure><pre>roc_curve_auc_score(X_test,y_test,y_pred_knn_proba, &quot;K-Nearest Neighbors&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*f9jxHrZZtJ2XNnQj2-TMDg.png" /></figure><pre>precision_recall_curve_and_scores(X_test,y_test,y_pred_knn,y_pred_knn_proba,&quot;K-Nearest Neighbors&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*YCkJGzA_bxdpvadczM1eBw.png" /></figure><h4>Logistic Regression</h4><pre>from sklearn.linear_model import LogisticRegression<br>logreg = LogisticRegression(max_iter=1000)<br>logreg.fit(X_train,y_train)<br>y_pred_logreg = logreg.predict(X_test)<br>y_pred_logreg_proba = logreg.predict_proba(X_test)</pre><pre>feature_weights(X_train,logreg,&quot;Logistic Regression&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*qjzaYrGIi8DrIgt4Ocj5hQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*7y9JBdps-JVAUw4L73-hxQ.png" /></figure><pre>confusion_matrix_plot(X_train,y_train,X_test,y_test, y_pred_logreg,logreg,&quot;Logistic Regression&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*qI5UQvzLU79yMg-nURlAbQ.png" /></figure><pre>confusion_matrix_plot(X_train,y_train,X_test,y_test, y_pred_logreg,logreg,&quot;Logistic Regression&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*M5vqkdj3Cm4GyEQ8iGi5eg.png" /></figure><pre>precision_recall_curve_and_scores(X_test,y_test,y_pred_knn,y_pred_logreg_proba,&quot;Logistic Regression&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*K7m06P9KX__1MUwAoE5FOw.png" /></figure><h4>Neural Network</h4><p>Neural Networks or Artificial Neural Networks (ANNs) are a subset of machine learning and the basis of deep learning. In this article, we use PyTorch to create a neural network model for classification.</p><pre>#Import package PyTorch for Neural Network<br>import torch<br>import torch.nn as nn<br>import torch.optim as optim<br>from torch.utils.data import Dataset, DataLoader</pre><pre># NN Model Parameter<br>EPOCHS = 50<br>BATCH_SIZE = 64<br>LEARNING_RATE = 0.001</pre><pre>#Make the classes for train data and test data<br>class TrainData(Dataset):<br>    def __init__(self,X_data,y_data):<br>        self.X_data = X_data<br>        self.y_data = y_data<br>    <br>    def __getitem__(self, index):<br>        return self.X_data[index], self.y_data[index]<br>    <br>    def __len__(self):<br>        return len(self.X_data)<br>    <br>class TestData(Dataset):<br>    def __init__(self,X_data):<br>        self.X_data = X_data<br>    <br>    def __getitem__(self,index):<br>        return self.X_data[index]<br>    <br>    def __len__(self):<br>        return len(self.X_data)</pre><pre>#creates train data and test data<br>train_data = TrainData(torch.FloatTensor(X_train.to_numpy()),<br>                      torch.FloatTensor(y_train.to_numpy()))<br>test_data = TestData(torch.FloatTensor(X_test.to_numpy()))</pre><pre>#Create a binary classification model<br>class BinaryClassification(nn.Module):<br>    def __init__(self):<br>        super(BinaryClassification, self).__init__()<br>        self.layer_1 = nn.Linear(X_train.shape[1],64)<br>        self.layer_2 = nn.Linear(40,64)<br>        self.layer_out = nn.Linear(64,1)<br>        <br>        self.relu = nn.ReLU()<br>        self.dropout = nn.Dropout(p=0.1)<br>        <br>    def forward(self, inputs):<br>        x = self.relu(self.layer_1(inputs))<br>        x = self.relu(self.layer_2(inputs))<br>        x = self.dropout(x)<br>        x = self.layer_out(x)<br>        return x</pre><pre>#Check the device that used<br>device = &quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;<br>device</pre><pre>model = BinaryClassification()<br>model.to(device)<br><br>print(model)<br>#Define loss function and optimizer<br>loss_fn = nn.BCEWithLogitsLoss()<br>optimizer = optim.Adam(model.parameters(), lr = LEARNING_RATE)</pre><pre># Create a function for calculate accuracy<br>def binary_acc(y_pred, y_test):<br>    y_pred_tag = torch.round(torch.sigmoid(y_pred))<br>    correct_results_sum = (y_pred_tag == y_test).sum().float()<br>    acc = correct_results_sum/y_test.shape[0]<br>    acc = torch.round(acc*100)<br>    return acc</pre><pre>#Training the neural network model<br>for epoch in range(EPOCHS):<br>    for X_train, y_train in train_loader:<br>        X_train, y_train = X_train.to(device), y_train.to(device)<br>        #Feed Forward<br>        y_pred = model(X_train)<br>        #Calculate Loss<br>        loss = loss_fn(y_pred,y_train.unsqueeze(1))<br>        acc = binary_acc(y_pred, y_train.unsqueeze(1))<br>        #Optimizer zero grad<br>        optimizer.zero_grad()<br>        #Loss Backward<br>        loss.backward()<br>        #Optimizer step<br>        optimizer.step()<br>    print(f&quot;Epoch : {epoch} | loss : {loss:.3f} | acc : {acc}&quot;)</pre><pre>#Testing the neural network model<br>y_pred_list = []<br>model.eval()<br>with torch.inference_mode():<br>    for X_test in test_loader:<br>        X_test = X_test.to(device)<br>        y_test_pred = model(X_test)<br>        y_test_pred = torch.sigmoid(y_test_pred)<br>        y_test_pred = torch.round(y_test_pred)<br>        y_pred_list.append(y_test_pred.cpu().numpy())<br>y_pred_list = [a.squeeze() for a in y_pred_list]</pre><pre>#Display confusion matrix<br>cm = confusion_matrix(y_test,y_pred_list)<br>display = ConfusionMatrixDisplay(confusion_matrix = cm, display_labels = [&quot;No Churn&quot;, &quot;Churn&quot;])<br>display.plot()<br>plt.title(&quot;Confusion Matrix - Neural Network&quot;)<br>plt.show()<br>print(f&quot;Accuracy Score : {accuracy_score(y_test, y_pred_list)}&quot;) </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*H8XO09Ronq6iu5vhmgQH2w.png" /></figure><pre>y_pred_probs = []<br>with torch.inference_mode():<br>    for X_test in test_loader:<br>        X_test = X_test.to(device)<br>        logits = model(X_test)<br>        y_pred_proba = torch.sigmoid(logits)<br>        y_pred_probs.append(y_pred_proba.cpu().numpy())<br>y_pred_prob = np.array(y_pred_probs).reshape(-1)<br>fpr, tpr, thresholds = roc_curve(y_test,y_pred_prob)<br>plt.plot([1,0],[1,0], &quot;k--&quot;)<br>plt.plot(fpr,tpr)<br>plt.title(&quot;ROC Curve - Neural Network&quot;)<br>plt.xlabel(&quot;False Positive Rate (FPR)&quot;)<br>plt.ylabel(&quot;True Positive Rate (TPR)&quot;)<br>plt.show()<br>print(f&quot;ROC Score = {roc_auc_score(y_test, y_pred_prob)}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*JvEZOforPeoolMxfgO7TiA.png" /></figure><pre>precision, recall, thresholds = precision_recall_curve(y_test,y_pred_prob)<br>plt.plot(recall, precision)<br>plt.xlabel(&quot;Recall&quot;)<br>plt.ylabel(&quot;Precision&quot;)<br>plt.title(&quot;Precision Recall Curve - Neural Network&quot;)<br>plt.show()<br>print(f&quot;F1 Score : {f1_score(y_test, y_pred_list)}&quot;)<br>print(f&quot;AUC (PRC) : {auc(recall, precision)}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*ZV_sWe12VG7f4TNqPFyAnA.png" /></figure><h3>Conclusion</h3><p>In this article, using the Telco Customer Churn dataset we have demonstrated an end-to-end machine learning project from beginning to end. Data cleaning and visualization were our first steps. Then, to give better data to train with the machine learning model we have to change categorical data to numerical data and we scale the numerical data (feature engineering). After that, we tried to build three machine-learning models and we evaluated that. Logistic regression has a high accuracy compared with Neural Networks and KNN. The ability to recognize potential customer scenarios where churn can be prevented requires a high level of accuracy since the benefits of the customer’s eventual returns must balance the expenses of associated retention initiatives.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d1905b04980" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>