Skip to main content

Prerequisites

Before getting started, ensure you have:
  • A modern web browser with JavaScript enabled
  • The TensorFlow.js library (loaded via CDN)
  • The trained model files in cnn_model/model.json format

Setup

1

Include TensorFlow.js

Add the TensorFlow.js library to your HTML file:
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@2.0.0/dist/tf.min.js"></script>
2

Define classification categories

Set up the seven skin cancer classification categories:
var model = null;
var classes = [
  'Actinic Keratoses',
  'Basal Cell Carcinoma',
  'Benign Keratoses',
  'Dermatofibroma',
  'Melanoma',
  'Melanocytic Nevus',
  'Vascular Lesion'
];
3

Load the model

Load the pre-trained VGG-16 model from your model files:
async function loadModel() {
  console.log("Loading Model");
  model = await tf.loadLayersModel('cnn_model/model.json');
  console.log("Loaded Model");
  
  // Update UI to show model is ready
  loadingmodel.innerHTML = "Loaded ML Model";
  progressbar.style.display = "none";
}

loadModel();

Making predictions

Once the model is loaded, you can classify skin lesion images using the predict() function:
async function predict() {
  try {
    if (imgtag.src == "") {
      alert("Select an Image to Classify");
      return;
    }

    // Preprocess the image: resize to 75x100 and convert to tensor
    let tensorImg = tf.browser.fromPixels(imgtag)
      .resizeNearestNeighbor([75, 100])
      .toFloat()
      .expandDims();
    
    // Run inference
    model.predict(tensorImg).data().then(
      function (prediction) {
        // Find the class with highest probability
        let predicted_class = prediction.indexOf(Math.max(...prediction));
        
        console.log(classes[predicted_class]);
        console.log(prediction);
        
        // Display results
        prediction_text.innerHTML = classes[predicted_class];
        probability_text.innerHTML = 
          Math.round(prediction[predicted_class] * 100) + "% Confidence";
      }
    );
  } catch (error) {
    alert("Error Classifying Image");
  }
}

Image preprocessing

The model expects images in a specific format:
Input dimensions: 75 pixels (height) x 100 pixels (width) x 3 channels (RGB)
The preprocessing pipeline:
  1. Convert to tensor: tf.browser.fromPixels() converts the HTML image element to a 3D tensor
  2. Resize: .resizeNearestNeighbor([75, 100]) resizes to the expected dimensions
  3. Normalize: .toFloat() converts pixel values to floating-point numbers
  4. Add batch dimension: .expandDims() adds a batch dimension for the model input

Handling image uploads

To load user-uploaded images:
function onFileSelected(event) {
  try {
    var selectedFile = event.target.files[0];
    var reader = new FileReader();
    
    imgtag.title = selectedFile.name;
    
    reader.onload = function(event) {
      imgtag.src = event.target.result;
    };
    
    reader.readAsDataURL(selectedFile);
  } catch (error) {
    alert("Error Reading Image");
  }
}
Connect this to your HTML file input:
<input type="file" accept="image/*" onchange="onFileSelected(event)">

Understanding the output

The model returns:
  • Predicted class: One of the 7 skin cancer categories
  • Confidence score: Probability percentage (0-100%) for the predicted class
  • Raw predictions: Array of probabilities for all 7 classes
This model is for educational purposes only. Do not use it as a substitute for professional medical diagnosis.

Next steps

Demo

See the complete web interface in action

Source code

View the full implementation on GitHub

Build docs developers (and LLMs) love