【问题标题】:Best model type in TensorFlow.js for Color Prediction?TensorFlow.js 中用于颜色预测的最佳模型类型?
【发布时间】:2018-11-21 16:14:03
【问题描述】:

当我意识到出现问题时,我正在创建颜色预测器。我让模型成功运行,但预测总是在大约 2.5 到大约 5.5 的相同中值范围内。该模型应该输出对应于每种颜色的 0 到 8,并且我对每种颜色都有均匀数量的数据点进行训练。有没有更好的模型我可以使用它来预测某个值是 0 还是 7?我假设它不会,因为它认为它们是某种异常值。

这是我的模型

const model = tf.sequential();

const hidden = tf.layers.dense({
  units: 3,
  inputShape: [3] //Each input has 3 values r, g, and b
});
const output = tf.layers.dense({
  units: 1 //only one output (the color that corresponds to the rgb values
    });
model.add(hidden);
model.add(output);

model.compile({
  activation: 'sigmoid',
  loss: "meanSquaredError",
  optimizer: tf.train.sgd(0.005)
});

这是解决我问题的好模型吗?

【问题讨论】:

  • 欢迎来到 SO;我建议编辑您的问题,删除讲故事和多余的信息(它只会造成混乱,降低获得答案的机会),并准确地简洁地阐明什么正是 是您的问题(目前还不清楚)。请务必阅读How do I ask a good question?
  • 为什么不为每种颜色创建一个平衡的数据集?例如,每个类有 100 个数据点。我认为你正面临阶级不平衡的问题。
  • @sjishan 我花了时间为每种颜色获取 20 个数据点,但问题仍然存在,仍然从未离开那个中值范围,但是很好的建议,我会在所有数据点上达到 100,但是等待某些颜色随机生成 100 次非常罕见
  • @desertnaut 感谢您的提示!我试图删掉背景信息,只保留大部分能解决我问题的内容
  • 输出是否需要是 1 到 8 范围内的整数?因为如果是这种情况,您将使用回归来解决分类问题。此外,您可以为模型添加非线性。

标签: javascript tensorflow machine-learning tensorflow.js


【解决方案1】:

该模型缺乏非线性,因为没有激活函数。 给定一个 rgb 输入,模型应该预测 8 个可能值中最可能的颜色。这是一个分类问题。问题中定义的模型正在进行回归,即它试图预测给定输入的数值。

对于分类问题,最后一层应该预测概率。在这种情况下,softmax 激活函数主要用于最后一层。 损失函数应该是categoricalCrossentropybinaryCrossEntropy(如果只有两种颜色可以预测)。

考虑以下预测 3 类颜色的模型:红色、绿色和蓝色

const model = tf.sequential();
model.add(tf.layers.dense({units: 10, inputShape: [3], activation: 'sigmoid' }));
model.add(tf.layers.dense({units: 10, activation: 'sigmoid' }));
model.add(tf.layers.dense({units: 3, activation: 'softmax' }));

model.compile({ loss: 'categoricalCrossentropy', optimizer: 'adam' });

const xs = tf.tensor([
  [255, 23, 34],
  [255, 23, 43],
  [12, 255, 56],
  [13, 255, 56],
  [12, 23, 255],
  [12, 56, 255]
]);

// Labels
const label = ['red', 'red', 'green', 'green', 'blue', 'blue']
const setLabel = Array.from(new Set(label))
const ys = tf.oneHot(tf.tensor1d(label.map((a) => setLabel.findIndex(e => e === a)), 'int32'), 3)

// Train the model using the data.
  model.fit(xs, ys, {epochs: 100}).then((loss) => {
  const t = model.predict(xs);
  pred = t.argMax(1).dataSync(); // get the class of highest probability
  labelsPred = Array.from(pred).map(e => setLabel[e])
  console.log(labelsPred)
}).catch((e) => {
  console.log(e.message);
})
<html>
  <head>
    <!-- Load TensorFlow.js -->
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@0.13.3/dist/tf.min.js"> </script>
  </head>

  <body>
  </body>
</html>

【讨论】:

  • 哇!谢谢!我现在明白了,想法是得到每种颜色的概率,然后选择最高概率,我现在明白了。但我不得不问,是什么导致你用 10 个节点制作了 2 个隐藏层?
  • 对于层数和每层有多少个节点,你可以迭代,直到找到一个可以带来更好精度的节点。它没有通用公式。
猜你喜欢
  • 1970-01-01
  • 2021-05-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多