首页 > 解决方案 > Tensorflow.js:expandDims() + cast() 问题

问题描述

我需要float32为我的模型提供一个张量。我需要用它来expandDims(tensor, axis=0)改变它的形状。但是,该操作似乎将我的张量转换为.[240, 320, 3][1, 240, 320, 3]expandDims()int32

当我cast(tensor, "float32")在这个张量上执行时,似乎该cast操作将我的张量挤压回[240, 320, 3].

image_v = (tf.cast(image_raw, "float32") / 255.0) - 0.5;
image_v = tf.expandDims(image_raw, 0); 
console.log(image_v.shape) // shape: [1, 240, 320, 3]
console.log(image_v.dtype) // dtype: "int32"

image_v = tf.cast(image_raw, "float32") 
console.log(image_v.shape) // shape: [240, 320, 3]
console.log(image_v.dtype) // dtype: "float32"

我正在寻找一种方法来扩展float32张量上的 dims 并保留tensorflow.js张量。任何帮助,将不胜感激!dtypefloat32

标签: tensorflowtensorflow.js

解决方案


Tfjs 不能对张量使用 JS 操作,你必须使用tf.div()and tf.sub()

image_v = (tf.cast(image_raw, "float32") / 255.0) - 0.5;

image_v是现在NaN,因为({}/255)-0.5 === NaN

image_v = tf.expandDims(image_raw, 0);

现在你扩展原始图像,它没有被修改。

image_v = tf.cast(image_raw, "float32")

您重用了原来的image_raw,因为在 tf 操作中不要修改张量。他们总是创造一个新的。

而且我建议不要重用变量或在外面工作tf.tidy(),因为你很容易忘记.dispose(),从而造成内存泄漏。

const image_raw = tf.zeros([240, 320, 3]);

const modified = tf.tidy(() => {
  const image_v_casted = tf.cast(image_raw, "float32").div(255).sub(0.5);
  const image_v_expanded = tf.expandDims(image_v_casted, 0);

  return image_v_expanded;
});


console.log('shape', modified.shape);
console.log('dtype', modified.dtype);
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@1.0.0/dist/tf.min.js"></script>


推荐阅读