1、torch.manual_seed(int):
在神经网络中,参数默认是进行随机初始化的。如果不设置的话每次训练时的初始化都是随机的,导致结果不确定。如果设置初始化,则每次初始化都是固定的。
def manual_seed(seed):
r"""Sets the seed for generating random numbers. Returns a
`torch.Generator` object.
Args:
seed (int): The desired seed.
"""
seed = int(seed)
import torch.cuda
if not torch.cuda._is_in_bad_fork():
torch.cuda.manual_seed_all(seed)
return default_generator.manual_seed(seed)
2、`x.narrow`(*dimension*, *start*, *length*) → Tensor
表示取变量x的第dimension维,的从索引start开始到,start+length范围的值.
x = torch.Tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
3、 .t() 是 .transpose函数的简写版本,只能对2维以下的tensor进行转置。
.transpose函数对一个n维tensor交换其任意两个维度的顺序 :torch.transpose(input,dim0,dim1)
.T 是 .permute 函数的简化版本,不仅可以操作2维tensor,甚至可以对n维tensor进行转置。当然当维数n=2时,.t() 与 .T 效果是一样的。
4、contiguous:view只能用在连续的variable上。如果在view之前用了transpose, permute等,需要用contiguous()来返回一个contiguous copy。隐含意思:转置和换维度可能会导致结果不是contiguous
有些tensor并不是占用一整块内存,而是由不同的数据块组成,而tensor的view()
操作依赖于内存是整块的,这时只需要执行contiguous()
这个函数,把tensor变成在内存中连续分布的形式。
判断是否contiguous用x.is_contiguous()
函数。
在pytorch的最新版本0.4版本中,增加了torch.reshape(), 这与 numpy.reshape 的功能类似。它大致相当于 tensor.contiguous().view()
5、permute() 将tensor的维度换位。
permute(*dims) → Tensor
>>> x = torch.randn(2, 3, 5)
>>> x.size()
torch.Size([2, 3, 5])
>>> x.permute(2, 0, 1).size()
torch.Size([5, 2, 3])
6、torch.cat()
用处1 :传入类型为tensor的list
用处2:
如果我们有两个tensor是A和B,想把他们拼接在一起,需要指定维数
C = torch.cat( (A,B),0 ) #按维数0拼接(竖着拼)
C = torch.cat( (A,B),1 ) #按维数1拼接(横着拼)
6、nn.NLLLoss(torch.log(nn.Softmax(x,dim=1))) ------->nn.CrossEntropyLoss(x)
CrossEntropyLoss就是把以上Softmax–Log–NLLLoss合并成一步
交叉熵公式:刻画的是实际输出p与期望输出q的距离,也就是交叉熵的值越小
但是Pytorch的公式不是这样的(惊喜吧!)
这是交叉熵的另外一种方式,Pytorch中CrossEntropyLoss()函数的主要是将softmax-log-NLLLoss合并到一块得到的结果。
7、torch.nn.Embedding()
官网的类解释:一个简单的查询表,存储了一个固定字典和大小的词嵌入
这个模块经常被用来存储词嵌入,并可以使用索引来获取他们。模块的输入是词表的大小和嵌入的维度,输出是先对应的词嵌入
A simple lookup table that stores embeddings of a fixed dictionary and size.
This module is often used to store word embeddings and retrieve them using indices. The input to the module is a list of indices, and the output is the corresponding word embeddings.