如何解决在修饰的tf函数中,出现错误:'Tensor'对象没有属性'numpy'
我已经四处张望,但是找不到任何以前的答案有帮助的人。
我有一个带有@ tf.function的张量流模型来进行训练(tf版本2.3.0)。在train_step调用中,我需要将数据从张量传递到对它执行cwt转换的numpy函数。没有(afaik)没有tensorflow cwt,因此需要将其传递给numpy函数。我遇到的问题是,在@ tf.function中,对张量进行了绘制,因此无法直接调用.numpy()将张量转换为numpy数组。小代码段在下面显示了代码。
我的问题是如何将生成器调用中生成的输出数据转换为可以传递给此numpy函数的内容。希望有办法做到这一点!
谢谢。
@tf.function
def train_step(self,true_data):
noise = tf.random.uniform(shape=[1,100,1],minval=0,maxval=1,dtype=tf.float32)
with tf.GradientTape() as gen_tape,tf.GradientTape() as disc_tape:
generated_data = self.generator(noise)
nump_data = generated_data.numpy()
<this line produces: AttributeError: 'Tensor' object has no attribute 'numpy'>
解决方法
如前所述,根据tf.function
规则,您不能在.numpy()
内部使用tf.fucntion
函数。
使用eval()
启用图形模式后,仍然可以采取一些变通方法将 Tensor转换为NumPy数组。
下面是经过修改的代码,应该可以帮助您解决问题。
@tf.function
def train_step(self,true_data):
noise = tf.random.uniform(shape=[1,100,1],minval=0,maxval=1,dtype=tf.float32)
with tf.GradientTape() as gen_tape,tf.GradientTape() as disc_tape:
generated_data = self.generator(noise)
nump_data = generated_data.eval(session=tf.compat.v1.Session())
如果代码不需要tf.function
,则可以直接使用eager execution enabled
而不是graph mode
运行Tensorflow 2.3 version
来运行它,这默认情况下会急于执行。这样可以避免这些问题。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。