Table of Contents
What is a model?
What is a neural network?
#Training model
Training models with TensorFlow.js
Prediction with TensorFlow.js
Using a pre-trained model in TensorFlow.js
Import Keras model
Why should it be used in the browser?
Summary
Home Web Front-end JS Tutorial How to create a basic AI model with TensorFlow.js?

How to create a basic AI model with TensorFlow.js?

Nov 10, 2020 pm 05:54 PM
javascript tensorflow front end

How to create a basic AI model with TensorFlow.js?

In this article we look at how to use TensorFlow.js to create basic AI models and use more complex models to achieve some interesting functions. I have just started to come into contact with artificial intelligence. Although in-depth knowledge of artificial intelligence is not required, I still need to understand some concepts.

What is a model?

The real world is very complex, and we need to simplify it to understand it. We can simplify it through models. There are many types of models: such as world maps, or charts, etc.

How to create a basic AI model with TensorFlow.js?

For example, if you want to build a model to express the relationship between house rental price and house area: First, you need to collect some data:

##3131000 31250004235000##45

Then, display these data on a two-dimensional graph, and treat each parameter (price, number of rooms) as 1 dimension:

How to create a basic AI model with TensorFlow.js?

Then we can Draw a line and predict the rental price of a house with more rooms. This model is called linear regression, and it is one of the simplest models in machine learning. But this model is not good enough:

  1. There are only 5 data, so it is not reliable enough.
  2. There are only 2 parameters (price, room), but there are more factors that may affect the price: such as area, decoration, etc.

The first problem can be solved by adding more data, say a million. For the second question, more dimensions can be added. In a two-dimensional chart it is easy to understand the data and draw a line, in a three-dimensional chart you can use a plane:

How to create a basic AI model with TensorFlow.js?

But what about when the dimensions of the data are three dimensions, four dimensions or even 1000000 When the dimension exceeds three dimensions, the brain has no way to visualize it on a chart, but the hyperplane can be calculated mathematically when the dimension exceeds three dimensions, and neural networks were born to solve this problem.

What is a neural network?

To understand what a neural network is, you need to know what a neuron is. A real neuron looks like this:

How to create a basic AI model with TensorFlow.js?

A neuron is composed of the following parts:

  • Dendrite : This is the input end of the data.
  • Axon: This is the output end.
  • Synapse (not represented in the diagram): This structure allows communication between one neuron and another. It is responsible for transmitting electrical signals between the nerve endings of axons and the dendrites of nearby neurons. These synapses are key to learning because they increase or decrease electrical activity depending on their use.

Neurons in machine learning (simplified):

How to create a basic AI model with TensorFlow.js?

  • Inputs (inputs) : Inputs parameter.
  • Weights: Like synapses, used to better establish linear regression by adjusting neurons.
  • Linear function: Each neuron is like a linear regression function. For a linear regression model, only one neuron is enough.
  • Activation function: Some activation functions can be used to change the output from a scalar to another non-linear function. Common ones are sigmoid, RELU and tanh.
  • Output (output) : The calculated output after applying the activation function.

The activation function is very useful, and the power of neural networks is mainly attributed to it. Without any activation function, it is impossible to get an intelligent neuron network. Because even though you have multiple neurons in your neural network, the output of your neural network will always be a linear regression. Therefore, some mechanism is needed to transform each linear regression into nonlinear to solve nonlinear problems. These linear functions can be converted into nonlinear functions through the activation function:

How to create a basic AI model with TensorFlow.js?

#Training model

As described in the 2D linear regression example, just Draw a line in the graph to predict new data. Still, the idea of ​​"deep learning" is to have our neural network learn to draw this line. For a simple line, you can use a very simple neural network with only one neuron, but for a model that wants to do more complex things, such as classifying two sets of data, the network needs to be "trained" Learn how to get the following:

How to create a basic AI model with TensorFlow.js?

The process is not complicated because it is two-dimensional. Each model is used to describe a world, but the concept of "training" is very similar across all models. The first step is to draw a random line and improve it iteratively in the algorithm, correcting errors in the process during each iteration. This optimization algorithm is called Gradient Descent (algorithms with the same concept are also more complex SGD or ADAM, etc.). Each algorithm (linear regression, logarithmic regression, etc.) has a different cost function to measure the error, and the cost function will always converge to a certain point. It can be a convex or concave function, but it will eventually converge to a point with 0% error. Our goal is to achieve this.

How to create a basic AI model with TensorFlow.js?

