我想使用Tensorflow.js(结合Node.js)创建一个将摄氏度转换为华氏度的模型。
然而,我不明白应该使用什么样的形状。
我尝试了不同的input_shape
,例如[1]
、[1,20]
,最后设置为[20]
。我还尝试了不同形状的摄氏度和华氏度数组,例如tensor(celsius)
、tensor([celsius])
。
这是代码
var model = tf.sequential()model.add(tf.layers.dense({inputShape:[20], units: 1}))async function trainModel(model, inputs, labels) { // Prepare the model for training. model.compile({ optimizer: tf.train.adam(), loss: tf.losses.meanSquaredError, metrics: ['mse'], }); const batchSize = 28; const epochs = 500; return await model.fit(inputs, labels, { epochs, shuffle: true, // callbacks: tfvis.show.fitCallbacks( // { name: 'Training Performance' }, // ['loss', 'mse'], // { height: 200, callbacks: ['onEpochEnd'] } // ) }); }c = tf.tensor([celsius]) // celsius = [1,2,3,4,...]console.log(c.shape) // ==> [1,20]f = tf.tensor([fahrenheit])console.log(f.shape) // ==> [1,20]trainModel(model, c, f)
此外,在Python教程中,input_shape
是[1]
。在Node.js中,似乎只有[20]
有效。
输入的形状是[1,20]
,这是正确的。
标签的形状也是[1,20]
,但会触发以下错误:
调试器显示:
Error when checking target: expected dense_Dense1 to have shape [,1], but got array with shape [1,20].
-EDIT
此外,当我尝试input_shape: [1,20]
时,它会显示:
expected dense_Dense1_input to have 3 dimension(s). but got array with shape 1,20
–
我希望模型通过关联摄氏度值和华氏度值来进行训练。
谢谢
回答:
错误很明显:
{inputShape:[20], units: 1}
模型包含一个单层。inputShape:[20]
意味着batchInputShape,即[null, 20]
将是第一层的形状。同样,units: 1
表示最后一层的形状将是[null, 1]
。
使用的特征具有形状[1, 20],因此与模型的batchInputShape相匹配。然而,标签的形状是[1, 20]
,这与要求不符。标签的形状必须是[1, 1]
,因此引发错误:
expected dense_Dense1 to have shape [,1], but got array with shape [1,20]
模型的units大小需要更改以反映标签的形状。
{inputShape:[20], units: 20}