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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM