# 快速上手

# 在浏览器中安装

# 使用script标签

<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@1.0.0/dist/tf.min.js"></script>

此时你可以通过http-server起一个服务来查看

npm install http-server -g

hs

点击到对应引用网页,在其js中写

const t1 = tf.tensor([1, 2]);
t1.print();
console.log(t1);

# 从NPM安装

您可以使用 npm cli工具或是yarn安装TensorFlow.js。

yarn add @tensorflow/tfjs

或者

npm install @tensorflow/tfjs 

使用parcel或者其他构建工具起一个服务,在其js文件中写

如使用parcel

npm install parcel -g

parcel index.html
const t1 = tf.tensor([1, 2]);
t1.print();
console.log(t1);
  • 技巧

可以先全局安装nrm,将下载地址景象到淘宝等源

npm install nrm -g

nrm ls

nrm use taobao

# 在node.js中安装

  • 安装带有原生c++绑定的tensorflow.js

  • 安装纯javascript版本,这是性能最慢的版本

首先还是要安装@tensorflow/tfjs这个包,然后修改代码

const tf = require('@tensorflow/tfjs');
const t1 = tf.tensor([1, 2]);
t1.print();
console.log(t1);
node xxx.js

============================
Hi there 👋. Looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, which binds to TensorFlow C++, by running npm i @tensorflow/tfjs-node, or npm i @tensorflow/tfjs-node-gpu if you have CUDA. Then call require('@tensorflow/tfjs-node'); (-gpu suffix for CUDA) at the start of your program. Visit https://github.com/tensorflow/tfjs-node for more details.
============================

npm i @tensorflow/tfjs-node // 苹果电脑的话可以直接安装

// window的话可能需要先依赖以下两个包

npm i node-gyp windows-build-tools@4.0.0 -g

修改代码

const tf = require('@tensorflow/tfjs-node');
node xxx.js

# tensorflow.js基本使用流程

构造tensor数据 -> 初始化模型 -> 给模型添加层 -> 给模型设置优化器、损失函数、激活函数等 -> 训练模型 -> 展示结果并根据逻辑进行下一步操作

示例:

import * as tf from '@tensorflow/tfjs';
import * as tfvis from '@tensorflow/tfjs-vis';
window.onload = async () => {
  const xs = [1, 2, 3, 4];
  const ys = [1, 3, 5, 7];
  /* 数据可视化 */
  tfvis.render.scatterplot(
    {
      name: '线性回归训练集',
    },
    {
      values: xs.map((x, i) => ({
        x,
        y: ys[i],
      })),
    },
    {
      xAxisDomain: [0, 5],
      yAxisDomain: [0, 8],
    },
  );

  /* 初始化模型 */
  const model = tf.sequential(); // 连续模型

  /*给模型添加层*/
  model.add(tf.layers.dense({
    units: 1, // 神经元个数
    inputShape: [1], //
  }));

  /*给模型设置损失函数与优化器*/
  model.compile({
    loss: tf.losses.meanSquaredError, // 损失函数-使用均方误差计算
    optimizer: tf.train.sgd(0.1), // 优化器-设置学习率
  });

  /*将训练数据转换成tensor*/
  const inputs = tf.tensor(xs);
  const labels = tf.tensor(ys);

  /*异步训练模型*/
  await model.fit(inputs, labels, {
    batchSize: 10, // 每次样本需要学习的样本数据量(2.5倍样本数=4epochs)
    epochs: 200, // 训练轮数
    callbacks: tfvis.show.fitCallbacks( // 可视化模拟训练过程
      { name: '训练过程' },
      ['loss'], // 制定度量单位(制作损失曲线)
    ),
  });

  /*输出预测结果并显示*/
  const output = model.predict(tf.tensor([5])); // 输入一个tensor帮你预测结果并赋值给变量
  console.log('output', output.dataSync());
  output.dataSync();
};