Machine learning is to submit input data with known corresponding results and corresponding results to TensorFlow model to train the model. This step is machine learning.

Once the training is complete, we feed the model input data that we don’t yet know the outcome of, and the model predicts what the outcome will be. This step is the application of AI.

For example, the existing Sexy gambling officer of Macao casino has cast the dice online, and has already cast 4 times:

The first time it was one point,

The second time I got three points,

The third time was five,

The fourth time was seven points.

A few points at most are beside the point.

The point is, the model can predict when the fifth time will be.

You can probably see the pattern at a glance, or even refine the formula (function) to apply: the result = 2n-1.

But if you write programs that apply formulas, you’re not writing AI.

In fact, we train our models to derive that formula, not for programmers to derive it and write it down.

The more we tune the model, the closer it gets to the right formula.

Writing here, I can sum up one point: the training of models is to ask models to find formulas (functions) from data.

With this function, you can input data and return results.

CODING

Now let’s use the example of rolling a die to write the code.

First install the Parcel globally.

NPM init a project.

Then install TensorFlow:

npm install @tensorflow/tfjs --saveCopy the code

Create index.html and 1.js files and add 1.js to index.html.

Run parcel index.html to start the project.

Let’s start writing the demo code in 1.js:

TensorFlow import * as tf from '@tensorflow/ TFJS '// Define linear decay model const model = tf.sequential() // add method to add a layer instance // Model. Add (tf. Layers. Dense ({units: 1, inputShape: [1]}) // Compile ({loss: 'meanSquaredError', optimizer: Const xs = tf.tensor2d([1, 2, 3, 4], const xs = tf.tensor2d([1, 2, 3, 4], Const ys = tf.tensor2d([1, 3, 5, 7], [4, 1]) // async function train() {// for loop to increase the number of training, For (let index = 0; index < 30; Index++) {// fit method training model, epochs = await model.fit(xs, ys, {epochs: 10})} // This method is used to predict the results of the test. Model. Predict (tf.tensor2d([5], [1, 1])).print()} train()Copy the code

OK!

In the browser console we can see the result of the above code:

Tensor
[[8.7086086],]Copy the code

The predicted result is 8.7086086, which differs about 0.3 from the correct result 9.

If we adjust the code and increase the number of training sessions by 10 times:

for (let index = 0; index < 300; index++)Copy the code

And the results:

Tensor
[[8.9998331],]Copy the code

That’s close to nine!

At this point, we’ve already scratched the surface of AI.

This article is the first example I wrote after learning TensorFlow, as an extract summary, and notes to share.