tensorflow - 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
张量。任何帮助,将不胜感激!dtype
float32
解决方案
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>
推荐阅读
- apache-spark - Get instance of Azure data bricks Spark in Python code
- javascript - 如何按ID在表中插入值?
- r - 如何在闪亮的应用程序中添加时间线栏以显示动画 ggplot 多年来的进度?
- elasticsearch - 带有嵌套字段的 Elasticsearch 搜索查询
- c# - 如何解决 Unity 中的游戏内双击问题?
- typescript - 如何在 TypeScript 中获取当前日期和时间
- docker - 为 Docker 安装 libssl-dev
- sql-server - VB.Net 无法连接到本地数据库
- javascript - 鼠标/触摸坐标在错误的位置 HTML 画布
- java - 如何对具有对象 RequestParam 的 Controller 方法进行单元测试?