DeveloperBreeze

Tensorflow.Js Programming Tutorials, Guides & Best Practices

Explore 2+ expertly crafted tensorflow.js tutorials, components, and code examples. Stay productive and build faster with proven implementation strategies and design patterns from DeveloperBreeze.

Leveraging Machine Learning Models in Real-Time with TensorFlow.js and React: Building AI-Powered Interfaces

Tutorial August 20, 2024
javascript

import React, { useState, useEffect } from 'react';
import * as tf from '@tensorflow/tfjs';
import '@tensorflow/tfjs-backend-cpu';
import '@tensorflow/tfjs-backend-webgl';

function ImageClassifier() {
  const [image, setImage] = useState(null);
  const [model, setModel] = useState(null);

  useEffect(() => {
    const loadModel = async () => {
      const loadedModel = await tf.loadGraphModel('https://path-to-model/model.json');
      setModel(loadedModel);
    };

    loadModel();
  }, []);

  const handleImageUpload = (event) => {
    const file = event.target.files[0];
    const reader = new FileReader();

    reader.onload = () => {
      setImage(reader.result);
    };

    if (file) {
      reader.readAsDataURL(file);
    }
  };

  return (
    <div>
      <input type="file" accept="image/*" onChange={handleImageUpload} />
      {image && <img src={image} alt="Uploaded" />}
    </div>
  );
}

export default ImageClassifier;

Now that we have the model loaded and an image selected, we can run predictions on the uploaded image. TensorFlow.js allows us to process the image and get predictions using the loaded model.