简介:作为Web开发人员,我们知道可以在浏览器中运行机器学习(Machine Learning)。但从哪里开始呢?2018年3月30日,TensorFlow团队展示了他们著名的机器学习(ML)框架TensorFlow的Javascript版本。TensorFlow.js允许我们 ...
create-react-app image-recognition现在,在App.js文件里面,我们将删除所有不必要的代码,只用ML5.js呈现一个名为Image classification的标题。 ml5.js入门完成后,我们将开始实施ml5.js. 该库将使我们的应用程序能够识别我们刚刚下载的图像上的内容。首先,使用终端安装ml5.js库:yarn add ml5安装完成后,我们将从ml5.js库中导入所有内容。然后,我们将在App组件中创建一个名为classifyImg的函数,该函数将:
在浏览器中显示结果!既然我们已经在App组件状态中进行了预测,那么我们要做的最后一件事就是将预测输出给用户。为此,在render方法中,我们将创建一个预测变量,该变量将在加载时存储默认值(现在div为空)。一旦模型做出预测并且它们存储在状态中,我们将映射预测数组以显示(1)模型的预测和(2)5个预测中的每个预测的概率。最后,我们将在我们的应用程序中显示预测,就在我们的 老虎图像下方,Javascript代码如下:import React, { Component } from "react";import "./App.css";import tiger from "./tiger.jpg";// Importing ml5.js as ml5import * as ml5 from "ml5";class App extends Component { state = { predictions: [] // Set the empty array predictions state } setPredictions = (pred) => { // Set the prediction state with the model predictions this.setState({ predictions: pred }); } classifyImg = () => { // Initialize the Image Classifier method with MobileNet const classifier = ml5.imageClassifier("MobileNet", modelLoaded); // When the model is loaded function modelLoaded() { console.log("Model Loaded!"); } // Put the image to classify inside a variable const image = document.getElementById("image"); // Make a prediction with a selected image classifier.predict(image, 5, function(err, results) { // Return the results return results; }) .then((results) => { // Set the predictions in the state this.setPredictions(results) }) } componentDidMount(){ // once the component has mount, start the classification this.classifyImg(); } render() { // First set the predictions to a default value while loading let predictions = (<div className="loader"></div>); // Map over the predictions and return each prediction with probability if(this.state.predictions.length > 0){ predictions = this.state.predictions.map((pred, i) => { let { className, probability } = pred; // round the probability with 2 decimal probability = Math.floor(probability * 10000) / 100 + "%"; return ( <div key={ i + "" }>{ i+1 }. Prediction: { className } at { probability } </div> ) }) } return ( <div className="App"> <h1>Image classification with ML5.js</h1> <img src={ tiger } id="image" width="400" alt="" /> { predictions } </div> ); }}export default App; h1 { margin: 0 0 1.4rem;}.App { padding: 1rem 0; display: flex; flex-direction: column; justify-content: center; align-items: center; min-height: calc(100vh - 2rem);}.App div { background-color: #eff6fe; width: 300px; padding: 10px 50px;}.App div:nth-of-type(odd) { background-color: #dfeeff;}div.loader { animation: loader-spin infinite 1.2s linear; padding: 0; background-color: transparent !important; height: 50px; width: 50px; border: 5px solid #eee; border-bottom: 5px solid #007bff; border-radius: 50% !important; margin: 2rem;}@keyframes loader-spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); }} |