gpt4 book ai didi

tensorflow - 对tf.Tensor.set_shape()的澄清

转载 作者:行者123 更新时间:2023-12-03 09:17:21 26 4
gpt4 key购买 nike

我的图像为478 x 717 x 3 = 1028178像素,等级为1。我通过调用tf.shape和tf.rank进行了验证。

当我调用image.set_shape([478,717,3])时,它将引发以下错误。

"Shapes %s and %s must have the same rank" % (self, other)) 
ValueError: Shapes (?,) and (478, 717, 3) must have the same rank

我通过首先强制转换为1028178再次进行了测试,但该错误仍然存​​在。
ValueError: Shapes (1028178,) and (478, 717, 3) must have the same rank

好吧,这确实是有道理的,因为一个是等级1,另一个是等级3。但是,为什么要抛出错误,因为像素总数仍然匹配。

我当然可以使用tf.reshape,它可以工作,但是我认为这不是最佳选择。

如TensorFlow常见问题解答所述

What is the difference between x.set_shape() and x = tf.reshape(x)?

The tf.Tensor.set_shape() method updates the static shape of a Tensor object, and it is typically used to provide additional shape information when this cannot be inferred directly. It does not change the dynamic shape of the tensor.

The tf.reshape() operation creates a new tensor with a different dynamic shape.



创建一个新的张量涉及内存分配,当涉及更多的训练示例时,这可能会花费更高的成本。这是设计使然,还是我在这里错过了什么?

最佳答案

据我所知(并编写了该代码), Tensor.set_shape() 中没有错误。我认为误解源于该方法的名称困惑。

为了详细说明FAQ entry you quotedTensor.set_shape()是一个纯Python函数,可改善给定tf.Tensor对象的形状信息。 “改善”是指“使内容更加具体”。

因此,当您拥有形状为Tensort对象(?,)时,即未知长度的一维张量。您可以调用t.set_shape((1028178,)),然后在调用t(1028178,)将具有t.get_shape()形状。这不会影响基础存储,也不会影响后端的任何内容:它仅意味着使用t进行后续形状推断可以依赖于它是长度为1028178的 vector 的断言。

如果t具有(?,)形状,则对t.set_shape((478, 717, 3))的调用将失败,因为TensorFlow已经知道t是 vector ,因此它不能具有(478, 717, 3)形状。如果要根据t的内容制作具有该形状的新Tensor,可以使用 reshaped_t = tf.reshape(t, (478, 717, 3)) 。这将在Python中创建一个新的tf.Tensor对象;实际的implementation of tf.reshape() 使用张量缓冲区的浅拷贝来执行此操作,因此在实践中不昂贵。

一个类比是Tensor.set_shape()就像是一种运行时强制转换,如Java之类的面向对象语言。例如,如果您有一个指向Object的指针,但是知道它实际上是String,则可以执行强制转换(String) obj以便将obj传递给需要String参数的方法。但是,如果您有一个String s并尝试将其转换为java.util.Vector,则编译器会给您一个错误,因为这两种类型无关。

关于tensorflow - 对tf.Tensor.set_shape()的澄清,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35451948/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com