线性回归模型:为什么预测值总是错误?

我正在尝试构建一个简单的线性回归模型,我的数据集是从1到10的数字。我试图训练模型,以便对于任何给定的输入,例如3,输出应该等于输入的值(y = x)。

预测结果总是错误。请问有人能解释一下我哪里做错了么?

const tf = require("@tensorflow/tfjs");const xArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];const yArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];const createModel = () => {  const model = tf.sequential();  model.add(tf.layers.dense({ inputShape: [1], units: 1, useBias: true })); //input layer  model.add(tf.layers.dense({ units: 1, useBias: true })); //output layer  return model;};const convertToTensor = () => {  return tf.tidy(() => {    const inputTensor = tf.tensor2d(xArray, [xArray.length, 1]);    const outputTensor = tf.tensor2d(yArray, [yArray.length, 1]);    return {      inputs: inputTensor,      outputs: outputTensor,    };  });};async function trainModel(model, inputs, trueValues) {  model.compile({    optimizer: tf.train.adam(),    loss: tf.losses.meanSquaredError,    metrics: ["mse"]  });  return await model.fit(inputs, trueValues, {    batchSize: 2,    epochs: 5,    learningRate: 0.04  });}function testModel(model, testValue) {  return tf.tidy(() => model.predict(tf.tensor2d([testValue], [1, 1]));}const run = async testValue => {  const model = createModel();  const tensorData = convertToTensor();  await trainModel(model, tensorData.inputs, tensorData.outputs);  const prediction = testModel(model, testValue);  console.log(prediction.toString());};run(5);

回答:

你的代码有两个问题:

  • 你没有正确设置learningRate的值。你需要将它作为第一个参数传递给tf.train.adam()函数
  • 你只学习了5个周期,这在你的情况下是不够的。

自己尝试

我从你的代码中删除了不必要的部分。你可以更改epochslearning rate的值,看看它们如何影响5的预测结果。我将epoch的默认值改为50。预测结果最终会非常接近5

document.querySelector('button').addEventListener('click', async () => {  const learningRate = document.querySelector('#learning_rate').value;  const epochs = document.querySelector('#epochs').value;  const xArray = [0,1,2,3,4,5,6,7,8,9];  const yArray = [0,1,2,3,4,5,6,7,8,9];  const createModel = () => {    const model = tf.sequential();    model.add(tf.layers.dense({ inputShape: [1], units: 1, useBias: true }));    model.add(tf.layers.dense({ units: 1, useBias: true }));    return model;  };  const convertToTensor = () => {    return tf.tidy(() => {      const inputTensor = tf.tensor2d(xArray, [xArray.length, 1]);      const outputTensor = tf.tensor2d(yArray, [yArray.length, 1]);      return {        inputs: inputTensor,        outputs: outputTensor,      };    });  };  async function trainModel(model, inputs, trueValues) {    model.compile({      optimizer: tf.train.adam(learningRate),      loss: tf.losses.meanSquaredError,      metrics: ["mse"]    });    const batchSize = 2;    return await model.fit(inputs, trueValues, {      batchSize,      epochs,    });  }  function testModel(model, testValue) {    return tf.tidy(() => model.predict(tf.tensor2d([testValue], [1, 1])));  }  const run = async testValue => {    const model = createModel();    const tensorData = convertToTensor();    await trainModel(model, tensorData.inputs, tensorData.outputs);    const prediction = testModel(model, testValue);    console.log(`Predction for 5: ${prediction.toString()}`);  };  run(5);});
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]/dist/tf.min.js"></script>epochs: <input type="number" id="epochs" value="50" />learning rate: <input type="number" id="learning_rate" value="0.04" /><button id="train">Train</button>

Related Posts

在使用k近邻算法时,有没有办法获取被使用的“邻居”?

我想找到一种方法来确定在我的knn算法中实际使用了哪些…

Theano在Google Colab上无法启用GPU支持

我在尝试使用Theano库训练一个模型。由于我的电脑内…

准确性评分似乎有误

这里是代码: from sklearn.metrics…

Keras Functional API: “错误检查输入时:期望input_1具有4个维度,但得到形状为(X, Y)的数组”

我在尝试使用Keras的fit_generator来训…

如何使用sklearn.datasets.make_classification在指定范围内生成合成数据?

我想为分类问题创建合成数据。我使用了sklearn.d…

如何处理预测时不在训练集中的标签

已关闭。 此问题与编程或软件开发无关。目前不接受回答。…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注