TensorFlow2.0 维度变换

1.维度变换

import tensorflow as tf
import numpy as np
print(tf.__version__)
# 维度变换
a = tf.random.normal([4, 28, 28, 3])
print(a.shape)

# 维度变换 [4, 28, 28, 3] --> [4, 28 * 28, 3] 
print(tf.reshape(a, [4, 784, 3]).shape)
# 维度变换 [4, 28, 28, 3] --> [4, 784 * 3]
print(tf.reshape(a, [4, -1]).shape)

在这里插入图片描述

2.矩阵的转置

# 矩阵的转置
a = tf.random.normal((4, 3, 2, 1))
print(a.shape)
# 维度真实颠倒 [4, 3, 2, 1] ==> [1, 2, 3, 4]
print(tf.transpose(a).shape)

在这里插入图片描述

a = tf.random.normal((4, 28, 28, 3))
print(a.shape)
# 根据需要 转置指定维度
# 维度真实颠倒 [b, h, w, c] --> [b, c, h, w]
print(tf.transpose(a, [0, 3, 1, 2]).shape)

在这里插入图片描述

3.增加 展开维度

# 增加 展开维度
a = tf.random.normal([4, 35, 8])
print(a.shape)
# 前面增加一个维度
print(tf.expand_dims(a, axis=0).shape)

在这里插入图片描述

# 后面增加一个维度
print(a.shape)
print(tf.expand_dims(a, axis=3).shape)

在这里插入图片描述

4.压缩维度

# 压缩维度
a = tf.zeros([1, 2, 1, 1 ,3])
print(a.shape)
# 压缩所有1维维度
print(tf.squeeze(a).shape)

在这里插入图片描述

# 压缩指定维度
print(a.shape)
print(tf.squeeze(a, axis=2).shape)

在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章