检查模型输入时出错:传递给模型的张量数组不是模型预期的大小

时间:2019-02-22 14:08:53

标签: javascript tensorflow tensorflow.js

训练完成后,我只有一张图像可以进行预测。由于我尝试使用带有多个标签的多个图像进行训练。但是在编译该模型时会引发异常。

    let model;
    async function loadModel(name){
        model = tf.sequential();
        console.log('model::'+JSON.stringify(model));
    }

    $("#predict-button").click(async function(){
        let image= $('#selected-image').get(0);
        let image1 = $('#selected-image1').get(0);
        console.log('image:::',image);
        console.log('image1:::',image1);
        const imageArray = [];
        imageArray.push(image);
        imageArray.push(image1);
        console.log('imageArray:::',imageArray);
        var tensorarr = [];
        var resize_image = [];
        let tensor;
        for(var i=0; i< imageArray.length; i++)
        {

            tensor = preprocessImage(imageArray[i],$("#model-selector").val());
            const resize = tf.reshape(tensor, [1, 224, 224, 3],'resize');
            resize_image.push(resize);
            tensorarr.push(tensor);

        }
        console.log('tensorarr:::',tensorarr);
        console.log('tensorFromImage:::',resize_image);
        // Labels
        const label = ['cat'];
                                console.log('label',label);

        const setLabel = Array.from(new Set(label));
                    console.log('setLabel',setLabel);

        const ys = tf.oneHot(tf.tensor1d(label.map((a) => setLabel.findIndex(e => e === a)), 'int32'), 10);
        console.log('ys',ys);
        //let ys = tf.scalar(127.5);

        model.add(tf.layers.conv2d({
            inputShape: [224, 224 , 3],
            kernelSize: 5,
            filters: 8,
            strides: 1,
            activation: 'relu',
            kernelInitializer: 'VarianceScaling'
        }));

        model.add(tf.layers.maxPooling2d({poolSize: 2, strides: 2}));
        model.add(tf.layers.maxPooling2d({poolSize: 2, strides: 2}));
        model.add(tf.layers.flatten({}));
        model.add(tf.layers.dense({units: 64, activation: 'relu'}));
        model.add(tf.layers.dense({units: 10, activation: 'softmax'}));
        model.compile({
            loss: 'meanSquaredError',
            optimizer : 'sgd'
        })     
        // Train the model using the data.
        model.fit(resize_image, ys, {epochs: 100}).then((loss) => {
            let t = [];
            let tp;
            console.log('resize_image',resize_image);
            for(var j=0; j<resize_image.length; j++){
            console.log('resize_image[j]',resize_image[j]);
            tp = model.predict(resize_image[j]);
            console.log('Prediction:::'+tp);
            t.push(tp);
        }
            pred = t.argMax(1).dataSync(); // get the class of highest probability
        const labelsPred = Array.from(pred).map(e => setLabel[e])
        console.log(labelsPred);
        const saveResults = model.save('downloads://my-model-1');
        console.log(saveResults);
    }).catch((e) => {
        console.log(e.message);
    })


    });


        function preprocessImage(image, modelName)
        {
        console.log('image'+JSON.stringify(image));
        let tensor;
        tensor = tf.browser.fromPixels(image)
        .resizeNearestNeighbor([224,224])
        .toFloat();
        console.log('tensor pro:::', tensor);

        if(modelName=="mobilenet")
        {
        let offset=tf.scalar(127.5);
        console.log('offset:::',offset);

        return tensor.sub(offset)
        .div(offset)
        .expandDims();
    }
        else
        {
        throw new Error("UnKnown Model error");
    }
    }

在编译模型时会出现此问题

  

“检查模型输入时出错:您所使用的张量数组   传递给您的模型不是模型期望的大小。预期   查看1张量,但得到以下张量列表:   张量”

1 个答案:

答案 0 :(得分:0)

张量数组传递给fit函数,但由于只有一个输入,因此它期望一个张量。 tf.stack可用于从张量数组创建张量。

model.fit(tf.stack(resize_image), ys)