One, foreword

This article mainly introduces the basic knowledge of Tensorflow and the use of its primary API through a simple demo. It is very suitable for the friends who want to contact Tensorflow machine learning but have no way to start. If you read this article, then congratulations, after reading it, you are sure to learn something!

Reading this article requires mastering some basic skills. Some Tensorflow basics, the concept of linear regression, javascript you Don’t Know.


Two, basic knowledge

What is Tensorflow?

  • TensorFlow™ is an open source software library that uses Data Flow Graphs for numerical calculations.
  • The Nodes represent mathematical operations, and the lines in the diagram represent arrays of multidimensional data related to each other between the Nodes, the tensor.
  • Its flexible architecture allows you to scale computing across multiple platforms, such as one or more cpus (or Gpus) on desktop computers, servers, mobile devices, and more. TensorFlow was originally developed by researchers and engineers in the Google Brain Group (part of the Google Machine Intelligence Research Institute) for machine learning and deep neural networks, but the system’s versatility makes it widely usable in other computing fields.

What is linear regression?

  • Linear regression is a statistical analysis method that uses regression analysis in mathematical statistics to determine the interdependent quantitative relationship between two or more variables, which is widely used. It is expressed as y = W ‘x+e, where the error follows a normal distribution with a mean of 0.

What is Machine Learning?

  • The core of machine learning is “using algorithms to parse data, learn from it, and then make a decision or prediction about something in the world.” This means that rather than explicitly writing a program to perform some task, you can teach a computer how to develop an algorithm to do it.

For example, deciding whether a picture is a cat? Let’s find a picture of a cat and write the rules for the picture of a cat. The picture is made up of pixels, so we need to judge pixels. But there are so many kinds of cats that we have too many rules to write. At this point, we can give the picture of the cat to machine learning, and also give other animals to machine learning, let the machine continue to learn, accumulate experience. Let’s give a new picture, and let the machine make the judgment, and now the machine has become a model machine that we have trained. Of course, this article is for beginners, so it won’t be too difficult.


Third, specific explanation

Tensorflowjs can run either in the front-end browser or in the back-end node. We used VUE here, because the ES6 modularity that VUE helped us deal with works in today’s browsers, and we used vue scaffolding to make our development more comfortable. Vue3.0 is used in this article.

1. Prepare data

  • The object we are working on is the main.js file under SRC. Delete everything from the file and start editing. The first step is to introduce the TensorFlow model and the Visualize package (Visualize), which is useful for analyzing the data. After introducing it, install it, install the commandnpm install --save @tensorflow/tfjs @tensorflow/tfjs-vis -s. Once the installation is complete, we need to place the data on the model. Here we have a simple linear relationship between the x and y axis books. The code is as follows:
import * as tf from '@tensorflow/tfjs';
import * as tfvis from '@tensorflow/tfjs-vis'; const xs = [1, 2, 3, 4]; // const yx = [1, 3, 5, 7]; / / y outputCopy the code

2. Data visualization

  • Rendering the data we created through one of TFVIS’s apis is our scatterPlot wave plot. Data in the form of dot graph display in our web page, but also set the name of the iconThe data set. Step 2 we use the map function to generate an array, each item is an object, and an index code, so that we can make the values of x and y correspond to each other[{x: 1, y: 1}, {x: 2, y: 3}]. The code is as follows:
window.onload = async () => {
  tfvis.render.scatterplot(
    {
      name: 'Data set'},) {// value an array of nested x and y values: xs.map((x, I) => {// value an array of nested x and y values: xs.map((x, I) => {return {
          x,
          y: yx[i]
        }
      })
    }
 }
Copy the code
  • rendering

Machine learning

  • Define model structure: a single neuron with an activation function. Add a neuron, single type in a single layer, and our data is one-to-one correspondence.
Sequential model = tf.sequential(); // Create a new model. // Model. Add (tf. Layers. Dense ({units: 1, inputShape: 1}))Copy the code
  • Set up the loss function and optimizer. Here, a loss function is defined to tell the machine to adjust in time if it is wrong. The adjustment uses our optimizer: Optimizer; Then we used the mean square error: meanSquaredError, which is as low as 0.1 error after optimization.
Compile ({// loss loss function tells error how much error is wrong // MSD mean square error // optimizer: Tf. Losses. MeanSquaredError, optimizer: tf. Train. SGD (0.1)})Copy the code

4. Training model

  • Train the model and visualize the training process
  const input = tf.tensor(xs), labels = tf.tensor(yx);
Copy the code
  • By creating model instances and representing the data as tensors, we are ready to start running the model.
{batchSize: 4, batchSize: the size of each batch of data to learn several epochs: 100, // epochs: FitCallbacks: tfvis.show.fitCallbacks({name:'Training process'},'loss']   // loss
    )
Copy the code

5. Test the model

const ouput = model.predict(tf.tensor([5])) 
  console.log(ouput.dataSync());
Copy the code

6. Test results


  • If you’ve done this, you’ve got your start on Tensorflow!

conclusion

Ok, after reading the article, are there any gains? Readers, if you think this article is helpful to your words, don’t forget to like 👍 and go again oh!

Github source address

liner-regression