TensorFlow.js: ValueError: Error when checking : expected dense_Dense1_input to have shape [null,38] but got array with shape [38,1]

TensorFlow.js: ValueError: Error when checking : expected dense_Dense1_input to have shape [null,38] but got array with shape [38,1]

我正在为聊天机器人训练模型,但遇到了这个错误。任何有关如何解决此问题的建议将不胜感激。谢谢

代码。

设置神经网络:

var model = await tf.sequential();
        model.add(tf.layers.dense({
            units: 8,
            inputShape: training[0].length
        }));
        // console.log(model);
        model.add(tf.layers.dense({
            units: 8
        }));
        model.add(tf.layers.dense({
            units: 8
        }));
        model.add(tf.layers.dense({
            units: output[0].length,
            activation: 'softmax'
        }))
        model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});

        await model.fit(tf.stack(training), tf.stack(output), {
            epochs: 1000,
            batchSize: 8
        }).then(printCall => {

            // IIFE function to prompt for user input.
            (function () {
                console.log("(Type 'quit' to stop)");
                while (true) {
                    let inp = "Hi";
                    if (inp.toLowerCase() == "quit")
                        break;
                    var results = model.predict(tf.tensor(bagOfWords(inp, uniq_words)));
                    console.log(result);
                }
            })();
        })

支持数据: 训练维度为 (23, 38) 的二维数组 输出维度为 (23, 6)

的二维数组

词袋:

function bagOfWords(s, words) {
    var bag = [];
    for (var i = 0; i < uniq_words.length; i++) {
        bag.push(0);
    }
    var sWords = tokenizer.tokenize(s);
    var s_words = [];
    sWords.map(each => {
        s_words.push(natural.LancasterStemmer.stem(each));
    });

    for (var se in s_words) {
        for (var w in uniq_words) {
            if (uniq_words[w] == s_words[se])
                bag[w] = 1;
        }
    }
    return bag;
}

上面的函数 bagOfWords returns 一个维度为 (38, 1) 的一维数组。

如果我可以添加更多内容以帮助更好地阐明问题,请告诉我。谢谢。

The above function bagOfWords returns a 1D array with dimensions (38, 1)

这不是一维数组。它是一个二维张量。

expected dense_Dense1_input to have shape [null,38] but got array with shape [38,1]

错误是由形状不匹配引起的。由于 tf.tensor(bagOfWords(inp, uniq_words)) 是形状为 [38, 1] 的张量,而模型期望形状为 [null, 38] 的张量,因此可以将张量重塑为后一种形状

tf.tensor(bagOfWords(inp, uniq_words)).reshape([-1, 38])