当张量中存在未知元素时,正确的方法是什么? [英] What is the right way to manipulate the shape of a tensor when there are unknown elements in it?
本文介绍了当张量中存在未知元素时,正确的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
(None, None, None, 32)
的张量,我想将其重塑为(None, None, 32)
,其中中间尺寸是原始尺寸的两个中间尺寸的乘积.正确的方法是什么?解决方案
import keras.backend as K
def flatten_pixels(x):
shape = K.shape(x)
newShape = K.concatenate([
shape[0:1],
shape[1:2] * shape[2:3],
shape[3:4]
])
return K.reshape(x, newShape)
在Lambda
层中使用它:
from keras.layers import Lambda
model.add(Lambda(flatten_pixels))
一些知识:
-
K.shape
返回张量的当前"形状,其中包含数据-这是一个Tensor
,其中包含所有维度的int
值.它仅在运行模型时正确存在,并且不能在模型定义中使用,只能在运行时计算中使用. -
K.int_shape
将张量的定义"形状返回为tuple
.这意味着变量尺寸将包含None
值.
Let's say that I have a tensor of shape (None, None, None, 32)
and I want to reshape this to (None, None, 32)
where the middle dimension is the product of two middle dimensions of the original one. What is the right way to do so?
解决方案
import keras.backend as K
def flatten_pixels(x):
shape = K.shape(x)
newShape = K.concatenate([
shape[0:1],
shape[1:2] * shape[2:3],
shape[3:4]
])
return K.reshape(x, newShape)
Use it in a Lambda
layer:
from keras.layers import Lambda
model.add(Lambda(flatten_pixels))
A little knowledge:
K.shape
returns the "current" shape of the tensor, containing data - It's aTensor
containingint
values for all dimensions. It only exists properly when running the model and can't be used in model definition, only in runtime calculations.K.int_shape
returns the "definition" shape of the tensor as atuple
. This means the variable dimensions will come containingNone
values.
这篇关于当张量中存在未知元素时,正确的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文