Tensor的维度变换

1.reshape重置形状

a = tf.random.normal([4,28,28,3])
print("a:",a.shape,a.ndim)

# 失去图片的行和列信息,可以理解为每个像素点(pixel)
b = tf.reshape(a,[4,28*28,3])
print("b:",b.shape,b.ndim)

# tensor维度转换时,可以指定其中一个值为-1
c = tf.reshape(a,[4,-1,3])
print("c:",c.shape,c.ndim)

# 失去图片的像素点信息,可以理解为data point(数据点)
d = tf.reshape(a,[4,-1])
print("d:",d.shape,d.ndim)

2.transpose转置

"""
可以理解为轴交换,会改变content的内容,即改变content的顺序
"""
a = tf.ones([4,28,28,3])
print("a:",a.shape,a.ndim)

# 若不传参数 则所有位置转置
b = tf.transpose(a)
print("b:",b.shape,b.ndim)

# 交换图片的行和列信息,虽然维度未变化,但是原来的content已改变
c = tf.transpose(a,[0,2,1,3])
print("c:",c.shape,c.ndim)

# 交换rgb通道和列的信息
d = tf.transpose(a,[0,1,3,2])
print("d:",d.shape,d.ndim)

# 小案例
print("image:",image.shape)
pl.figure(figsize=(5,5))
pl.imshow(image[0])

image1 = tf.transpose(image,[0,2,1])
pl.figure(figsize=(5,5))
pl.imshow(image1[0])

3.expand_dims 增加维度

"""
需要在哪个轴添加一个新轴,则指定axis=多少
"""


a = tf.random.normal([4,28,28,3])
print("a:",a.shape,a.ndim)

# 增加一个task维度
b = tf.expand_dims(a,axis = 0)
print("b:",b.shape,b.ndim)

# 末尾增加一个维度
c = tf.expand_dims(a,axis = -1)
print("c:",c.shape,c.ndim)

# 在任意位置增加一个维度
d = tf.expand_dims(a,axis = 4)
print("d:",d.shape,d.ndim)

4.squeeze 减少维度

a = tf.ones([1,1,4,28,28,1,3,1])
print("a:",a.shape,a.ndim)

# 不指定轴,则删除所有位数为1的轴
b = tf.squeeze(a)
print("b:",b.shape,b.ndim)

# 指定具体的轴,则删除对应的轴
c = tf.squeeze(a,axis = -3)
print("c:",c.shape,c.ndim)

5.pad填充

import tensorflow as tf

a = tf.reshape(tf.range(9), [3, 3])
print("a = \n", a)
print("-" * 100)
# 第一个【[ ]】是在第一维数据上的扩充,即上下
# 第二个【[ ]】是在第二维数据上的扩充,即左右
b = tf.pad(a, [[1, 0], [0, 1]])
print("b = \n", b)

6.tile数据复制

import tensorflow as tf

a = tf.reshape(tf.range(9), [3, 3])
print("a = \n", a)
print("-" * 100)

b = tf.tile(input=a, multiples=[1, 2])
print("b = \n", b)

7.broadcast_to广播,等价expand_dims+tile

import tensorflow as tf

a = tf.constant([[1, 2, 3], [4, 5, 6]], tf.int32)
print("a = \n", a)

b = tf.expand_dims(a, axis=0)
print("b = \n", b)


c = tf.tile(b, [2, 1, 1])
print("c = \n", c)

d = tf.broadcast_to(input=a, shape=[2, 2, 3])
print("d = \n", d)

8.stack增加维度

x = tf.constant([1, 4])
y = tf.constant([2, 5])
z = tf.constant([3, 6])
tf.stack([x, y, z])  # [[1, 4], [2, 5], [3, 6]] (Pack along first dim.)
tf.stack([x, y, z], axis=1)  # [[1, 2, 3], [4, 5, 6]]

9.unstack减少维度

x = tf.reshape(tf.range(12), (3,4))
p, q, r = tf.unstack(x)
print(p.shape)

10.concat数据拼接

  t1 = [[1, 2, 3], [4, 5, 6]]
  t2 = [[7, 8, 9], [10, 11, 12]]
  tf.concat([t1, t2], 0)  # [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
  tf.concat([t1, t2], 1)  # [[1, 2, 3, 7, 8, 9], [4, 5, 6, 10, 11, 12]]


  tf.shape(tf.concat([t3, t4], 0))  # [4, 3]
  tf.shape(tf.concat([t3, t4], 1))  # [2, 6]

11.split数据分离

import numpy as np
import tensorflow as tf
x = np.arange(0,50)
x = x.reshape((5, 10))
print(x.shape)  #(5, 10)
split1, split2, split3 = tf.split(x, num_or_size_splits=[2, 3, 5], axis = 1)

 

posted @ 2023-03-25 11:19  NAVYSUMMER  阅读(147)  评论(0)    收藏  举报
交流群 编程书籍