ml5.js

repository·main·Indexed 41 days ago

https://github.com/ml5js/ml5-next-gen

A friendly machine learning library for the web, version 1.4.0, designed for artists, students, and creative coders. Built on top of TensorFlow.js and inspired by p5.js and Processing, it provides accessible browser-based ML models for tasks including pose detection (MoveNet, BlazePose), body segmentation (BodyPix, SelfieSegmentation), image and sound classification, and neural networks.

Tokens
18K
Snippets
65
Records
78
Agent score
52%

What's inside ml5.js

  1. Install ml5.js via CDN

    main

    You can include ml5.js in your HTML document by fetching it from unpkg. You can either fetch the latest 1.x version or specify a specific version for stability.

    <!-- Fetch the latest 1.x version -->
    <script src="https://unpkg.com/ml5@1/dist/ml5.js"></script>
    
    <!-- Fetch a specific version -->
    <script src="https://unpkg.com/ml5@<version>/dist/ml5.min.js"></script>
    
    <!-- Example: Fetching version 0.6.1 -->
    <script src="https://unpkg.com/ml5@0.6.1/dist/ml5.min.js"></script>
  2. Explore ml5.js examples in the p5.js Web Editor

    main
    You can experiment with ml5.js without any local setup by using the p5.js Web Editor. The repository provides numerous example sketches that can be opened and run directly in the browser. These examples cover a wide range of machine learning tasks including pose detection, segmentation, depth estimation, face mesh, feature extraction, hand pose, image classification, neural networks, neuroevolution, object detection, sentiment analysis, and sound classification.
  3. Visualize neural network training with NeuralNetworkVis

    main

    The NeuralNetworkVis class provides utility methods to visualize neural network training progress and data distributions using @tensorflow/tfjs-vis.

    Key capabilities include:

    • Viewing model summaries.
    • Generating scatterplots for specific input/output pairs or all pairs.
    • Creating bar charts for specific labels.
    • Visualizing training performance (loss and accuracy) during the training process.
    import NeuralNetworkVis from 'ml5/src/NeuralNetwork/NeuralNetworkVis.js';
    
    const vis = new NeuralNetworkVis();
    // Use vis methods to visualize models and data
  4. Understand DepthEstimationResult

    main

    The estimate() and estimateStart() methods return a DepthEstimationResult object containing the following properties:

    • data: Raw depth map as a 2D array.
    • image: A p5.Image (if p5 is running) or ImageData of the depth map with the chosen colormap.
    • imageData: ImageData visualization (normalized) with the chosen colormap.
    • width: Width of the depth map.
    • height: Height of the depth map.
    • minDepth: The minimum depth value used for normalization in this result.
    • maxDepth: The maximum depth value used for normalization in this result.
    • getDepthAt(x, y): A function that returns the raw depth at the specified (x, y) coordinates, or null if out of bounds.
    • mask: A p5.Image of the segmentation mask (if applySegmentationMask is true).
    • sourceFrame: A p5.Image of the exact frame used for the estimation.
  5. Understand how ml5js handles multiple optional arguments

    main

    ml5js uses a utility called handleArguments to allow developers to pass arguments to model constructors or methods in any order. Instead of strictly following a positional argument pattern, the library inspects the type of each argument provided and maps it to a named property.

    Argument Mapping Logic

    When you pass arguments, they are categorized as follows:

    • string: Assigned to string (often used for model names or URLs).
    • number: Assigned to number.
    • function: Assigned to callback.
    • Array: Assigned to array.
    • HTMLVideoElement: Assigned to both video and audio.
    • HTMLImageElement / HTMLCanvasElement / ImageData / tf.Tensor3D: Assigned to image.
    • Other Objects: Any object that doesn't match the media types above is treated as an options object.

    Usage Pattern

    Because the library identifies arguments by type, you can often omit arguments or change their order. However, if you provide multiple arguments of the same type (e.g., two different objects), the last one provided will override the previous ones.

    Example of flexible argument passing:

    // Instead of: model.predict(image, options, callback)
    // You can do:
    model.predict(callback, image, options);
  6. Understand HandPose detection results

    main

    The HandPose model returns an array of hand objects. The raw TensorFlow.js output is enhanced for ease of use:

    1. Confidence: The score property from the original model is renamed to confidence.
    2. Keypoints: Each keypoint in the keypoints array is augmented with named properties. For each keypoint, you can access its coordinates via its name (e.g., if the keypoint is 'wrist', you can access hand.wrist).

    Keypoint Structure: Each named keypoint object contains:

    • x: 2D x-coordinate
    • y: 2D y-coordinate
    • x3D: 3D x-coordinate
    • y3D: 3D y-coordinate
    • z3D: 3D z-coordinate
    const results = await myHandPose.detect(videoElement);
    
    results.forEach(hand => {
      console.log(hand.confidence); // Renamed from score
      
      // Accessing augmented keypoints by name
      if (hand.wrist) {
        console.log('Wrist X:', hand.wrist.x, 'Wrist Y:', hand.wrist.y);
        console.log('Wrist 3D Z:', hand.wrist.z3D);
      }
    });
  7. Supported image and media input types in ml5js

    main

    ml5js models are designed to be flexible with input types. When providing data for image-based models, you can use any of the following formats:

    • HTML Elements: HTMLImageElement, HTMLCanvasElement, HTMLVideoElement, or OffscreenCanvas.
    • TensorFlow.js: A 3D Tensor (tf.Tensor3D).
    • ImageData: Standard ImageData objects.
    • p5.js: p5.Image, p5.Video, or any p5.Element (objects containing .elt or .canvas).

    Note that HTMLVideoElement is treated as both an image and audio source by the internal argument handler.

    // Example of the variety of inputs accepted by ml5 models:
    // 1. HTML Image
    const img = document.getElementById('my-image');
    // 2. HTML Video
    const video = document.getElementById('my-video');
    // 3. p5.js Image
    const p5Img = myP5Instance.loadImage('path/to/img.png');
    // 4. TensorFlow Tensor
    const tensor = tf.browser.fromPixels(img).expandDims(0); // (Note: models usually expect 3D tensors)
  8. Understand the BodyPose detection result format

    main

    The detection results are returned as an array of pose objects. The BodyPose class enhances the raw TensorFlow.js output with several features:

    1. Confidence Renaming: The score property in keypoints is renamed to confidence for consistency.
    2. Named Keypoints: Keypoints are added directly to the pose object by their name (e.g., pose.nose.x, pose.left_shoulder.y) for easier access.
    3. 3D Keypoints: If using BlazePose, 3D keypoints are available via pose.keypoint3D properties attached to the named keypoints.
    4. Bounding Boxes: Bounding boxes are resized to match the dimensions of the input media.
    5. Mirroring: If flipHorizontal is set in the runtime configuration, keypoints and bounding boxes are mirrored around the x-axis.
  9. How ObjectDetection works

    main

    The ObjectDetection class provides a high-level interface for running computer vision models on web media.

    Lifecycle

    1. Initialization: Calling objectDetection() creates an instance and begins loading the specified model (defaulting to cocossd).
    2. Ready State: The instance provides a ready property (a Promise) that resolves when the model is fully loaded and ready for inference.
    3. Inference Modes:
      • Single Shot: Use detect() for a one-time analysis of an image or video frame.
      • Continuous Loop: Use detectStart() to enter a loop where the model automatically processes subsequent frames of a video or canvas. This loop is managed via requestAnimationFrame and can be broken using detectStop().

    Supported Models

    Currently, the implementation primarily supports the cocossd (COCO Single Shot MultiBox Detector) model.

  10. Initialize BodyPose with bodyPose()

    main

    To use the BodyPose model, call the bodyPose() factory function. You must specify a modelName (either 'MoveNet' or 'BlazePose') and can optionally provide a configuration object and a callback function that executes once the model is loaded.

    Note: The bodyPose() function is the recommended way to create an instance, rather than using the BodyPose class directly.

    // Example initialization
    const bodyPose = ml5.bodyPose('MoveNet', { enableSmoothing: true }, () => {
      console.log('Model is ready!');
    });
  11. Build and train a custom NeuralNetwork

    main

    The NeuralNetwork class allows you to build, compile, and train custom TensorFlow.js models. You can define a sequential model, add layers, compile it with specific options, and train it using input and output tensors.

    Workflow:

    1. Instantiate NeuralNetwork (automatically calls createModel).
    2. Use addLayer(layer) to add TensorFlow.js layers.
    3. Use compile(options) to configure the model.
    4. Use train(options) to start the training process.

    Training Options: Pass an object to train() containing:

    • inputs: The training input tensors.
    • outputs: The training output tensors.
    • batchSize: Number of samples per gradient update.
    • epochs: Number of iterations over the dataset.
    • shuffle: Boolean to shuffle data.
    • validationSplit: Fraction of data to use for validation.
    • whileTraining: Callbacks for the training lifecycle.
    import NeuralNetwork from 'ml5/src/NeuralNetwork/NeuralNetwork';
    import * as tf from '@tensorflow/tfjs';
    
    const nn = new NeuralNetwork();
    
    // 1. Add layers
    nn.addLayer(tf.layers.dense({ units: 10, activation: 'relu', inputShape: [5] }));
    nn.addLayer(tf.layers.dense({ units: 1 }));
    
    // 2. Compile
    nn.compile({ optimizer: 'adam', loss: 'meanSquaredError' });
    
    // 3. Train
    await nn.train({
      inputs: tf.tensor2d([[1, 2, 3, 4, 5]]),
      outputs: tf.tensor2d([[1]]),
      epochs: 10,
      batchSize: 1
    });