numpy与tensorflow操作(一)

numpy.meshgrid(x,y)

[X,Y] = meshgrid(x,y)

生成size(y)Xsize(x)大小的矩阵X和Y。它相当于x从一行重复增加到size(y)行,把y转置成一列再重复增加到size(x)列。因此命令等效于:

X=ones(size(y))*x;
Y=y’*ones(size(x))

x = np.linspace(-1,1,2)
y = np.linspace(-1,1,5)
print(x)
print(y)
new_x, new_y = np.meshgrid(x,y)
print(new_x)
print(new_y)
'''
[-1.  1.]
[-1.  -0.5  0.   0.5  1. ]
[[-1.  1.]
 [-1.  1.]
 [-1.  1.]
 [-1.  1.]
 [-1.  1.]]
[[-1.  -1. ]
 [-0.5 -0.5]
 [ 0.   0. ]
 [ 0.5  0.5]
 [ 1.   1. ]]
'''

numpy.vstack()

按列堆叠矩阵

a = np.identity(2)
b = np.identity(2)*2
c = np.vstack([a,b])
print(c)
'''
[[1. 0.]
 [0. 1.]
 [2. 0.]
 [0. 2.]]
'''

numpy.prod()

对应轴上元素的乘积 默认没有轴,即所有元素乘积。 axis=0 按列 axis=1 按行

a = np.prod([[1.,2.],[3.,4.]])
print(a)
a = np.prod([[1.,2.],[3.,4.]], axis=0)
print(a)
a = np.prod([[1.,2.],[3.,4.]], axis=1)
print(a)
'''
24.0
[3. 8.]
[ 2. 12.]
'''

—————————————————————————————————————

tensorflow.range()

用于构造数列。

range(limit, delta=1, dtype=None, name='range')
range(start, limit, delta=1, dtype=None, name='range')

 

tensorflow.tile()

通过平铺(tile)给定的张量来构造张量。第i维平铺multiples[i]次

tf.tile(
    input,
    multiples,
    name=None
)
with tf.Session() as sess:
    a = tf.tile([1,2,3],[2])
    print(sess.run(a))
    b = tf.tile([[1,2,3],[4,5,6],[7,8,9]],[2,3])
    print(sess.run(b))

'''
[1 2 3 1 2 3]
[[1 2 3 1 2 3 1 2 3]
 [4 5 6 4 5 6 4 5 6]
 [7 8 9 7 8 9 7 8 9]
 [1 2 3 1 2 3 1 2 3]
 [4 5 6 4 5 6 4 5 6]
 [7 8 9 7 8 9 7 8 9]]

'''

tensorflow.stack()

tf.stack(
    values,
    axis=0,
    name='stack'
)
x = tf.constant([1, 4])
y = tf.constant([2, 5])
z = tf.constant([3, 6])
tf.stack([x, y, z])  # [[1, 4], [2, 5], [3, 6]] (Pack along first dim.)
tf.stack([x, y, z], axis=1)  # [[1, 2, 3], [4, 5, 6]]

给定一个形状为(A, B, C)的张量的长度 N 的列表;

如果 axis == 0,那么 output 张量将具有形状(N, A, B, C)。如果 axis == 1,那么 output 张量将具有形状(A, N, B, C)。

a = tf.ones((2,3,4))
b = tf.zeros((2,3,4))
c = tf.ones((2,3,4)) * 2
indices = tf.stack([a, b, c])
'''

[[[[1. 1. 1. 1.]
   [1. 1. 1. 1.]
   [1. 1. 1. 1.]]

  [[1. 1. 1. 1.]
   [1. 1. 1. 1.]
   [1. 1. 1. 1.]]]


 [[[0. 0. 0. 0.]
   [0. 0. 0. 0.]
   [0. 0. 0. 0.]]

  [[0. 0. 0. 0.]
   [0. 0. 0. 0.]
   [0. 0. 0. 0.]]]


 [[[2. 2. 2. 2.]
   [2. 2. 2. 2.]
   [2. 2. 2. 2.]]

  [[2. 2. 2. 2.]
   [2. 2. 2. 2.]
   [2. 2. 2. 2.]]]]
'''

tensorflow.gather_nd()

将参数中的切片收集到由索引指定的形状的张量中

gather_nd(
    params,
    indices,
    name=None
)
indices = [[0, 1], [1, 0]]
params = [[['a0', 'b0'], ['c0', 'd0']],
          [['a1', 'b1'], ['c1', 'd1']]]
output = [['c0', 'd0'], ['a1', 'b1']]

References:

https://blog.csdn.net/m0_37908327/article/details/68953784

https://www.cnblogs.com/sunshinewang/p/6897966.html

https://blog.csdn.net/guotong1988/article/details/73564947

https://www.w3cschool.cn/tensorflow_python/

猜你喜欢

转载自blog.csdn.net/sinat_37011812/article/details/81837437