TensorflowJS:错误: model.execute(dict) 中提供的 dict['images'] 的形状必须为 [-1,224,224,3],但为 [400,600,1]

Ric*_*cha 6 typescript tensorflow angular tensorflow.js

我正在使用谷歌的mobilenet神经网络对图像进行分类。我正在使用 Angular 6 + TensorFlow.js 构建我的图像分类器应用程序。

我尝试按照tfjs-converter 库自述文件提供的步骤进行操作,并得出以下代码:

import * as tf from '@tensorflow/tfjs';
import { FrozenModel } from '@tensorflow/tfjs';

export class NeuralNetwork {
    private MODEL_PATH: string = 'http://localhost:4200/assets/model/tensorflowjs_model.pb';
    private WEIGHTS_PATH: string = 'http://localhost:4200/assets/model/weights_manifest.json';
    constructor(){}
    async loadModel() {
        const localModel: FrozenModel = (await tf.loadFrozenModel(this.MODEL_PATH, this.WEIGHTS_PATH));
        let image: any = document.getElementById('cat');

        let pixels =  tf.fromPixels(image, 1);
        let result = localModel.predict(pixels);
        
    }
    async predict(){
        let image: any = document.getElementById('cat');
        debugger;
        this.model.execute({input: tf.fromPixels(image)});
    }
    
}
Run Code Online (Sandbox Code Playgroud)

图像 HTML 元素:

<img id="cat" src="http://localhost:4200/assets/images/cat.jpg"/>
Run Code Online (Sandbox Code Playgroud)

当我尝试执行该localModel.predict(pixels)函数时,出现以下错误:

未捕获(承诺中):错误: model.execute(dict) 中提供的 dict['images'] 的形状必须为 [-1,224,224,3],但为 [400,600,1]

我是 Tensorflow 和 TensorFlow.js 技术的新手。有人知道我做错了什么吗?

edk*_*ked 0

该错误表明模型中定义的形状与传递给模型的输入的形状之间不匹配。要解决这个问题,你必须重塑你的输入。

然而,使用输入的tf.reshape不起作用,因为没有整数 k 例如k*224*224*3等于400*600*1。可以考虑使用tf.slice对输入图像进行切片,以便仅保留图像所需的形状。

const a = tf.randomNormal([400, 600, 3])
// a has shape [400, 600, 3]
// a cannot be reshaped into [224, 224, 3]
// a can be sliced into [224, 224, 3]
const b = a.slice([0, 0, 0], [224, 224, 3])
Run Code Online (Sandbox Code Playgroud)