When using the gradient descent algorithm, we start from some random point in its cost function, but we don't know where it is! It's like being blindfolded and thrown on a mountain. If you want to go down the mountain, you have to go to the lowest point step by step. If the terrain is irregular (such as a concave function), the descent will be more complicated.

I won’t explain the “gradient descent” algorithm in depth here. It’s enough to remember that this is an optimization algorithm for minimizing prediction errors in the process of training AI models. This algorithm requires a lot of time and GPU for matrix multiplication. It is usually difficult to reach this convergence point on the first execution, so some hyperparameters need to be modified, such as the learning rate or adding regularization. After gradient descent iterations, the convergence point is approached when the error approaches 0%. This creates a model that can then be used to make predictions.

How to create a basic AI model with TensorFlow.js?

Training models with TensorFlow.js

TensorFlow.js provides an easy way to create neural networks. First create a LinearModel class using the trainModel method. We will use a sequential model. A sequential model is a model in which the output of one layer is the input to the next layer, i.e. when the model topology is a simple hierarchy with no branches or skips. Define the layers inside the trainModel method (we use only one layer as it is enough to solve the linear regression problem):

import * as tf from '@tensorflow/tfjs';

/**
* 线性模型类
*/
export default class LinearModel {
  /**
 * 训练模型
 */
  async trainModel(xs, ys){
    const layers = tf.layers.dense({
      units: 1, // 输出空间的纬度
      inputShape: [1], // 只有一个参数
    });
    const lossAndOptimizer = {
      loss: 'meanSquaredError',
      optimizer: 'sgd', // 随机梯度下降
    };

    this.linearModel = tf.sequential();
    this.linearModel.add(layers); // 添加一层
    this.linearModel.compile(lossAndOptimizer);

    // 开始模型训练
    await this.linearModel.fit(
      tf.tensor1d(xs),
      tf.tensor1d(ys),
    );
  }

  //...
}
Copy after login

Use this class for training:

const model = new LinearModel()

// xs 与 ys 是 数组成员(x-axis 与 y-axis)
await model.trainModel(xs, ys)
Copy after login

End of training Then you can start making predictions.

Prediction with TensorFlow.js

Although some hyperparameters need to be defined in advance when training the model, making general predictions is still easy. It is enough to pass the following code:

import * as tf from '@tensorflow/tfjs';

export default class LinearModel {
  ... //前面训练模型的代码

  predict(value){
    return Array.from(
      this.linearModel
      .predict(tf.tensor2d([value], [1, 1]))
      .dataSync()
    )
  }
}
Copy after login

Now you can predict:

const prediction = model.predict(500) // 预测数字 500
console.log(prediction) // => 420.423
Copy after login

How to create a basic AI model with TensorFlow.js?

Using a pre-trained model in TensorFlow.js

Training the model is the hardest part. First, the data is standardized for training, and all hyperparameters need to be set correctly, etc. For us beginners, we can directly use those pre-trained models. TensorFlow.js can use many pretrained models and can also import external models created with TensorFlow or Keras. For example, you can directly use the posenet model (real-time human posture assessment) to do some interesting projects:

How to create a basic AI model with TensorFlow.js?

The code of this Demo: https://github.com/aralroca/posenet- d3

It is easy to use:

import * as posenet from '@tensorflow-models/posenet'

// 设置一些常数
const imageScaleFactor = 0.5
const outputStride = 16
const flipHorizontal = true
const weight = 0.5

// 加载模型
const net = await posenet.load(weight)

// 进行预测
const poses = await net.estimateSinglePose(
  imageElement,
  imageScaleFactor,
  flipHorizontal,
  outputStride
)
Copy after login

This JSON is pose Variable:

{
  "score": 0.32371445304906,
  "keypoints": [
    {
      "position": {
        "y": 76.291801452637,
        "x": 253.36747741699
      },
      "part": "nose",
      "score": 0.99539834260941
    },
    {
      "position": {
        "y": 71.10383605957,
        "x": 253.54365539551
      },
      "part": "leftEye",
      "score": 0.98781454563141
    }
    // 后面还有: rightEye, leftEar, rightEar, leftShoulder, rightShoulder
    // leftElbow, rightElbow, leftWrist, rightWrist, leftHip, rightHip,
    // leftKnee, rightKnee, leftAnkle, rightAnkle...
  ]
}
Copy after login

You can see it from the official demo, use this model There are many interesting projects that can be developed.

How to create a basic AI model with TensorFlow.js?

Source code of this project: https://github.com/aralroca/fishFollow-posenet-tfjs

Import Keras model

External models can be imported into TensorFlow.js. Below is a program for number recognition using Keras model (h5 format). First, use tfjs_converter to convert the format of the model.

