使用tensorflow.js网站上的默认基础示例,我试图对其进行修改,以便通过提供一个指定电影类型的数组来预测我是否会喜欢这部电影:
// 定义一个线性回归模型。 const model = tf.sequential(); model.add(tf.layers.dense({units: 1, inputShape: [1]})); // 准备模型进行训练:指定损失函数和优化器。 model.compile({loss: 'meanSquaredError', optimizer: 'sgd'}); // 生成一些用于训练的合成数据。 //[action, adventure, romance] const xs = tf.tensor1d([1,1,0]); //目标数据应为1到5的评分 const ys = tf.tensor1d([3]); // 使用数据训练模型。 model.fit(xs, ys).then(() => { // 使用模型对模型之前未见过的数据点进行推理: // 打开浏览器开发者工具查看输出 model.predict(tf.tensor2d([1,0,0])).print(); });
然而,关于const ys = tf.tensor1d([3]);
,它抛出了一个错误,告诉我输入张量应具有与目标张量相同的样本数。发现3个输入样本和1个目标样本
,但我想从一个数组[3]预测到一个从1到5的数字,我不知道如何使用这个示例实现这一点
回答:
样本的数量应该与目标的数量匹配,否则模型无法学习。我更新了您的示例,添加了另一个样本和另一个目标,并修正了形状。
// 定义一个线性回归模型。const model = tf.sequential();model.add(tf.layers.dense({ units: 1, inputDim: 3 }));// 准备模型进行训练:指定损失函数和优化器。model.compile({ loss: 'meanSquaredError', optimizer: 'sgd' });// 生成一些用于训练的合成数据。//[action, adventure, romance]const xs = tf.tensor2d([[1, 1, 0], [1, 0, 1]]);//目标数据应为1到5的评分const ys = tf.tensor2d([[3], [2]]);// 使用数据训练模型。model.fit(xs, ys).then(() => { // 使用模型对模型之前未见过的数据点进行推理: // 打开浏览器开发者工具查看输出 model.predict(tf.tensor2d([[1, 0, 0]])).print();});
这可以编译并产生以下结果:
Tensor [[1.6977279],]