predict() function performs skin cancer classification on the selected image using the loaded TensorFlow.js model.
Function signature
This is an asynchronous function. Ensure the model is loaded via
loadModel() and an image is selected via onFileSelected() before calling this function.Parameters
This function takes no parameters. It operates on the globalimgtag element that contains the selected image.
Return value
An array of confidence scores for each of the 7 skin cancer classes. The function doesn’t directly return this value but uses it internally to update the UI.
Classification classes
The model classifies images into 7 categories:- Actinic Keratoses
- Basal Cell Carcinoma
- Benign Keratoses
- Dermatofibroma
- Melanoma
- Melanocytic Nevus
- Vascular Lesion
How it works
The prediction process follows these steps:- Validates that an image has been selected
- Converts the image to a TensorFlow.js tensor
- Preprocesses the image (resize to 75x100, convert to float, expand dimensions)
- Runs the model prediction
- Identifies the class with highest confidence
- Updates the UI with the prediction and confidence percentage
Image preprocessing
The function performs the following preprocessing steps:- Converts the HTML image to pixels using
tf.browser.fromPixels() - Resizes to [75, 100] using nearest neighbor interpolation
- Converts to float tensor
- Expands dimensions to match model input shape
Code example
Implementation
Here’s the complete implementation from the source code:Error handling
The function includes comprehensive error handling:No image selected
Classification errors
Required global variables
The function depends on these global variables:Output format
The function updates two HTML elements with the results:prediction_text- Displays the predicted class name (e.g., “Melanoma”)probability_text- Displays the confidence percentage (e.g., “87% Confidence”)
Console output
The function also logs prediction details to the console:The confidence percentage is rounded to the nearest whole number using
Math.round().