【问题标题】:Tensorflow.js - how to create a model for a simple sumTensorflow.js - 如何为简单求和创建模型
【发布时间】:2020-12-04 15:07:57
【问题描述】:

我开始研究 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
   ...

现在我想实现一个简单的求和,如下表所示。

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

【问题讨论】:

    标签: tensorflow configuration layer tensorflow.js


    【解决方案1】:

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

    只需设置 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();
    });
    

    【讨论】:

    • 非常感谢您的回归。而且,是的,这个想法现在只是为了理解更多基本概念,这让我可以进行下一步(计算器在我身边!)。
    猜你喜欢
    • 1970-01-01
    • 2021-11-28
    • 1970-01-01
    • 2021-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多