我按照tf.random.normal
方法(或K.random_normal
通过keras
API)使用高斯噪声。
它是在自定义中使用的tensorflow
Layer
,而该自定义又由一个自定义使用Model
。
出于某种原因,当直接调用图层/模型或通过使用自定义训练循环时,一切都按预期工作tf.GradientTape()
,但是当尝试使用该fit
方法时,它将引发令人费解的错误。
似乎与推断批次尺寸有关,这None
在调用fit
方法时表示。
我怀疑这与编译张量和符号张量与渴望张量有关,但是我不知道如何实际解决这个问题?
我试图将问题简化为一个重现该问题的最小示例:
import numpy as np
import tensorflow.keras.backend as K
from tensorflow.keras import models
import tensorflow as tf
class Demo(models.Model):
def __init__(self):
super().__init__()
def call(self, inputs, training=None, mask=None):
# batch gives "2" when called directly or via GradientTape()
# gives "None" when called via fit
batch = K.int_shape(inputs)[0]
dim = K.int_shape(inputs)[1]
noise = tf.random.normal(shape=(batch, dim), mean=0.0, stddev=1.0)
# manually specifying the batch dimension does work, e.g.
# noise = tf.random.normal(shape=(2, dim), mean=0.0, stddev=1.0)
return inputs * noise
test_data = np.array([[1., 2., 3., 4.], [5., 6., 7., 8.]])
tester = Demo()
tester.compile(optimizer='adam')
# manual calling works
print(test_data - tester(test_data))
# but calling fit does not
tester.fit(x=test_data)
# raises: TypeError: Failed to convert object of type <class 'tuple'> to Tensor.
# Contents: (None, 4). Consider casting elements to a supported type.
对问题可能有什么建议?
在该call
方法中,不是使用keras.backend
getbatch
和dim
,而是直接使用tensorflow。
batch = tf.shape(inputs)[0]
dim = tf.shape(inputs)[1]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句