在 TensorFlow 中展平包含矢量的二维张量的最佳方法?

Best way to flatten a 2D tensor containing a vector in TensorFlow?

将实际上是水平或垂直向量的二维张量展平为一维张量的最有效方法是什么?

在性能方面是否存在差异:

tf.reshape(w, [-1])

tf.squeeze(w)

?

都是tf.reshape(w, [-1]) and tf.squeeze(w) are "cheap" in that they operate only on the metadata (i.e. the shape) of the given tensor, and don't modify the data itself. Of the two tf.reshape() has slightly simpler logic internally,但是两者的性能应该是没有区别的

对于一个简单的 2D 张量,两者的功能应该相同,如@sv_jan5 所述。但是,请注意 tf.squeeze(w) 仅在多层张量的情况下挤压第一层,而 tf.reshape(w,[-1]) 将压平整个张量,而不管深度如何。

例如,让我们看一下

w = [[1,2,],[3,4]]    

现在这两个函数的输出将不再相同。 tf.squeeze(w)会输出

<tf.Tensor: shape=(2, 2), dtype=int32, numpy=
array([[1, 2],
       [3, 4]], dtype=int32)>

tf.reshape(w,[-1])会输出

<tf.Tensor: shape=(4,), dtype=int32, numpy=array([1, 2, 3, 4], dtype=int32)>