文章目录
维度变换
简介
- shape, ndim
- reshape
- expand_dims/squeeze
- transpose
- broadcast_to
View
- 图片信息 [b,h,w]
- [b, 28, 28]
- →[b, 28*28]
- →[b, 2, 14*28]
- →[b, 28, 28, 1] [b,h,w,c]
import tensorflow as tf
import numpy as np
Reshape
a=tf.random.normal([4,28,28,3])
a.shape, a.ndim
(TensorShape([4, 28, 28, 3]), 4)
# 重置维度
tf.reshape(a, [4,28*28,3]).shape
TensorShape([4, 784, 3])
tf.reshape(a, [4,784,3]).shape
TensorShape([4, 784, 3])
# -1 自动推断
tf.reshape(a,[4,-1,3]).shape
TensorShape([4, 784, 3])
tf.reshape(a,[4,784*3]).shape
TensorShape([4, 2352])
tf.reshape(a,[4,-1]).shape
TensorShape([4, 2352])
Reshape is flexib 重塑是灵活的
a=tf.random.normal([4,28,28,3])
a.shape
TensorShape([4, 28, 28, 3])
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])
Reshape could lead to potential bugs!
- 重塑可能会导致潜在的错误
- images: [4, 28, 28, 3]
- [b, h, w, 3]
- reshape to: [4, 784, 3]
- [b, pixel, 3]
- [4, 784, 3] ℎ𝑒𝑖𝑔ℎ𝑡: 28, 𝑤𝑖𝑑𝑡ℎ: 28 [4, 28, 28, 3]
- [4, 784, 3] ℎ𝑒𝑖𝑔ℎ𝑡: 14, 𝑤𝑖𝑑𝑡ℎ: 56 [4, 14, 56, 3]
- [4, 784, 3] 𝑤𝑖𝑑𝑡ℎ: 28, ℎ𝑒𝑖𝑔ℎ𝑡: 28 [4, 28, 28, 3]
tf.transpo 矩阵转置
- [h,w] -> [w,h]
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])
[b,h,w,c]→[b, 3, h, w]
a=tf.random.normal([4,28,28,3])
a.shape
TensorShape([4, 28, 28, 3])
tf.transpose(a,[0,2,1,3]).shape
TensorShape([4, 28, 28, 3])
tf.transpose(a,[0,3,2,1]).shape
TensorShape([4, 3, 28, 28])
tf.transpose(a,[0,3,1,2]).shape
TensorShape([4, 3, 28, 28])
Squeeze VS Expand_dims
挤压与扩张
Expand dim
- a: [classes, students, classes]
- [4, 35, 8]
- add school dim
- [1, 4, 35, 8] + [1, 4, 35, 8]
- [2, 4, 35, 8]
a=tf.random.normal([4,35,8])
a.shape
TensorShape([4, 35, 8])
# 在第0维添加一个轴
tf.expand_dims(a,axis=0).shape
TensorShape([1, 4, 35, 8])
# 在第2维添加一个轴
tf.expand_dims(a,axis=2).shape
TensorShape([4, 35, 1, 8])
# 在第3维添加一个轴
tf.expand_dims(a,axis=3).shape
TensorShape([4, 35, 8, 1])
tf.expand_dims(a,axis=-1).shape
TensorShape([4, 35, 8, 1])
tf.expand_dims(a,axis=-4).shape
TensorShape([1, 4, 35, 8])
Squeeze dim
- Only squeeze for shape=1 dim (仅挤压shape=1 dim)
- [4, 35, 8,
1
] - [
1
, 4, 35, 8] - [
1
, 4, 35,1
]
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])
# 仅挤压shape=1 dim
# tf.squeeze(a, axis=1).shape