numpy.pad、numpy.reshape、numpy.transpose

在卷积神经网络中,在convolutional layer需要对tensor进行填充,在数据处理时需要改变tensor的形状,对tensor进行转置。


 numpy.pad(array, pad_width, mode, **kwargs),array为需要填充的array对象,pad_width为各个维度需要填充的宽度,mode为填充模式,常用的为constant。

 1 import numpy as np
 2 
 3 # np.pad
 4 vector = np.array([1, 2])
 5 vector_pad_constant = np.pad(vector, (1, 2), 'constant', constant_values=(3, 4))
 6 vector_pad_edge = np.pad(vector, (1, 2), 'edge')
 7 print(vector_pad_constant)
 8 print(vector_pad_edge)
 9 
10 matrix = np.array([[1, 2], [3, 4]])
11 matrix_pad_constant = np.pad(matrix, [(1, 1), (2, 2)], 'constant', constant_values=[(1,2), (3, 4)]) # 二维数组pad_width传入数组,表示先在上下方向填充多上行,再在左右填充多少列
12 matrix_pad_edge = np.pad(matrix, [(1, 1), (2, 2)], 'edge')
13 print('---------------------------------------')
14 print(matrix_pad_constant)
15 print(matrix_pad_edge)
[3 1 2 4 4]
[1 1 2 2 2]
---------------------------------------
[[3 3 1 1 4 4]
 [3 3 1 2 4 4]
 [3 3 3 4 4 4]
 [3 3 2 2 4 4]]
[[1 1 1 2 2 2]
 [1 1 1 2 2 2]
 [3 3 3 4 4 4]
 [3 3 3 4 4 4]]

  numpy.reshape(anewshapeorder='C'),a为需要reshape对象,newshape为新的形状。

1 # np.reshape
2 matrix_reshape = matrix.reshape(4, -1) # reshape为一个4*?的矩阵,-1表示列数自动计算
3 print(matrix_reshape.shape)
4 print(matrix_reshape)
5 
6 _matrix_reshape = matrix.reshape(-1, 4) # 行数自动计算
7 print(_matrix_reshape.shape)
8 print(_matrix_reshape)
(4, 1)
[[1]
 [2]
 [3]
 [4]]
(1, 4)
[[1 2 3 4]]

numpy.transpose(aaxes=None),a为需要转置对象,axes为None时,默认反转矩阵的维度,否则按照axes的值重新排列矩阵。

By default, reverse the dimensions, otherwise permute the axes according to the values given.。

1 # np.transpose
2 tensor = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
3 tensor_reshape = tensor.reshape((2, 2, 3))
4 print(tensor_reshape.shape)
5 print(tensor_reshape)
6 
7 tensor_transpose = tensor_reshape.transpose(2, 0, 1)
8 print(tensor_transpose.shape)
9 print(tensor_transpose)
(2, 2, 3)
[[[ 1  2  3]
  [ 4  5  6]]

 [[ 7  8  9]
  [10 11 12]]]
(3, 2, 2)
[[[ 1  4]
  [ 7 10]]

 [[ 2  5]
  [ 8 11]]

 [[ 3  6]
  [ 9 12]]]

猜你喜欢

转载自www.cnblogs.com/techi/p/11621032.html