【问题标题】:Generic Tensorflow.js training example通用 Tensorflow.js 训练示例
【发布时间】:2018-04-20 17:00:23
【问题描述】:

我正在尝试训练神经网络进行一些图像处理。我使用 Synaptic.js 成功地做到了这一点,但是当我必须使用更多层时,它的学习速度非常慢。 Tensorflow.js 示例描述了一些具体案例,很难理解它们并适用于我的案例。有人可以帮我把这个 Synaptic.js 代码转换成 Tensorflow.js 吗?输入是 3x3(或更多)的 RGB 像素 [0..1] 内核,输出是单个 RGB 像素 [0..1]

const layers = [27, 9, 3];
const learningRate = 0.05;
const perceptron = new Synaptic.Architect.Perceptron(layers);

// Train
sampleData.forEach(([input, output]) => {
    perceptron.activate(input);
    perceptron.propagate(learningRate, output);
});

// Get result
const result = realData.map((input) => perceptron.activate(input));

【问题讨论】:

    标签: javascript tensorflow.js synaptic.js


    【解决方案1】:

    示例仓库中有一些非常通用的 TensorFlow.js 示例: https://github.com/tensorflow/tfjs-examples

    对于您的情况,您需要执行类似该 repo 中的 iris 示例的操作。

    // Define the model.
    const model = tf.sequential();
    // you will need to provide the size of the individual inputs below 
    model.add(tf.layers.dense({units: 27, inputShape: INPUT_SHAPE})); 
    model.add(tf.layers.dense({units: 9});
    model.add(tf.layers.dense({units: 3});
    const optimizer = tf.train.adam(0.05);
    modcel.compile({
      optimizer: optimizer,
      loss: 'categoricalCrossentropy',
      metrics: ['accuracy'],
    });
    // Train.
    const lossValues = [];
    const accuracyValues = [];
    // Call `model.fit` to train the model.
    const history = await model.fit(input, output, {epochs: 10});
    // Get result
    const result = realData.map((input) => model.predict(input));
    

    【讨论】:

    • 这看起来很简单,但我在选择张量的形状时遇到了问题。实际上,我希望我的输入为 [3, 3, 3](3x3 像素),输出为 [3](单像素),因此输入层应该有 27 个神经元,输出层应该有 3 个神经元。我想通过 100 像素对其进行训练,因此我设置了 inputShape: [100, 3, 3, 3] 并创建输入 [100, 3, 3, 3] 和输出 [100, 3] 张量。但它失败并出现错误,说它期望 5D 数组作为输入。
    • 最后我将输入展平为 2D 并且它起作用了。我不确定它的作用,await result.data() 返回一些疯狂的数字(例如,期望 [0..1] 但得到 -170),但感谢您的快速启动。
    • meanSquaredError替换损失