tf.stack的用法
1 tf.stack
tf.stack用于拼接两个tf 张量,拼接可以在不同的维度上进行,拼接后的新张量维度加1
例子1:拼接1维数组:
x1=tf.constant([1,2,3])# shape:(3)
x2=tf.constant([3,4,5])# shape: (3)
#在第0个轴上拼接
y1=tf.stack([x1,x2],0) #shape=(2*3)
print(sess.run(y1))
-------------------y1
[[1 2 3]
[3 4 5]]
-------------------
#在第1个轴上拼接
#此处的axis最大值为1
y2=tf.stack([x1,x2],axis=1) #shape=(3*2)
print(sess.run(y2)
-------------------y2
[[1 3]
[2 4]
[3 5]]
-------------------
例子2:拼接高维数组
>>>x2=tf.constant([[[1,1],[2,2]],[[3,2],[4,4]]])#shape:(2,2,2)
[[[1 1]
[2 2]]
[[3 2]
[4 4]]]
>>>x3=tf.constant([[[5,5],[6,6]],[[7,7],[8,8]]])#shape:(2,2,2)
[[[5 5]
[6 6]]
[[7 7]
[8 8]]]
#注意下面代码stack函数的参数axis值的变化从0到3
>>> z1=tf.stack([x2,x3],axis=0) #shape:(2*2*2*2)
>>> print(sess.run(z1))
[[[[1 1]
[2 2]]
[[3 2]
[4 4]]]
[[[5 5]
[6 6]]
[[7 7]
[8 8]]]]
>>> z2=tf.stack([x2,x3],1)
>>> print(sess.run(z2))
[[[[1 1]
[2 2]]
[[5 5]
[6 6]]]
[[[3 2]
[4 4]]
[[7 7]
[8 8]]]]
>>> z3=tf.stack([x2,x3],2)
>>> print(sess.run(z3))
[[[[1 1]
[5 5]]
[[2 2]
[6 6]]]
[[[3 2]
[7 7]]
[[4 4]
[8 8]]]]
>>> z4=tf.stack([x2,x3],axis=3) # axis的最大值为3 比x2的维度大1
>>> print(sess.run(z4))
[[[[1 5]
[1 5]]
[[2 6]
[2 6]]]
[[[3 7]
[2 7]]
[[4 8]
[4 8]]]]
2 tf数组取值
>>>x2=tf.constant([[[1,1],[2,2]],[[3,2],[4,4]]])#shape:(2,2,2)
[[[1 1]
[2 2]]
[[3 2]
[4 4]]]
>>> y=x2[:,:,0] #取最后一维的索引0的值
>>> y.shape
TensorShape([Dimension(2), Dimension(2)])
#注意此处的y的shape大小是2*2 二维不是2*2*1三维
3 tf.expand_dims
>>> x=tf.constant([[1,2],[3,4]])
>>> sess=tf.Session()
>>> print(sess.run(x))
[[1 2]
[3 4]]
>>> y=tf.expand_dims(x,-1) # 对x的最后的维度添加1维
>>> y.shape
TensorShape([Dimension(2), Dimension(2), Dimension(1)])
>>> print(sess.run(y))
[[[1]
[2]]
[[3]
[4]]]
>>> y=tf.expand_dims(x,1) # 在第1维度添加1维
>>> print(sess.run(y))
[[[1 2]]
[[3 4]]]
4 tf.boolean_mask
>>> y=tf.constant([1,2,3,4,5,6,7,8])
>>> print(sess.run(tf.boolean_mask(y,[1])))
>>> mask=y >2
>>> print(sess.run(mask))
[False False True True True True True True]
>>> print(sess.run(tf.boolean_mask(y,mask)))
[3 4 5 6 7 8]