在 Tensorflow 的 C++ TensorShape API 中,Python 的 None 相当于什么?
In Tensorflow's C++ TensorShape API, what is the equivalent of Python's None?
假设我有一个用Tensorflow的Python API创建的tensor,如下,
x = tf.placeholder("float", shape=[None, inputLen])
我想在 C++ 中创建一个 tensorflow::Tensor 等价物,这样我就可以 运行 一个以 x 作为输入的经过训练的图。我应该如何处理输入形状的第一维,它在 C++ 中是 tensorflow::TensorShape 类型?
如果我这样做:
tensorflow::TensorShape inputShape;
inputShape.AddDim(0);
inputShape.AddDim(inputLen);
好像不行,因为num_elements变成了0,这不是我期望的inputLen的值。
更新: 现在有一个 tensorflow::PartialTensorShape
class 可以表示具有未知尺寸或未知等级的形状。值 -1
用于表示未知值(即 None
在 Python 中表示的内容)。它用于 C++ 形状推断代码,可以在形状类型的属性或 tf.TensorShape
原型中指定。
TL;DR: C++ 中没有等效项,因为 TensorFlow 的 C++ 部分仅在 运行 时检查形状,当它们被完全定义时;而 Python 部分在图形构建时检查形状,此时它们可能未完全定义。
没有 tf.Dimension(None)
(i.e., an unknown dimension) in the C++ tensorflow::TensorShape
class. This is because the (C++) tensorflow::TensorShape
class describes the shape of a (C++) tensorflow::Tensor
, which represents a concrete value for a tensor, and therefore must have a fully defined shape. The Python tf.Tensor
的等价物 class 表示一个 符号 张量——表示尚未成为 运行 的操作的输出]—因此它可以具有一维或多维未知的形状。
如果您使用的 C++ API to feed a placeholder, you should simply create a new tensorflow::Tensor
为您提供给占位符的每个不同值使用了完全定义的形状(在 Session::Run()
调用中)。但是请注意,C++ API 不会检查占位符的形状,因此您应该手动确保形状与占位符的预期形状匹配。
如果您正在使用 C++ API 构建图表,并且您想要 定义 一个在一维或多维中具有未知大小的占位符,您应该定义一个占位符节点,其 shape
属性设置为 tensorflow::TensorShape({})
。尽管这等同于标量,但由于历史原因,这被视为完全不受约束的形状。
假设我有一个用Tensorflow的Python API创建的tensor,如下,
x = tf.placeholder("float", shape=[None, inputLen])
我想在 C++ 中创建一个 tensorflow::Tensor 等价物,这样我就可以 运行 一个以 x 作为输入的经过训练的图。我应该如何处理输入形状的第一维,它在 C++ 中是 tensorflow::TensorShape 类型?
如果我这样做:
tensorflow::TensorShape inputShape;
inputShape.AddDim(0);
inputShape.AddDim(inputLen);
好像不行,因为num_elements变成了0,这不是我期望的inputLen的值。
更新: 现在有一个 tensorflow::PartialTensorShape
class 可以表示具有未知尺寸或未知等级的形状。值 -1
用于表示未知值(即 None
在 Python 中表示的内容)。它用于 C++ 形状推断代码,可以在形状类型的属性或 tf.TensorShape
原型中指定。
TL;DR: C++ 中没有等效项,因为 TensorFlow 的 C++ 部分仅在 运行 时检查形状,当它们被完全定义时;而 Python 部分在图形构建时检查形状,此时它们可能未完全定义。
没有 tf.Dimension(None)
(i.e., an unknown dimension) in the C++ tensorflow::TensorShape
class. This is because the (C++) tensorflow::TensorShape
class describes the shape of a (C++) tensorflow::Tensor
, which represents a concrete value for a tensor, and therefore must have a fully defined shape. The Python tf.Tensor
的等价物 class 表示一个 符号 张量——表示尚未成为 运行 的操作的输出]—因此它可以具有一维或多维未知的形状。
如果您使用的 C++ API to feed a placeholder, you should simply create a new tensorflow::Tensor
为您提供给占位符的每个不同值使用了完全定义的形状(在 Session::Run()
调用中)。但是请注意,C++ API 不会检查占位符的形状,因此您应该手动确保形状与占位符的预期形状匹配。
如果您正在使用 C++ API 构建图表,并且您想要 定义 一个在一维或多维中具有未知大小的占位符,您应该定义一个占位符节点,其 shape
属性设置为 tensorflow::TensorShape({})
。尽管这等同于标量,但由于历史原因,这被视为完全不受约束的形状。