【问题标题】:max value of a tensor in graph mode tensorflow图模式张量流中张量的最大值
【发布时间】:2021-11-25 09:36:01
【问题描述】:

我在图形模式下有这个tf 代码(它有一个由@tf.function 包装的训练函数),我需要获取带有类型的张量x 的最大值

<class 'tensorflow.python.framework.ops.Tensor'> Tensor("x_3:0", shape=(100,), dtype=int64).

然后我需要使用x 的最大值作为tf.reshape()shape 参数中的参数之一。如果我打印tf.reduce_max(x) 的输出,我得到Tensor("Max:0", shape=(), dtype=int64),这是tf.reshape() 的无效参数。我试过tf.reduce_max(x).numpy(),它会抛出错误消息'Tensor' object has no attribute 'numpy'

那么如何在tf 2.6.0 中获取图形模式下张量的最大值?

更新这是我的代码,包含必要的细节(我希望),看看发生了什么:

MyModel.py

class MyModel(tf.keras.Model):
    def __init__(self, ...,hidden_size,name='model',**kwargs):
        super(MyModel, self).__init__(name=name, **kwargs)
        self.hidden_size = hidden_size

    def call(self, inputs, training=True):
        x1, input, target, length, y = inputs
        batch_size = input.shape[0]
        print('check point 2', length, tf.reduce_max(length))
        padded_outputs = tf.reshape(tf.boolean_mask(outputs_dec,mask), shape=(batch_size,tf.reduce_max(length),self.hidden_size))
        print('check point 3',padded_outputs.shape)

    @tf.function
    def train(self, inputs, optimizer):
        with tf.GradientTape() as tape:
            costs = self.call(inputs)
        gradients = tape.gradient(self.loss, self.params)
        optimizer.apply_gradients(zip(gradients, self.params))

train_mymodel.py

tr_data = tf.data.Dataset.from_tensor_slices((x1_tr,                                             
                                              x2.input, 
                                              x2.target, 
                                              x2.length,
                                              y_tr))\                           
                                             .batch(args.batch_size)
while int(checkpoint.step) < args.epochs:
            for i, (x1_batch, input_batch, target_batch, length_batch, y_batch) in enumerate(tr_data):
                print('check point 1', length_batch)
                costs, obj_fn = mymodel.train((x1_batch, input_batch, target_batch, length_batch, y_batch),optimizer)
check point 1 tf.Tensor([300 300 ... 300 300], shape=(100,),type=int64)
check point 2 Tensor("x_3:0", shape=(100,), dtype=int64) Tensor("Max_1:0", shape=(), dtype=int64)
check point 3 (100, None, 500)

padded_outputs 的形状应该是(100, 300, 500)

UPDATE2 跟踪图表时发生错误。如果我硬编码shape=(batch_size,300,self.hidden_size) 并使用tf.print(batch_size,tf.reduce_max(length),self.hidden_size),那么代码运行时不会出现错误消息,tf.print() 的输出是(100,300,500)。有什么办法可以避免这种行为?

【问题讨论】:

  • 您遇到的错误是什么?
  • 好吧,它稍后会崩溃,因为它期望 padded_outputs 的形状是 (100, 300, 500) 而不是 (100, None, 500)。 tf.reduce_max() 应该返回 300 而不是 None。
  • 是的,请将错误信息添加到您的问题中。
  • 此时没有错误。该错误稍后出现,因为填充输出的大小意外。它不应该是无大小。查看打印“检查点 1”中的输入向量。它是一个大小为 (100,) 的张量,所有值都是 300。然后 tf.reduce_max() 应该返回 300,而 tf.reshape() 应该返回大小为 (100,300,500) 的 padded_outputs。
  • 你能用 tf.print 替换所有打印语句并用输出更新你的问题吗?

标签: python tensorflow eager-execution


【解决方案1】:

它应该通过简单地传递减少的张量作为参数来工作:

import tensorflow as tf
tf.random.set_seed(1)

@tf.function
def reshape_on_max_value():
  tensor1 = tf.random.uniform((5, 2), maxval=5, dtype=tf.int32)
  tensor2 = tf.random.uniform((4, 1), maxval=5, dtype=tf.int32)
  x = tf.reduce_max(tensor1)
  tf.print(type(tensor1), type(tensor2))
  tf.print(tf.reshape(tensor2, [x, 1, 1]).shape)

reshape_on_max_value()
<class 'tensorflow.python.framework.ops.Tensor'> <class 'tensorflow.python.framework.ops.Tensor'>
TensorShape([4, 1, 1])

【讨论】:

  • 输入 type(tensor1) 或 type(tensor2) 会得到什么?
  • 更新了答案。非常有趣的是它不适合你。你能提供更多细节吗?
  • 对不起,我的错误。现在我得到和你一样的结果。我不明白为什么它在我的实际代码中不起作用。您知道为什么 x 在您的代码和我的问题中的类型不同吗? “x_3:0”部分。
  • 请发布您的实际代码... x_3 部分只是张量名称。
猜你喜欢
  • 2023-01-11
  • 2020-02-08
  • 1970-01-01
  • 2017-07-31
  • 1970-01-01
  • 1970-01-01
  • 2017-10-05
  • 2018-06-25
  • 2021-09-25
相关资源
最近更新 更多