Code Reference

查过的代码,随手记录

Updated on July 17, 2020
Posted by Jing Yang on July 13, 2020

Numpy

.dot

a.dot(b)表示两个向量内积

A.dot(B) 表示两个矩阵的矩阵乘法

np.linspace

np.linspace(start,end,Number)从start到end,生成等距的维度为Number的向量。如果start和end是向量的话,则生成对应矩阵

np.random.randn

np.random.randn(5,3)创建一个5×3的随机矩阵,元素为满足标准正态分布的随机变量

.repeat(a,b)

A.repeat(a,b)表示将A在维度b复制a次。b=1表示复制列

pad(array, pad_width)

#在数组A的边缘填充constant_values指定的数值

#(3,2)表示在A的第[0]轴填充(二维数组中,0轴表示行),即在0轴前面填充3个宽度的0,比如数组A中的95,96两个元素前面各填充了3个0;在后面填充2个0,比如数组A中的97,98两个元素后面各填充了2个0*

#(2,3)表示在A的第[1]轴填充(二维数组中,1轴表示列),即在1轴前面填充2个宽度的0,后面填充3个宽度的0*

A = np.arange(95,99).reshape(2,2)
array([[95, 96],
       [97, 98]])
np.pad(A,((3,2),(2,3)),'constant',constant_values = (0,0))  

#constant_values表示填充值,且(before,after)的填充值等于(0,0)

array([[ 0,  0,  0,  0,  0,  0,  0],
       [ 0,  0,  0,  0,  0,  0,  0],
       [ 0,  0,  0,  0,  0,  0,  0],
       [ 0,  0, 95, 96,  0,  0,  0],
       [ 0,  0, 97, 98,  0,  0,  0],
       [ 0,  0,  0,  0,  0,  0,  0],
       [ 0,  0,  0,  0,  0,  0,  0]])

Pytorch

随机取样

假设有num_examples个样本

def select_data_batch(features,labels,batch_size):
    num_examples=features.size(0)
	indices=list(range(num_examples))
	random.shuffle(indices) #对样本序号进行随机
	for i in range(0,num_examples,batch_size)
		j=torch.LongTensor(indices[i:min(i+batch_size,num_examples)]) 
    	yield features.index_select(0,j),labels.index_select(0,j)

torch.index_select ( A, i , j )

也可以写作 A.index_select (i,j) 表示A的维度i,选取indece为j的元素,j可以使indice集合。比如要选取第3、4行的向量,可以是 A.index_select (0,[3,4])

torch.cat

torch.cat(A,B,int)将A和B两个矩阵从维度int拼接在一起

torch.matmul

torch.matmul(A,B) 根据A和B的类型进行乘法。若均为向量,则为点积;若A是矩阵,B是向量或是矩阵,则按照矩阵乘法。

数组排序后还原

l = torch.randint(10,(10,))
a, idx1 = torch.sort(l)
b, idx2 = torch.sort(idx1)
a.index_select(0,idx2) #0表示选择的维度  返回值为l

import matplotlib.pyplot as plt

plt.scatter

plt.scatter(a.numpy(),b.numpy(),size=2) 以a为横轴,b为纵轴,点的size为2