0% found this document useful (0 votes)
13 views5 pages

Skin PRJ

Uploaded by

dksk0945
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views5 pages

Skin PRJ

Uploaded by

dksk0945
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 5

import os, glob

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd

from sklearn.model_selection import train_test_split


from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
from tensorflow.keras.callbacks import Callback,EarlyStopping
from tensorflow.keras.applications import ResNet50
from tensorflow.keras.applications.resnet50 import preprocess_input
from sklearn.metrics import classification_report

file_path = 'archive (2)/data/train'

name_class = os.listdir(file_path)
name_class
['benign', 'malignant']

filepaths = list(glob.glob(file_path+'/**/*.*'))

labels = list(map(lambda x: os.path.split(os.path.split(x)[0])[1], filepaths))


labels

filepath = pd.Series(filepaths, name='Filepath').astype(str)


labels = pd.Series(labels, name='Label')
data = pd.concat([filepath, labels], axis=1)
data = data.sample(frac=1).reset_index(drop=True)
data.head(5)
Filepath Label
0 archive (2)/data/train\malignant\1117.jpg malignant
1 archive (2)/data/train\benign\1513.jpg benign
2 archive (2)/data/train\benign\78.jpg benign
3 archive (2)/data/train\benign\35.jpg benign
4 archive (2)/data/train\malignant\115.jpg malignant

counts = data.Label.value_counts()
sns.barplot(x=counts.index, y=counts)
plt.xlabel('Type')
plt.xticks(rotation=90);

total_samples = len(data)
malignant_count = data[data['Label'] == 'malignant'].shape[0]
benign_count = data[data['Label'] == 'benign'].shape[0]

print(f"Total Samples: {total_samples}")


print(f"Malignant Samples: {malignant_count}")
print(f"Benign Samples: {benign_count}")
Total Samples: 2637
Malignant Samples: 1197
Benign Samples: 1440

train, test = train_test_split(data, test_size=0.25, random_state=42)

fig, axes = plt.subplots(nrows=5, ncols=3, figsize=(10,8), subplot_kw={'xticks':


[],'yticks':[]})
for i, ax in enumerate(axes.flat):
ax.imshow(plt.imread(data.Filepath[i]))
ax.set_title(data.Label[i])
plt.tight_layout()
plt.show()

train_datagen = ImageDataGenerator(preprocessing_function=preprocess_input)
test_datagen = ImageDataGenerator(preprocessing_function=preprocess_input)

train_gen = train_datagen.flow_from_dataframe(
dataframe=train,
x_col='Filepath',
y_col='Label',
target_size=(100,100),
class_mode='categorical',
batch_size=32,
shuffle=True,
seed=42
)
valid_gen = train_datagen.flow_from_dataframe(
dataframe=test,
x_col='Filepath',
y_col='Label',
target_size=(100,100),
class_mode='categorical',
batch_size=32,
shuffle=False,
seed=42
)
test_gen = test_datagen.flow_from_dataframe(
dataframe=test,
x_col='Filepath',
y_col='Label',
target_size=(100,100),
class_mode='categorical',
batch_size=32,
shuffle=False
)
Found 1977 validated image filenames belonging to 2 classes.
Found 660 validated image filenames belonging to 2 classes.
Found 660 validated image filenames belonging to 2 classes.

pretrained_model = ResNet50(
input_shape=(100,100, 3),
include_top=False,
weights='imagenet',
pooling='avg'
)

pretrained_model.trainable = False

inputs = pretrained_model.input

x = Dense(128, activation='relu')(pretrained_model.output)
x = Dense(128, activation='relu')(x)

outputs = Dense(2, activation='softmax')(x)

model = Model(inputs=inputs, outputs=outputs)

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

my_callbacks = [EarlyStopping(monitor='val_accuracy',
min_delta=0,
patience=2,
mode='auto')]

history = model.fit(
train_gen,
validation_data=valid_gen,
epochs=100
)

model.save("model_SkinCancer.h5")

pd.DataFrame(history.history)[['accuracy','val_accuracy']].plot()
plt.title("Accuracy")
plt.show()

pd.DataFrame(history.history)[['loss','val_loss']].plot()
plt.title("Loss")
plt.show()

results = model.evaluate(test_gen, verbose=0)

print(" Test Loss: {:.5f}".format(results[0]))


print("Test Accuracy: {:.2f}%".format(results[1] * 100))
Test Loss: 1.22177
Test Accuracy: 84.24%
# Predict the label of the test_gen
pred = model.predict(test_gen)
pred = np.argmax(pred,axis=1)

# Map the label


labels = (train_gen.class_indices)
labels = dict((v,k) for k,v in labels.items())
pred = [labels[k] for k in pred]

y_test = list(test.Label)
print(classification_report(y_test, pred))
precision recall f1-score support

benign 0.86 0.85 0.86 362


malignant 0.82 0.84 0.83 298

accuracy 0.84 660


macro avg 0.84 0.84 0.84 660
weighted avg 0.84 0.84 0.84 660

from tensorflow.keras.models import load_model


from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.resnet50 import preprocess_input
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

# Load the trained model


model = load_model("model_SkinCancer.h5")

# Define the path to the downloaded image


custom_image_path = "Skin_Cancer_Custom/mali3.jpg"

# Function to classify custom input and display the image


def classify_and_display(custom_image_path):
# Preprocess the input image
img = image.load_img(custom_image_path, target_size=(100, 100))
img_array = image.img_to_array(img)
img_array = np.expand_dims(img_array, axis=0)
img_array = preprocess_input(img_array)

# Make predictions
predictions = model.predict(img_array)

# Post-process predictions
predicted_class_index = np.argmax(predictions)
class_labels = {0: 'benign', 1: 'malignant'}
predicted_class_label = class_labels[predicted_class_index]
confidence = predictions[0][predicted_class_index]

# Display the image and prediction details


img = mpimg.imread(custom_image_path)
plt.imshow(img)
plt.title(f"The predicted class is: {predicted_class_label}\nAccuracy:
{confidence:.2%}")
plt.axis('off')
plt.show()

# Classify and display the downloaded image


classify_and_display(custom_image_path)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy