1. 程式人生 > 實用技巧 >tensorflow2.0——維度變換

tensorflow2.0——維度變換

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:\n',b) c = tf.unstack(a,axis = 1) print('axis = 1分解後c:\n',c)