import tensorflow as tf import numpy as np ##############################维度变换tf.reshape()函数###################################### a = tf.range(30) b = tf.reshape(tensor=a, shape=[3, -1]) # c = a.numpy().reshape(6,-1) # 将tensor转化为numpy类型 c = tf.constant(np.arange(30).reshape(6, -1)) print('第一种方法维度改变后的b:', b) print('第二种方法维度改变后的c:', c) # numpy的方法 print() ##############################增加维度tf.expand_dims()函数###################################### a = tf.range(3) b = tf.expand_dims(a, axis=0) print('原张量a:', a, a.shape) print('增加维度后b:', b, b.shape) print() ##############################转换维度tf.transpose()函数###################################### a = tf.constant([[1, 2], [3, 4], [5, 6]]) # b = tf.transpose(a) b = tf.transpose(a, perm=[1, 0]) # perm为维度顺序 print('原张量a:', a, a.shape) print('转换维度后b:', b, b.shape) print() ##############################拼接和分割tf.concat(),tf.split()函数###################################### print('************************拼接***********************') a = tf.constant([[1, 2], [3, 4], [5, 6]]) b = tf.constant([[9, 9], [8, 8], [7, 7]]) c = tf.concat([a, b], axis=0) d = tf.concat([a, b], axis=1) print('原张量a:', a, a.shape) print('原张量b:', b, b.shape) print('a,b按0轴合并后c:', c, c.shape) print('a,b按1轴合并后d:', d, d.shape) print('************************分割***********************') print('axis = 0的分割') a = tf.reshape(tf.range(24), shape=(4, 6)) print('分割前张量a:', a) b = tf.split(a, 2, axis=0) # 中间参数2为分割成两个张量 print('两份分割b为:', b) c = tf.split(a, [1,1,2], axis=0) # 中间参数[1,1,2]为分割成三个张量 print('[1,1,2]份分割c为:', c) print('axis = 1的分割') print('分割前张量a:', a) c2 = tf.split(a, [1,3,2], axis=1) # 中间参数[1,3,2]为分割成三个张量,按axis=1分割 print() print('[1,3,2]份分割c2为:', c2) ##############################堆叠和分解tf.stack(),tf.unstack()函数###################################### print('************************堆叠***********************') a = tf.constant([1,2,3]) b = tf.constant([2,4,6]) print('原张量a:', a, a.shape) print('原张量b:', b, b.shape) c = tf.stack((a,b),axis = 0) print('axis = 0堆叠后c:',c) d = tf.stack((a,b),axis = 1) print('axis = 1堆叠后d:',d) print('************************分解***********************') a = tf.constant([[1,2,3],[4,5,6],[7,8,9],[5,5,5]]) print('原张量a:', a, a.shape) b = tf.unstack(a,axis = 0) print('axis = 0分解后b: ',b) c = tf.unstack(a,axis = 1) print('axis = 1分解后c: ',c)