1. 程式人生 > >tf.reshape()

tf.reshape()

tf.reshape

tf.reshape(
    tensor,
    shape,
    name=None
)

例如:

  • 將 1x9矩陣 ==> 3x3矩陣
import tensorflow as tf
import numpy as np

A = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])

t = tf.reshape(A, [3, 3])
with tf.Session() as sess:
    print(sess.run(t))

# 輸出
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
  • 將 3x2x3矩陣 ==> 1x18矩陣(也就是整個矩陣平鋪)
import tensorflow as tf
import numpy as np

A = np.array([[[1, 1, 1],
               [2, 2, 2]],
              [[3, 3, 3],
               [4, 4, 4]],
              [[5, 5, 5],
               [6, 6, 6]]])

t = tf.reshape(A, [-1])
with tf.Session() as sess:
    print
(sess.run(t)) # 輸出 [1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 6 6 6]
  • 將 3x2x3矩陣 ==> 2x9矩陣([2, -1]表示列項平鋪)
import tensorflow as tf
import numpy as np

A = np.array([[[1, 1, 1],
               [2, 2, 2]],
              [[3, 3, 3],
               [4, 4, 4]],
              [[5, 5, 5],
               [6, 6, 6]]
]) t = tf.reshape(A, [2, -1]) with tf.Session() as sess: print(sess.run(t)) # 輸出 [[1 1 1 2 2 2 3 3 3] [4 4 4 5 5 5 6 6 6]]
  • 將 3x2x3矩陣 ==> 2x3x3矩陣([2, -1, 3]表示行項平鋪)
import tensorflow as tf
import numpy as np

A = np.array([[[1, 1, 1],
               [2, 2, 2]],
              [[3, 3, 3],
               [4, 4, 4]],
              [[5, 5, 5],
               [6, 6, 6]]])

t = tf.reshape(A, [2, -1, 3])
with tf.Session() as sess:
    print(sess.run(t))

# 輸出
[[[1 1 1]
  [2 2 2]
  [3 3 3]]

 [[4 4 4]
  [5 5 5]
  [6 6 6]]]
  • 將1x1矩陣(只能為1x1的矩陣,否則形狀不符,Occur ValueError) ==> Scalar(標量),也就是一個數
import tensorflow as tf
import numpy as np

A = np.array([7])

t = tf.reshape(A, [])
with tf.Session() as sess:
    print(sess.run(t))

# 輸出
7

引數

  • tensor:輸入的張量
  • shape:表示重新設定的張量形狀,必須是int32或int64型別
  • name:表示這個op名字,在tensorboard中才會用

返回值

  • 有著重新設定過形狀的張量