目錄
TensorFlow2-維度變換
Outline(大綱)
-
shape, ndim
-
reshape
-
expand_dims/squeeze
-
transpose
圖片視圖
- [b, 28, 28] # 保存b張圖片,28行,28列(保存數據一般行優先),圖片的數據沒有被破壞
- [b, 28*28] # 保存b張圖片,不考慮圖片的行和列,只保存圖片的數據,不關注圖片數據的細節
- [b, 2, 14*28] # 保存b張圖片,把圖片分為上下兩個部分,兩個部分具體多少行是不清楚的
- [b, 28, 28, 1] # 保存b張圖片,28行,28列,1個通道
First Reshape(重塑視圖)
import tensorflow as tf
a = tf.random.normal([4, 28, 28, 3])
a.shape, a.ndim
(TensorShape([4, 28, 28, 3]), 4)
tf.reshape(a, [4, 784, 3]).shape # 給出一張圖片某個通道的數據,丟失行、寬的信息
TensorShape([4, 784, 3])
tf.reshape(a, [4, -1, 3]).shape # 4*(-1)*3 = 4*28*28*3
TensorShape([4, 784, 3])
tf.reshape(a, [4, 784*3]).shape # 給出一張圖片的所有數據,丟失行、寬和通道的信息
TensorShape([4, 2352])
tf.reshape(a, [4, -1]).shape
TensorShape([4, 2352])
Second Reshape(恢復視圖)
tf.reshape(tf.reshape(a, [4, -1]), [4, 28, 28, 3]).shape
TensorShape([4, 28, 28, 3])
tf.reshape(tf.reshape(a, [4, -1]), [4, 14, 56, 3]).shape
TensorShape([4, 14, 56, 3])
tf.reshape(tf.reshape(a, [4, -1]), [4, 1, 784, 3]).shape
TensorShape([4, 1, 784, 3])
first reshape:
- images: [4,28,28,3]
- reshape to: [4,784,3]
second reshape:
- [4,784,3] height:28,width:28 [4,28,28,3] √
- [4,784,3] height:14,width:56 [4,14,56,3] ×
- [4,784,3] width:28,height:28 [4,28,28,3] ×
Transpose(轉置)
a = tf.random.normal((4, 3, 2, 1))
a.shape
TensorShape([4, 3, 2, 1])
tf.transpose(a).shape
TensorShape([1, 2, 3, 4])
tf.transpose(a, perm=[0, 1, 3, 2]).shape # 按照索引替換維度
TensorShape([4, 3, 1, 2])
a = tf.random.normal([4, 28, 28, 3]) # b,h,w,c
a.shape
TensorShape([4, 28, 28, 3])
tf.transpose(a, [0, 2, 1, 3]).shape # b,2,h,c
TensorShape([4, 28, 28, 3])
tf.transpose(a, [0, 3, 2, 1]).shape # b,c,w,h
TensorShape([4, 3, 28, 28])
tf.transpose(a, [0, 3, 1, 2]).shape # b,c,h,w
TensorShape([4, 3, 28, 28])
Expand_dims(增加維度)
- a:[classes, students, classes]
add school dim(增加學校的維度):
- [1, 4, 35, 8] + [1, 4, 35, 8] = [2, 4, 35, 8]
a = tf.random.normal([4, 25, 8])
a.shape
TensorShape([4, 25, 8])
tf.expand_dims(a, axis=0).shape # 索引0前
TensorShape([1, 4, 25, 8])
tf.expand_dims(a, axis=3).shape # 索引3前
TensorShape([4, 25, 8, 1])
tf.expand_dims(a,axis=-1).shape # 索引-1后
TensorShape([4, 25, 8, 1])
tf.expand_dims(a,axis=-4).shape # 索引-4后,即左邊空白處
TensorShape([1, 4, 25, 8])
Squeeze(擠壓維度)
Only squeeze for shape = 1 dim(只刪除維度為1的維度)
- [4, 35, 8, 1] = [4, 35, 8]
- [1, 4, 35, 8] = [14, 35, 8]
- [1, 4, 35, 1] = [4, 35, 8]
tf.squeeze(tf.zeros([1,2,1,1,3])).shape
TensorShape([2, 3])
a = tf.zeros([1,2,1,3])
a.shape
TensorShape([1, 2, 1, 3])
tf.squeeze(a,axis=0).shape
TensorShape([2, 1, 3])
tf.squeeze(a,axis=2).shape
TensorShape([1, 2, 3])
tf.squeeze(a,axis=-2).shape
TensorShape([1, 2, 3])
tf.squeeze(a,axis=-4).shape
TensorShape([2, 1, 3])