基础配置
import numpy as npimport torchimport torch.nn as nn#设置单元格全部行的输出结果from IPython.core.interactiveshell import InteractiveShellInteractiveShell.ast_node_interactivity = "all"
np.concatenate()用法
concatenate功能:数组拼接
函数定义:numpy.concatenate((a1, a2, …), axis=0, out=None)
Parameters:
a1, a2, … : 数组序列,除了axis对应的轴,数组其他维度必须一样
axis : 可选,默认是0
out : 多维数组,可选,如果out提供,则结果保存在out中。数组大小必须正确,与真实结果相匹配。
Returns: res : 多维数组,最后拼接好的数组
a = np.array([[1, 2], [3, 4]])b = np.array([[5, 6]])np.concatenate((a, b), axis=0)np.concatenate((a, b.T), axis=1)
array([[1, 2],[3, 4],[5, 6]])array([[1, 2, 5],[3, 4, 6]])
numpy.empty()用法
numpy.empty 方法用来创建一个指定形状(shape)、数据类型(dtype)、顺序且未初始化(随机)的数组:
numpy.empty(shape, dtype = float, order = ‘C’)
参数说明
shape    数组形状
dtype 数据类型,可选
order 有”C”和”F”两个选项,分别代表,行优先和列优先,在计算机内存中的存储元素的顺序。
import numpy as npx = np.empty([3,2], dtype = int,order='C')print (x)
[[ 538976288 1092624416][1701410336 1718558839][1617780768 1953068832]]
取上、下三角矩阵(常用于mask)
np.tiru()用法
语法:np.triu(m, k=0) m:表示一个矩阵,K:表示对角线的起始位置(k取值默认为0),取矩阵的上三角矩阵
data=torch.arange(25).reshape((5,5))data#k=0表示正常的上三角矩阵upper_triangle = np.triu(data, 0)upper_triangle#k=-1表示对角线的位置下移1个对角线upper_triangle = np.triu(data, -1)upper_triangle#k=1表示对角线的位置上移1个对角线upper_triangle = np.triu(data, 1)upper_triangle
tensor([[ 0, 1, 2, 3, 4],[ 5, 6, 7, 8, 9],[10, 11, 12, 13, 14],[15, 16, 17, 18, 19],[20, 21, 22, 23, 24]])array([[ 0, 1, 2, 3, 4],[ 0, 6, 7, 8, 9],[ 0, 0, 12, 13, 14],[ 0, 0, 0, 18, 19],[ 0, 0, 0, 0, 24]], dtype=int64)array([[ 0, 1, 2, 3, 4],[ 5, 6, 7, 8, 9],[ 0, 11, 12, 13, 14],[ 0, 0, 17, 18, 19],[ 0, 0, 0, 23, 24]], dtype=int64)array([[ 0, 1, 2, 3, 4],[ 0, 0, 7, 8, 9],[ 0, 0, 0, 13, 14],[ 0, 0, 0, 0, 19],[ 0, 0, 0, 0, 0]], dtype=int64)
tril(m, k)用法
tril(m, k)取矩阵的下三角阵
lower_triangle = np.tril(data, 0)lower_trianglelower_triangle = np.tril(data, -1)lower_trianglelower_triangle = np.tril(data, 1)lower_triangle
array([[ 0, 0, 0, 0, 0],[ 5, 6, 0, 0, 0],[10, 11, 12, 0, 0],[15, 16, 17, 18, 0],[20, 21, 22, 23, 24]], dtype=int64)array([[ 0, 0, 0, 0, 0],[ 5, 0, 0, 0, 0],[10, 11, 0, 0, 0],[15, 16, 17, 0, 0],[20, 21, 22, 23, 0]], dtype=int64)array([[ 0, 1, 0, 0, 0],[ 5, 6, 7, 0, 0],[10, 11, 12, 13, 0],[15, 16, 17, 18, 19],[20, 21, 22, 23, 24]], dtype=int64)
a=np.triu(np.ones((1, 10, 10)), k=1)a
array([[[0., 1., 1., 1., 1., 1., 1., 1., 1., 1.],[0., 0., 1., 1., 1., 1., 1., 1., 1., 1.],[0., 0., 0., 1., 1., 1., 1., 1., 1., 1.],[0., 0., 0., 0., 1., 1., 1., 1., 1., 1.],[0., 0., 0., 0., 0., 1., 1., 1., 1., 1.],[0., 0., 0., 0., 0., 0., 1., 1., 1., 1.],[0., 0., 0., 0., 0., 0., 0., 1., 1., 1.],[0., 0., 0., 0., 0., 0., 0., 0., 1., 1.],[0., 0., 0., 0., 0., 0., 0., 0., 0., 1.],[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]]])
