使用 tensorflow.js 根据流派预测电影的受欢迎程度

Using tensorflow.js to predict movie desirability based on genre

使用 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 的数字的预测,但我没有知道如何使用此示例实现此目的

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

// 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],]