【发布时间】: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