【问题标题】:Tensorflow giving random answers on a regression problemTensorflow 对回归问题给出随机答案
【发布时间】:2019-05-29 18:18:01
【问题描述】:

我正在尝试使用 Tensorflow.js 使用 Node.js 重现 Python 练习。

目标是使用机器学习简单地将摄氏温度转换为华氏温度。

但是,我是 Tensorflow.js 的菜鸟,它总是给我随机的答案。

我尝试了多种方法,例如许多不同的形状。 我检查了 Python 和 Node.js 是否具有相同的模型。他们都有以下型号:

Layer (type)                 Output shape              Param #   
=================================================================
dense_Dense1 (Dense)         [null,1]                  2         
=================================================================
Total params: 2
Trainable params: 2
Non-trainable params: 0
const tf = require("@tensorflow/tfjs-node")

function convert(c){
    return (c*1.8)+32 // Convert celsius to fahrenheit
} 

var celsius = []
var fahrenheit = []

for (let i = 0; i < 20; i++) {
    var r = 100; // Keeping this only value to ensure that Tf knows the answer I also have tried with 20 different values but doesn't work
    celsius.push([r]) // Shape [20,1]
    fahrenheit.push([convert(r)]) // Push the answer (212) to the fahrenheit array
}

var model = tf.sequential();
model.add(tf.layers.dense({inputShape:[1], units: 1}))

async function trainModel(model, inputs, labels) {
    // Prepare the model for training.  
    model.compile({
      optimizer: tf.train.adam(),
      loss: tf.losses.meanSquaredError,
      metrics: ['accuracy'], // Accuracy = 0
    });

    model.summary(); 

    const epochs = 500;

    return await model.fit(inputs, labels, {
      epochs,
      batchSize: 20, 
      verbose: false // Nothing interesting with verbose
    });
  }

c = tf.tensor(celsius)
f = tf.tensor(fahrenheit)

var training = trainModel(model, c, f)

training.then(function(args){
    var prediction = model.predict(tf.tensor([[100]]));
    prediction.print(); // Prints a random number
    console.log("Real answer = "+convert(100)) 
})

输出的张量值每次都是随机变化的。 这是一个例子:

Tensor
     [[65.9411697],]
Real answer = 212

【问题讨论】:

  • 您希望模型如何从单个值中学习?
  • 我尝试了一组不同的值,但没有成功。确实,这里只有一个值是 100,但我也要求它预测 100。在任何情况下都不应该过拟合吗?
  • 看来问题出在优化器上,试试 'sgd' 作为优化器。我添加了一个带有工作示例的答案。

标签: javascript node.js tensorflow artificial-intelligence tensorflow.js


【解决方案1】:

似乎主要问题是优化器。 - 如果使用 SGD 优化器进行训练。预测工作正常。

const tf = require("@tensorflow/tfjs-node")
const nr_epochs=500; 

function convert(c){
  return (c*1.8)+32 // Convert celsius to fahrenheit
} 


let celsius = []
let fahrenheit = []

for (let i = 0; i < 100; i++) {
  var r = 100; // Keeping this only value to ensure that Tf knows the answer
  celsius.push(i) // Shape [20,1]
  fahrenheit.push(convert(i)) // Push the answer (212) to the fahrenheit array
}

const train = async (xy, ys) => {
  const model = tf.sequential();

  model.add(tf.layers.dense({units: 1, inputShape: [1]}));

  model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});
  await model.fit(xs,ys,{epochs: nr_epochs})
  return model;
}

const predict =  (model, n) => {
  const predicted =  model.predict(tf.tensor2d([n],[1,1])); 
  return predicted;
}

const xs = tf.tensor2d(celsius.slice (0,15), [15,1]);
const ys = tf.tensor2d(fahrenheit.slice (0,15), [15,1]);
(async () => {
  let trained = await train (xs,ys);
  for (let n of [4,6,12]) {
    let predicted = predict (trained, n).dataSync ();
    console.log (`Value: ${n} Predicted: ${predicted [0]}`)
  }
})()

日志:

Value: 4 Predicted: 38.01055908203125
Value: 6 Predicted: 42.033267974853516
Value: 12 Predicted: 54.101402282714844

【讨论】:

  • 确实……很奇怪,Python 使用了 adam。知道为什么吗?
  • @KillianC 坦率地说,我不知道。我也想知道——也许我明天会更深入地挖掘,无论如何我需要更好地了解。
  • 我用 python 和 tensorflow.js 尝试了同样的方法。在具有一层输入 = 1 和单元 = 1 的模型上对其进行训练。在 adam 和 mse 上使用 1500 个 epoch。它不收敛。它确实是 tensorflow.js 的一种奇怪行为,我让它在具有相同模型配置的 python 上工作,它在 50 个时期内收敛,损失小于 0.7e-4。
  • @nijeeshjoshy 感谢您的更新! - 这很有趣,我们可能需要研究 js 实现。 - 这也应该与亚当一起工作。明天我会尝试调试优化器。
【解决方案2】:

当我向模型添加另外 3 个更密集的层时,Adam 优化器起作用。但我让它只用一层就可以在 python 上的 adam 上工作。

xs = []
ys = []

for (var i = -100; i < 100; i++) {
  xs.push(i)
  ys.push( i*1.8 + 32)
}

console.log(xs,ys)

model = tf.sequential({
  layers: [
    tf.layers.dense({
            units: 4,
            inputShape: [1]
        }),
        tf.layers.dense({
            units: 4,
            inputShape: [4]
        }),
        tf.layers.dense({
            units: 4,
            inputShape: [4]
        }),
        tf.layers.dense({
            units: 1,
            inputShape: [4]
        })
  ]
})


model.compile({
  loss: 'meanSquaredError',
  optimizer: 'adam'
})

var tfxs = tf.tensor2d(xs,[xs.length,1])
var tfys = tf.tensor2d(ys,[xs.length,1])


model.fit(tfxs, tfys,{epochs: 500}).then(function() {
  model.predict(tfxs).print()
})

【讨论】:

  • 知道为什么会有这种差异吗?
  • @KillianC 我不知道。在过去的几年里,我一直在拉我的头发。几天试图弄清楚这个问题。还是没有头绪
猜你喜欢
  • 1970-01-01
  • 2015-07-23
  • 2017-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-29
  • 1970-01-01
相关资源
最近更新 更多