Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error when checking model input: the Array of Tensors that you are passing to your model is not the size the model expected

I have one image to get prediction after training done. Since I tried with multiple images with multiple labels to train. But throws an exception while compiling that model.

    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");
    }
    }

While compiling model this issue coming

"Error when checking model input: the Array of Tensors that you are passing to your model is not the size the model expected. Expected to see 1 Tensor(s), but instead got the following list of Tensor(s): Tensor"

like image 511
ANKIT SHARMA Avatar asked Dec 04 '25 03:12

ANKIT SHARMA


1 Answers

An array of tensors is passed to the fit function whereas it expects a single tensor since there is only one input. tf.stack can be used to create a tensor from the array of tensors.

model.fit(tf.stack(resize_image), ys)
like image 166
edkeveked Avatar answered Dec 05 '25 18:12

edkeveked