我正在使用Python3.7.7。和Tensorflow 2.1.0。
我有一段代码:
class_prototype = tf.math.reduce_mean(support_set_embeddings, axis=0)
print("Embeddings type: ", type(support_set_embeddings))
print("Class prototype type: ", type(class_prototype))
print("Support set embeddings shape: ", support_set_embeddings.shape)
print("Class prototype shape: ", class_prototype.shape)有了这个输出:
Embeddings type: <class 'tensorflow.python.framework.ops.EagerTensor'>
Class prototype type: <class 'tensorflow.python.framework.ops.EagerTensor'>
Support set embeddings shape: (5, 12, 12, 512)
Class prototype shape: (12, 12, 512)我得到了这个形状的(12, 12, 512),但是我想要一个形状为(1, 12, 12, 512)的张量。
为了得到它,我做到了
tf.expand_dims(class_prototype , axis=0)但是,如果我添加一个新的维度,会修改它的数据吗?
发布于 2020-09-10 10:43:21
添加维度不会修改数据。它只是更改数据的部门或维度。
例:
代码:
import tensorflow as tf
x1 = tf.constant(np.array(range(1,9)))
x2 = tf.reshape(x1, (2,2,2))
x2输出:
<tf.Tensor: shape=(2, 2, 2), dtype=int64, numpy=
array([[[1, 2],
[3, 4]],
[[5, 6],
[7, 8]]])>现在,如果您使用expand_dims,它只会向您的数据添加另一个维度。
代码:
x3 = tf.expand_dims(x2, axis = 0)
x3输出:
<tf.Tensor: shape=(1, 2, 2, 2), dtype=int64, numpy=
array([[[[1, 2],
[3, 4]],
[[5, 6],
[7, 8]]]])>您可以将expand_dims看作是将数组附加到空数组。
通过使用reshape函数而不是expand_dims函数,您可以获得相同的结果。
代码:
x4 = tf.reshape(x1, (1,2,2,2))
x4输出:
<tf.Tensor: shape=(1, 2, 2, 2), dtype=int64, numpy=
array([[[[1, 2],
[3, 4]],
[[5, 6],
[7, 8]]]])>发布于 2020-09-10 11:42:52
数据未被修改。
(N, 12, 12, 512)意味着您有N个具有(12, 12, 512)形状的元素。对于N=1,这意味着您有一个形状为(12, 12, 512)的元素,因此等效于(1, 12, 12, 512)。
进一步扩展维度只会继续这种逻辑:
(1,1,12,12,512)意味着您有一个元素和一个元素,该元素具有形状(12, 12, 512)。最后,我们仍然只有一个3D张量。
只有对于N>1,我们在张量中得到了不同数量的元素,这意味着我们已经修改了底层数据(例如,通过重复3D张量)。
https://stackoverflow.com/questions/63827440
复制相似问题