我有一个具有以下尺寸的 3D 张量:宽度 x 高度 x 深度。我需要将可变大小的体积调整为特定的形状,比如 256 x 256 x 256。不幸的是,在 TensorFlow.js 中,它们具有用于调整大小的方法集,例如 tf.image.resizeBilinear 和 tf.image.resizeNearestNeighbor 仅适用于 2D 图像。是否有解决方法让这些方法在 3D 空间中工作?
最佳答案
要调整张量的大小,可以使用 tf.reshape如果输入大小与输出大小匹配
const x = tf.tensor(Array.from({length :64}, (_, i) => i), [4, 4]);
x.reshape([1, 16])
reshape 的一个应用是从初始数据集创建批处理
如果输入和输出大小不匹配,可以使用 tf.slice
const x = tf.tensor(Array.from({length :64}, (_, i) => i), [4, 4, 4]);
x.slice([1, 1, 1], [2, 2, 2]) // we are taking the 8 values at the center of the cube
后者可用于裁剪形状为 [height, width, channels]
// t is a tensor
// edge is the size of an edge of the cube
const cropImage = (t, edge) => {
shape = t.shape;
startCoord = shape.map(i => (i - edge) / 2)
return t.slice(startCoord, [edge, edge, edge])
// to keep the number of channels
return t.slice([...startCoord.slice(0, shape.length - 1), 0], [edge, edge, channels])
}
关于TensorFlow.js 调整 3D 张量大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53368649/