Hemant0000's picture
Update app.py
f68f46e verified
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.applications import MobileNetV2
from tensorflow.keras import layers, models
import tensorflow as tf
labels = ['Actinic Keratosis', 'Atopic Dermatitis', 'Benign Keratosis',
'Dermatofibroma', 'Melanocytic nevus', 'Melanoma',
'Squamous cell carcinoma', 'Tinea Ringworm candidiasis',
'Vascular lesion']
# Image data generator with augmentation
train_datagen = ImageDataGenerator(
rescale=1.0/255,
rotation_range=20,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True,
fill_mode='nearest'
)
test_datagen = ImageDataGenerator(rescale=1.0/255)
train_generator = train_datagen.flow_from_directory(
'train',
target_size=(150, 150),
batch_size=32,
class_mode='categorical'
)
validation_generator = test_datagen.flow_from_directory(
'val',
target_size=(150, 150),
batch_size=32,
class_mode='categorical'
)
# Model architecture
base_model = MobileNetV2(weights='imagenet', include_top=False, input_shape=(150, 150, 3))
base_model.trainable = False # Freeze the base model
model = tf.keras.models.Sequential([
base_model,
layers.GlobalAveragePooling2D(),
layers.Dense(1024, activation='relu'),
layers.Dense(len(labels), activation='softmax')
])
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
# Training
history = model.fit(
train_generator,
steps_per_epoch=train_generator.samples // 32,
validation_data=validation_generator,
validation_steps=validation_generator.samples // 32,
epochs=20
)
# Save the model
model.save('skin_disease_model.h5')
import gradio as gr
import numpy as np
import tensorflow as tf
# Load your trained model
model = tf.keras.models.load_model('skin_disease_model.h5') # Update with your model path
# Class labels
labels = ['Actinic Keratosis', 'Atopic Dermatitis', 'Benign Keratosis',
'Dermatofibroma', 'Melanocytic nevus', 'Melanoma',
'Squamous cell carcinoma', 'Tinea Ringworm candidiasis',
'Vascular lesion']
# Gradio function for prediction
def predict_skin_disease(img):
try:
# Preprocess the image
img = np.array(img) / 255.0 # Normalize
img = tf.image.resize(img, (150, 150)) # Resize to match model input
img = np.expand_dims(img, axis=0) # Add batch dimension
# Make prediction using the model
prediction = model.predict(img)
# Convert prediction to a dictionary of class labels and probabilities
return {labels[i]: float(prediction[0][i]) for i in range(len(labels))}
except Exception as e:
return f"Error: {str(e)}"
# Gradio Interface
gr_interface = gr.Interface(
fn=predict_skin_disease,
inputs=gr.Image(type="numpy", label="Upload an Image of Skin Lesion"),
outputs=gr.Label(num_top_classes=3), # Display top 3 predictions
title="Skin Disease Classification",
description="Upload an image of a skin lesion to classify it into various skin diseases."
)
# Launch the Gradio interface
gr_interface.launch()