Tensorflow学习笔记之张量增加维度与复制
例1
import tensorflow as tf
b=[1,2,3]
b=tf.convert_to_tensor(b,dtype=float)
print(b)
b1=tf.expand_dims(b,axis=0)
b1=tf.tile(b1,multiples=[2,1]) #multiples列表表示在对应维度上复制的倍数(1倍为不复制)
b2=tf.expand_dims(b,axis=1)
b2=tf.expand_dims(b,axis=1)
b2=tf.tile(b2,multiples=[1,3])
print(b1)
print(b2)
下面是打印结果,可以认真体会一下expand_dims和tile两个函数的作用。
E:\Anaconda\python.exe E:/PyCharmproject/Deeplearningdemo/tt.py
2020-02-14 18:43:39.001050: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2
tf.Tensor([1. 2. 3.], shape=(3,), dtype=float32)
<dtype: 'float32'>
tf.Tensor(
[[1. 2. 3.]
[1. 2. 3.]], shape=(2, 3), dtype=float32)
tf.Tensor(
[[1. 1. 1.]
[2. 2. 2.]
[3. 3. 3.]], shape=(3, 3), dtype=float32)
Process finished with exit code 0
例2
import tensorflow as tf
from tensorflow.keras import layers,optimizers,datasets
x=tf.range(4)
x=tf.reshape(x,[2,2])
print(x)
x=tf.tile(x,multiples=[1,2])
y=tf.tile(x,multiples=[2,1])
print("x")
print(x)
print("y")
print(y)
下面是打印结果,读者自行体会
E:\Anaconda\python.exe E:/PyCharmproject/Deeplearningdemo/tt.py
2020-02-14 19:02:43.087657: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2
tf.Tensor(
[[0 1]
[2 3]], shape=(2, 2), dtype=int32)
x
tf.Tensor(
[[0 1 0 1]
[2 3 2 3]], shape=(2, 4), dtype=int32)
y
tf.Tensor(
[[0 1 0 1]
[2 3 2 3]
[0 1 0 1]
[2 3 2 3]], shape=(4, 4), dtype=int32)
Process finished with exit code 0
个人觉得以矩阵的长宽或是行与列比较好理解,如果用其他方式,则较难理解,比如multiples=[x,y],x就是在行的层次上进行复制,y是在列的层次上进行复制,当然1表示不复制。
完结、、、