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)

在這裏插入圖片描述

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