深度学习《常用Tensorflow2必备Tensor操作API》

Tensorflow必备Tensor操作API:

一、生成tensor:

import tensorflow as tf

tensor_a = tf.random.normal([2, 3], mean = 1 , stddev = 1)              # 正太分布
tensor_b = tf.random.truncated_normal([2, 3], mean = 0, stddev = 1)     # 截段的正太分布
tensor_c = tf.random.uniform([2, 3], minval = 0, maxval = 1)            # 均匀分布

二、转换成tensor:

import numpy as np
import tensorflow as tf

a0 = np.random.rand(5, 2)
a1 = tf.convert_to_tensor(a0, dtype = "float32")
a2 = tf.cast(a0, dtype = "float32")

三、切片操作:

import tensorflow as tf

tensor_a = tf.random.normal([4, 64, 64, 3], mean = 1 , stddev = 1)
# (2, 64, 64, 3)
out1 = tensor_a[0:2, :, :, :] 
# (2, 32, 32, 3)
out2 = tensor_a[0:2, 0:32, 0:32, :] 
# (2, 64, 64, 3)
out3 = tensor_a[0:2, ...] 

# (3, 64, 64, 3)
out4 = tf.gather(tensor_a, [0, 2, 3], axis = 0 )
# (2, 64, 64, 3)
out6 = tf.boolean_mask(tensor_a, [True, False, False, True], axis = 0)

四、维度变换:

import tensorflow as tf

tensor_a = tf.random.normal([4, 64, 64, 3], mean = 1 , stddev = 1)
# (4, 4096, 3)
out1 = tf.reshape(tensor_a , [4, -1, 3])
# (4, 64, 192)
out2 = tf.reshape(tensor_a , [4, 64, -1])
# (3, 4, 64, 64)
out3 = tf.transpose(tensor_a, [3, 0, 1, 2])

五、维度增与减

import tensorflow as tf

tensor_a = tf.random.normal([64, 64, 3], mean = 1 , stddev = 1)
# (1, 64, 64, 3)
out1 = tf.expand_dims(tensor_a , axis = 0)

tensor_b = tf.random.normal([1, 64, 64, 3], mean = 1 , stddev = 1)
# (64, 64, 3)
out2 = tf.squeeze(tensor_b , axis = 0)

六、合并与分割:

import tensorflow as tf

tensor_a = tf.random.normal([2, 32, 64, 3], mean = 1 , stddev = 1)
tensor_b = tf.random.normal([2, 32, 64, 3], mean = 1 , stddev = 1)
# (4, 32, 64, 3)
out1 = tf.concat([tensor_a, tensor_b], axis = 0)
# (2, 64, 64, 3)
out2 = tf.concat([tensor_a, tensor_b], axis = 1)

tensor_c = tf.random.normal([64, 64, 3], mean = 1 , stddev = 1)
tensor_d = tf.random.normal([64, 64, 3], mean = 1 , stddev = 1)
# (2, 64, 64, 3)
out3 = tf.stack([tensor_c , tensor_d] , axis = 0 )

tensor_e = tf.random.normal([4, 64, 64, 3], mean = 1 , stddev = 1)
out4 = tf.split( tensor_e, axis = 2 , num_or_size_splits = [16, 16, 16, 16])
print(out4[0].shape, out4[1].shape, out4[2].shape, out4[3].shape)
# out:(4, 64, 16, 3) (4, 64, 16, 3) (4, 64, 16, 3) (4, 64, 16, 3)

out5 = tf.split( tensor_e, axis = 2 , num_or_size_splits = 2)
print(out5[0].shape, out5[1].shape)
# out:(4, 64, 32, 3) (4, 64, 32, 3)

七、填充.复制:

import tensorflow as tf

tensor_a = tf.random.truncated_normal([4,28,28,3] , dtype = "float32")
# (4, 32, 32, 3)
out1 = tf.pad(tensor_a , [[0,0],[2,2],[2,2],[0,0]])
# (8, 28, 28, 3)
out2 = b = tf.tile(tensor_a , [2, 1, 1, 1])

八、where():

import tensorflow as tf

a = [[ 0.08529424,  -0.13806899,  -0.67322326],
     [ 1.3721075,   -1.2072325,   -0.56882554],
     [ 0.02258053,  -0.21793075,  -0.42977524]]
tensor_a = tf.cast(a, dtype = "float32")
out1 = tf.where( tensor_a > 0, 1, -1)
print(out1)

# out1:
# [[ 1 -1 -1]
#  [ 1 -1 -1]
#  [ 1 -1 -1]]

你可能感兴趣的:(深度学习基础知识)