strided_slice
这个函数是对数组进行切片,第一个参数是待处理的数组,后面三个list分别是起始坐标,结束坐标,步长。比如二维数组,第一维从0开始到10结束,步长1,第二维从3开始到6结束,步长2,应写作[0,3],[11,7],[1,2]
sess = tf.Session()
a = np.array([[1,2,3],[4,5,6]])
op1 = tf.strided_slice(a,[0,0],[2,2],[1,1])
print(sess.run(op1))
op2 = tf.strided_slice(a,[1,1],[2,2],[1,1])
print(sess.run(op2))
输出是
[[1 2]
[4 5]]
[[5]]
fill
按照尺寸填充一个数组
op = tf.fill([2,3],1)
sess.run(op)
输出是
array([[1, 1, 1],
[1, 1, 1]], dtype=int32)
cond
cond(condition, f1, f2)
先判断condition,为真执行f1,否则执行f2,注意condition需要是tensorflow的tensor,不能是python的bool
x = 10
y = 20
r = tf.cond(tf.less(x, y), lambda : tf.multiply(x, 17), lambda : tf.add(y, 23))
sess.run(r)
输出为
170
reduce_sum
其他reduce开头的方法和这个类似
按照axis进行求和
a=np.array([[1,2],[3,4]])
op=tf.reduce_sum(a)
print(sess.run(op))
op=tf.reduce_sum(a,1)
print(sess.run(op))
op=tf.reduce_sum(a,0)
print(sess.run(op))
输出为
10
[3 7]
[4 6]
concat
按照axis合并
a=np.array([[1,2],[3,4]])
b=np.array([[5,6],[7,8]])
op=tf.concat([a,b],1)
print(sess.run(op))
op=tf.concat([a,b],0)
print(sess.run(op))
输出为:
[[1 2 5 6]
[3 4 7 8]]
[[1 2]
[3 4]
[5 6]
[7 8]]
squeeze
降维,把维度为1的轴消掉。比如有array有shape是[1,2,1,4],参数设置[0]就会把数组维度变为[2,1,4],参数设置[0,2]就会把数组维度变为[2,4]
a = np.array([[[[1,2,3,4]],[[1,2,3,4]]]])
print(a.shape)
op = tf.squeeze(a,[0])
print(sess.run(op))
print(sess.run(op).shape)
op = tf.squeeze(a,[2])
print(sess.run(op))
print(sess.run(op).shape)
op = tf.squeeze(a,[0,2])
print(sess.run(op))
print(sess.run(op).shape)
输出为:
(1, 2, 1, 4)
[[[1 2 3 4]]
[[1 2 3 4]]]
(2, 1, 4)
[[[1 2 3 4]
[1 2 3 4]]]
(1, 2, 4)
[[1 2 3 4]
[1 2 3 4]]
(2, 4)
expand_dims
和squeeze相反,升维
a = np.array([[1,2,3,4],[1,2,3,4]])
print(a.shape)
op=tf.expand_dims(a, 0)
print(sess.run(op))
print(sess.run(op).shape)
输出为:
(2, 4)
[[[1 2 3 4]
[1 2 3 4]]]
(1, 2, 4)
stack
按axis进行叠加
a = [1, 4]
b = [2, 5]
c = [3, 6]
op = tf.stack([a,b,c])
print(sess.run(op))
print(sess.run(op).shape)
op = tf.stack([a,b,c],axis=1)
print(sess.run(op))
print(sess.run(op).shape)
输出为:
[[1 4]
[2 5]
[3 6]]
(3, 2)
[[1 2 3]
[4 5 6]]
(2, 3)
unstack
按照axis把array展开,结果为一个list
a = np.array([[1,2,3,4],[1,2,3,4]])
print(a.shape)
op = tf.unstack(a)
print(sess.run(op))
op = tf.unstack(a,axis=1)
print(sess.run(op))
输出为:
(2, 4)
[array([1, 2, 3, 4]), array([1, 2, 3, 4])]
[array([1, 1]), array([2, 2]), array([3, 3]), array([4, 4])]
gather
按照indice选择param的值进行组合
param = [1, 2]
indice1 = [0, 1]
indice2 = [0,0,1]
indice3 = 1
indice4 = [[0,1]]
op = tf.gather(a,indice1)
print(sess.run(op))
op = tf.gather(a,indice2)
print(sess.run(op))
op = tf.gather(a,indice3)
print(sess.run(op))
op = tf.gather(a,indice4)
print(sess.run(op))
输出为:
[1 2]
[1 1 2]
2
[[1 2]]
tile
将原始数组按照参数进行复制,参数的长度要和原始数组的维数相同
a=[[[1,2,3],[4,5,6]]]
op = tf.tile(a,[1,1,1])
print(sess.run(op))
op = tf.tile(a,[1,2,1])
print(sess.run(op))
op = tf.tile(a,[1,2,2])
print(sess.run(op))
输出为:
[[[1 2 3]
[4 5 6]]]
[[[1 2 3]
[4 5 6]
[1 2 3]
[4 5 6]]]
[[[1 2 3 1 2 3]
[4 5 6 4 5 6]
[1 2 3 1 2 3]
[4 5 6 4 5 6]]]