【问题标题】:Add a new dimension to a Tensor, will modify its data?向张量添加新维度,会修改其数据吗?
【发布时间】:2020-09-10 10:11:19
【问题描述】:

我使用的是 Python 3.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)

但是,如果我添加一个新维度,会修改它的数据吗?

【问题讨论】:

    标签: python numpy tensorflow


    【解决方案1】:

    添加维度不会修改您的数据。它只是改变了数据的部门或维度。

    例如:

    代码:

    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]]]])>
    

    【讨论】:

    • 谢谢。数组维度是我不明白的一件事。好吧,直到3D数组我才理解,如果数组有更多维度,我不明白。非常感谢您的回答。
    【解决方案2】:

    数据没有被修改。

    (N, 12, 12, 512) 表示您有 N 个形状为 (12, 12, 512) 的元素。 对于N=1,这意味着您有1 个形状为(12, 12, 512) 的元素,因此相当于(1, 12, 12, 512)

    进一步扩大维度只是继续这个逻辑:

    (1,1,12,12,512) 表示您有 1 个元素和 1 个形状为 (12, 12, 512) 的元素。所以最后我们仍然只有 1 个3D 张量。

    仅对于 N&gt;1,我们最终会在张量中得到不同数量的元素,这意味着我们已经修改了基础数据(例如,通过重复 3D 张量)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-27
      • 1970-01-01
      • 2018-08-03
      • 2019-04-16
      相关资源
      最近更新 更多