pytorch随笔:一

1. embedding

import torch.nn as nn

embed=nn.embedding(dic_size,word_vec)

embed(torch.tensor([1,2,3]))

embedding功能在nn里,初始化给出两个参数(词表大小,词向量维度),这时给出的其实是一个随机化的矩阵,传入索引访问。

2. 构建网络的方式

(1) 通过类来构建

class Net(torch.nn.Module):
    def __init__(self, n_feature, n_hidden, n_output):
        super(Net, self).__init__()
        self.hidden = torch.nn.Linear(n_feature, n_hidden)
        self.predict = torch.nn.Linear(n_hidden, n_output)

    def forward(self, x):
        x = F.relu(self.hidden(x))
        x = self.predict(x)
        return x
print(net1)
"""
Net (
  (hidden): Linear (1 -> 10)
  (predict): Linear (10 -> 1)
)
"""

Net类继承torch.nn.Module,在init方法中是对一些层的声明,其实这些初始化工作在forward中也可以进行,这样做可以使结构更加清晰。注意反向传播的时候才加入的relu在print中并没有

(2)快速构建

net2 = torch.nn.Sequential(
    torch.nn.Linear(1, 10),
    torch.nn.ReLU(),
    torch.nn.Linear(10, 1)
)
print(net2)
"""
Sequential (
  (0): Linear (1 -> 10)
  (1): ReLU ()
  (2): Linear (10 -> 1)
)
"""

这种方式好处是简单,但是没有上一种灵活。

3. view,squeeze,unsqueeze

view

相当于reshape,传入一个表示维度的元祖,可以有一个-1代表维度不定,通过其他维度算得

In [6]: t
Out[6]:
tensor([[ 4,  1,  8],
        [ 1,  0,  5]], dtype=torch.int32)

In [7]: t.shape
Out[7]: torch.Size([2, 3])

In [8]: t.view(3,2)
Out[8]:
tensor([[ 4,  1],
        [ 8,  1],
        [ 0,  5]], dtype=torch.int32)

sequeeze

传入一个整型索引值,0表示第一个维度。如果该维度是1,则去掉

unsequeeze

In [30]: t.shape
Out[30]: torch.Size([2, 3])

In [31]: t.unsqueeze(0).shape
Out[31]: torch.Size([1, 2, 3])

In [32]: t.squeeze(0).shape
Out[32]: torch.Size([2, 3])

4. pytorch中的矩阵点乘

在pytorch中文文档中对于torch.mul还没有修改,在新版的pytorch中,形状不同数量相同的两个矩阵是无法做乘法的。也就是说在中文文档的例子中,下面这个操作没办法用了:

>>> a = torch.randn(4,4)
>>> a

-0.7280  0.0598 -1.4327 -0.5825
-0.1427 -0.0690  0.0821 -0.3270
-0.9241  0.5110  0.4070 -1.1188
-0.8308  0.7426 -0.6240 -1.1582
[torch.FloatTensor of size 4x4]

>>> b = torch.randn(2, 8)
>>> b

 0.0430 -1.0775  0.6015  1.1647 -0.6549  0.0308 -0.1670  1.0742
-1.2593  0.0292 -0.0849  0.4530  1.2404 -0.4659 -0.1840  0.5974
[torch.FloatTensor of size 2x8]

>>> torch.mul(a, b)

-0.0313 -0.0645 -0.8618 -0.6784
 0.0934 -0.0021 -0.0137 -0.3513
 1.1638  0.0149 -0.0346 -0.5068
-1.0304 -0.3460  0.1148 -0.6919
[torch.FloatTensor of size 4x4]

猜你喜欢

转载自blog.csdn.net/gt362ll/article/details/83045700