使用Pytorch

时间:2019-11-08 19:11:23

标签: python nlp pytorch softmax

我正在使用Pytorch 1.3.0运行循环网络,其中输入是来自小概率语法(单次热编码)的单词,目标是输入之前的一个单词。我已经成功运行了模型,但是我想知道是否有一种方法可以在给定输入单词的情况下返回可能的下一个单词的概率分布。我的最终目标是测量网络输出偏离此概率分布的程度。

我已经看到其他示例使用softmax函数来获取概率张量,但仅在单词/字符生成的情况下。因此,我使用了相同的函数,但是插入了Forward函数中。然后我使用了print(),因为我无法获得没有错误返回的函数(也因为我不知道自己在做什么)。

为简单起见,我只用一句话来运行模型:“猫跑了”

一种热编码如下,并附带目标序列“猫奔跑”。(编码中包含的时间段):

input_seq = np.array([[[0., 0., 1., 0.],
                       [0., 1., 0., 0.],
                       [0., 0., 0., 1.]]], dtype = np.float32) 

target_seq = [[1, 3, 0]]

然后使用Pytorch,这是我的模型代码:

device = torch.device("cpu")

input_seq = torch.from_numpy(input_seq)
target_seq = torch.Tensor(target_seq)

class Model(nn.Module):
    def __init__(self, input_size, output_size, hidden_dim, n_layers):
        super(Model, self).__init__()
        self.hidden_dim = hidden_dim
        self.n_layers = n_layers
        self.rnn = nn.RNN(input_size, hidden_dim, n_layers, batch_first=True)   
        self.fc = nn.Linear(hidden_dim, output_size)

    def forward(self, x):

        batch_size = x.size(0)
        hidden = self.init_hidden(batch_size)
        out, hidden = self.rnn(x, hidden)

        out = out.contiguous().view(-1, self.hidden_dim)
        out = self.fc(out)
        prob = nn.functional.softmax(out[-1], dim=0).data  # here is where I included the code
        print(prob)

        return out, hidden

    def init_hidden(self, batch_size):
        hidden = torch.zeros(self.n_layers, batch_size, self.hidden_dim).to(device)
        return hidden

这是我实例化模型的地方:

model = Model(input_size=dict_size, output_size=dict_size, hidden_dim=12, n_layers=1)
model.to(device)
n_epochs = 5  # epochs set to 5 for simplicity
lr=0.01
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=lr)

最后是培训:

for epoch in range(1, n_epochs + 1):
    optimizer.zero_grad() 
    input_seq = input_seq.to(device)
    output, hidden = model(input_seq)
    loss = criterion(output, target_seq.view(-1).long())
    loss.backward() 
    optimizer.step()

    print('Epoch: {}/{}.............'.format(epoch, n_epochs), end=' ')
    print("Loss: {:.4f}".format(loss.item()))

运行代码时,它将每个单词的概率打印为张量,但仅在每个时期的末尾而不是在每个单词输入之后输出。

所以我的两个问题是:

1)无论如何,序列中的每个单词之后都可以输出概率?因此,在此示例中,当模型处理“猫”时,它将返回所有可能单词的概率。还是那是无法完成的事情?

2)然后,如果对问题1回答“是”,是否可以通过print()函数返回概率而不是使用class IconTabGeneral: NSView { override func draw(_ dirtyRect: NSRect) { StyleKitMac.drawTabGeneral() } } 函数? (因此基本上返回变量而不会导致错误)

这是我第一次询问有关堆栈溢出的问题,也是我在Pytorch上的第一次实际经验,因此对于任何混乱(以及我对此领域的知识不足),我深表歉意!

0 个答案:

没有答案