Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/tensorflow/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Tensorflow 2:如何在自定义损耗中使用Tensory_的形状?_Python_Tensorflow_Keras - Fatal编程技术网

Python Tensorflow 2:如何在自定义损耗中使用Tensory_的形状?

Python Tensorflow 2:如何在自定义损耗中使用Tensory_的形状?,python,tensorflow,keras,Python,Tensorflow,Keras,我将一个列表a传递给我的自定义函数,在将其转换为常数张量后,我想tf.tile它。我平铺的次数取决于y\u true的形状。我不知道怎样才能把y\u true的形状变成整数。代码如下: def getloss(a): a=tf.常数(a,tf.float32) def损失(y_真,y_pred): a=tf.重塑(a,[1,1,-1]) ytrue_shape=y_true。获取_shape()。作为_list()???? 倍数=tf.常数([ytrue_形状[0],ytrue_形状[1],1]

我将一个列表
a
传递给我的自定义函数,在将其转换为常数张量后,我想
tf.tile
它。我平铺的次数取决于
y\u true
的形状。我不知道怎样才能把
y\u true
的形状变成整数。代码如下:

def getloss(a):
a=tf.常数(a,tf.float32)
def损失(y_真,y_pred):
a=tf.重塑(a,[1,1,-1])
ytrue_shape=y_true。获取_shape()。作为_list()????
倍数=tf.常数([ytrue_形状[0],ytrue_形状[1],1],tf.int32)
a=tf.tile(a,倍数)
#...
回波损耗

我尝试了
y\u true.get\u shape().as\u list()
但它报告了一个错误,因为编译模型时第一个维度(批量大小)是
None
。有什么方法可以在这里使用
y\u true
的形状吗?

在构建模型期间尝试访问张量的形状时,如果不是所有形状都已知,最好使用。将在运行模型时对其进行评估,如文档中所述:

tf.shape和Tensor.shape在渴望模式下应该相同。在tf.function或compat.v1上下文中,直到执行时才可能知道所有维度。因此,在为图形模式定义自定义层和模型时,更喜欢动态tf.shape(x)而不是静态x.shape

ytrue\u shape=tf.shape(y\u true)
这将产生一个张量,因此使用TF ops获得您想要的:

multiples = tf.concat((tf.shape(y_true_shape)[:2],[1]),axis=0)

但是
tf.shape(y\u true)
给出了一个张量,这意味着我不能在第六行中使用ytrue\u shape[0]或ytrue\u shape[1]作为整数。如果我使用
tf.shape(y\u true)
它将报告一个类型错误:预期为int32,改为“Tensor”类型。是的,对我来说很明显,您需要tensorflow ops来获得您想要的。我加了一句简短的评论。下次我会更彻底。哇,我从没想过我能用这种方式实现它。你真的启发了我。多谢各位!