Tensorflow.js - 如何为简单求和创建模型

Tensorflow.js - how to create a model for a simple sum

我开始学习 tensoflow.js。我已经看到并重新创建了线性函数的预测示例;您最初拥有的位置:

async function learnLinear(){
   model = tf.sequential();
   // uma camada e um nó
   model.add(tf.layers.dense({units: 1, inputShape: [1]}));
   // 
   model.compile({
      loss: 'meanSquaredError', //funcao de perda: erro quadratico médio p/ funcoes lineares
      optimizer: 'sgd' // descida de gradiente estocástica - metodologia para o aprendizado
      });
   
   // abaixo valores x,y nos parametros e o segundo é o formato 6 linhas 1 coluna
   const xs = tf.tensor2d([-1, 0, 1, 2, 3, 4],[6, 1]); 
   const ys = tf.tensor2d([-3, -1, 1, 3, 5, 7], [6, 1]);

   // treinar o modelo em um número fixo de iterações (épocas)
   await model.fit(xs, ys, {epochs: 900}); // 900 iterações
   ...

现在我想按照下面 table 中的建议实现一个简单的求和。

但我无法为此创建模板配置(张量、层和训练的外观)。能举个例子吗?

您可以像您的示例一样进行简单的线性回归。这么多数据的结果会很糟糕,所以不要指望用它来代替你的计算器。

只需设置您的 x1 和 x2 张量,并让您的模型输入接受 2 个输入。

// Define a model for linear regression.
const model = tf.sequential();
model.add(tf.layers.dense({units: 1, inputShape: [2]}));

// Prepare the model for training: Specify the loss and the optimizer.
model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});

// Generate some synthetic data for training.
const x1 = tf.tensor2d([1, 1, 2, 1, 3], [5, 1]);
const x2 = tf.tensor2d([0, 1, 1, 1, 1], [5, 1]);
// we concat x1 and x2 to get an input of the shape [5,2]
// "Tensor [[1, 0],
//          [1, 1],
//          [2, 1],
//          [1, 1],
//          [3, 1]]"
const xs = tf.concat([x1,x2],1)
// The labels is just the sum of x1+x2
// "Tensor [[1],[2],[3],[2],[4]]"
const ys = tf.add(x1,x2)

// Train the model using the data.
model.fit(xs, ys, epochs=1000).then(() => {
  // Try one prediction. 
  // The result will be pretty bad because 
  // there is not much data
  model.predict(tf.tensor2d([0, 1], [1, 2])).print();
});