使用tensorflow.js根据流派预测电影的满意度

时间:2018-04-12 08:01:51

标签: javascript machine-learning tensorflow.js

使用tensorflow.js网站的默认基本示例我试图通过给它一个指定电影类型的数组来改变它,它可以预测我是否会喜欢这部电影:

  // Define a model for linear regression.
  const model = tf.sequential();
  model.add(tf.layers.dense({units: 1, inputShape: [1]}));

  // Prepare the model for training: Specify the loss and the optimizer.
  model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});
  // Generate some synthetic data for training.

  //[action, adventure, romance]
  const xs = tf.tensor1d([1,1,0]);
  //target data should be rating from 1 to 5
  const ys = tf.tensor1d([3]);

  // Train the model using the data.
  model.fit(xs, ys).then(() => {
    // Use the model to do inference on a data point the model hasn't seen before:
    // Open the browser devtools to see the output
    model.predict(tf.tensor2d([1,0,0])).print();
  });

然而,关于const ys = tf.tensor1d([3]);它会抛出错误告诉我Input Tensors should have the same number of samples as target Tensors. Found 3 input sample(s) and 1 target sample(s),但我想从数组[3]预测到1到5之间的数字而且我不知道知道如何使用此示例实现此目的

1 个答案:

答案 0 :(得分:0)

样本数量应与目标数量相匹配,否则模型无法学习。我更新了你的例子,添加了另一个样本和另一个目标,并更正了形状。

// Define a model for linear regression.
const model = tf.sequential();
model.add(tf.layers.dense({ units: 1, inputDim: 3 }));

// Prepare the model for training: Specify the loss and the optimizer.
model.compile({ loss: 'meanSquaredError', optimizer: 'sgd' });
// Generate some synthetic data for training.

//[action, adventure, romance]
const xs = tf.tensor2d([[1, 1, 0], [1, 0, 1]]);
//target data should be rating from 1 to 5
const ys = tf.tensor2d([[3], [2]]);

// Train the model using the data.
model.fit(xs, ys).then(() => {
  // Use the model to do inference on a data point the model hasn't seen before:
  // Open the browser devtools to see the output
  model.predict(tf.tensor2d([[1, 0, 0]])).print();
});

这会编译并产生以下结果:

Tensor
     [[1.6977279],]