How can I change the shape of a variable in TensorFlow?

前端 未结 6 554
醉梦人生
醉梦人生 2020-12-03 07:21

TensorFlow tutorial says that at creation time we need to specify the shape of tensors. That shape automatically becomes the shape of the tensor. It also says that TensorF

6条回答
  •  清歌不尽
    2020-12-03 07:39

    Documentation shows methods for reshaping. They are:

    • reshape
    • squeeze (removes dimensions of size 1 from the shape of a tensor)
    • expand_dims (adds dimensions of size 1)

    as well as bunch of methods to get shape, size, rank of your tensor. Probably the most used is reshape and here is a code example with a couple of edge cases (-1):

    import tensorflow as tf
    
    v1 = tf.Variable([
        [1, 2, 3, 4],
        [5, 6, 7, 8],
        [9, 10, 11, 12]
    ])
    v2 = tf.reshape(v1, [2, 6])
    v3 = tf.reshape(v1, [2, 2, -1])
    v4 = tf.reshape(v1, [-1])
    # v5 = tf.reshape(v1, [2, 4, -1]) will fail, because you can not find such an integer for -1
    v6 = tf.reshape(v1, [1, 4, 1, 3, 1])
    v6_shape = tf.shape(v6)
    v6_squeezed = tf.squeeze(v6)
    v6_squeezed_shape = tf.shape(v6_squeezed)
    
    init = tf.initialize_all_variables()
    
    sess = tf.Session()
    sess.run(init)
    a, b, c, d, e, f, g = sess.run([v2, v3, v4, v6, v6_shape, v6_squeezed, v6_squeezed_shape])
    # print all variables to see what is there
    print e # shape of v6
    print g # shape of v6_squeezed
    

提交回复
热议问题