pip install tensorflowjs
Copy after login

Use the converter:

tensorflowjs_converter --input_format keras keras/cnn.h5 src/assets
Copy after login

Finally, import the model into JS code:

// 载入模型
const model = await tf.loadModel('./assets/model.json')

// 准备图片
let img = tf.fromPixels(imageData, 1)
img = img.reshape([1, 28, 28, 1])
img = tf.cast(img, 'float32')

// 进行预测
const output = model.predict(img)
Copy after login

It only takes a few lines of code to complete. Of course, you can add more logic to the code to achieve more functions. For example, you can write numbers on canvas and then get their images for prediction.

How to create a basic AI model with TensorFlow.js?

Source code of this project: https://github.com/aralroca/MNIST_React_TensorFlowJS

Why should it be used in the browser?

Due to different devices, the efficiency may be very low when training the model in the browser. Using TensorFlow.js to use WebGL to train the model in the background is 1.5 to 2 times slower than using the Python version of TensorFlow.

But before the emergence of TensorFlow.js, there was no API that could directly use machine learning models in the browser. Now, models can be trained and used offline in browser applications. And predictions are faster because there are no requests to the server. Another benefit is low cost since all these calculations are done on the client side.

Summary

  • A model is a simplified way of representing the real world that can be used to make predictions.
  • You can use neural networks to create models.
  • TensorFlow.js is a simple tool for creating neural networks.

English original address: https://aralroca.com/blog/first-steps-with-tensorflowjs

Author: Aral Roca

For more programming-related knowledge, please visit: Programming Courses! !

Number of rooms Price
265000
535000

The above is the detailed content of How to create a basic AI model with TensorFlow.js?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

PHP and Vue: a perfect pairing of front-end development tools PHP and Vue: a perfect pairing of front-end development tools Mar 16, 2024 pm 12:09 PM

PHP and Vue: a perfect pairing of front-end development tools. In today's era of rapid development of the Internet, front-end development has become increasingly important. As users have higher and higher requirements for the experience of websites and applications, front-end developers need to use more efficient and flexible tools to create responsive and interactive interfaces. As two important technologies in the field of front-end development, PHP and Vue.js can be regarded as perfect tools when paired together. This article will explore the combination of PHP and Vue, as well as detailed code examples to help readers better understand and apply these two

Questions frequently asked by front-end interviewers Questions frequently asked by front-end interviewers Mar 19, 2024 pm 02:24 PM

In front-end development interviews, common questions cover a wide range of topics, including HTML/CSS basics, JavaScript basics, frameworks and libraries, project experience, algorithms and data structures, performance optimization, cross-domain requests, front-end engineering, design patterns, and new technologies and trends. . Interviewer questions are designed to assess the candidate's technical skills, project experience, and understanding of industry trends. Therefore, candidates should be fully prepared in these areas to demonstrate their abilities and expertise.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Is Django front-end or back-end? check it out! Is Django front-end or back-end? check it out! Jan 19, 2024 am 08:37 AM

Django is a web application framework written in Python that emphasizes rapid development and clean methods. Although Django is a web framework, to answer the question whether Django is a front-end or a back-end, you need to have a deep understanding of the concepts of front-end and back-end. The front end refers to the interface that users directly interact with, and the back end refers to server-side programs. They interact with data through the HTTP protocol. When the front-end and back-end are separated, the front-end and back-end programs can be developed independently to implement business logic and interactive effects respectively, and data exchange.

Exploring Go language front-end technology: a new vision for front-end development Exploring Go language front-end technology: a new vision for front-end development Mar 28, 2024 pm 01:06 PM

As a fast and efficient programming language, Go language is widely popular in the field of back-end development. However, few people associate Go language with front-end development. In fact, using Go language for front-end development can not only improve efficiency, but also bring new horizons to developers. This article will explore the possibility of using the Go language for front-end development and provide specific code examples to help readers better understand this area. In traditional front-end development, JavaScript, HTML, and CSS are often used to build user interfaces

Django: A magical framework that can handle both front-end and back-end development! Django: A magical framework that can handle both front-end and back-end development! Jan 19, 2024 am 08:52 AM

Django: A magical framework that can handle both front-end and back-end development! Django is an efficient and scalable web application framework. It is able to support multiple web development models, including MVC and MTV, and can easily develop high-quality web applications. Django not only supports back-end development, but can also quickly build front-end interfaces and achieve flexible view display through template language. Django combines front-end development and back-end development into a seamless integration, so developers don’t have to specialize in learning

See all articles