PyTorch 也是第一个以随机计算图(stochastic computation graph)情势建立强化进修(RL)库的框架,使得策略梯度(policy gradient)强化进修如反向传播一样易于应用。要将其添加到上述模型中,你只需从新编写主 SPINN 的 for 轮回的前几行,如下所示,使得 Tracker 可以或许定义进行每种解析转移矩阵的概率。
- !# nn.functional contains neural network operations without parametersfrom torch.nn import functional as F
- transitions = []for i in range(len(buffers[0]) * 2 - 3):
- # we know how many steps
- # obtain raw scores for each kind of parser transition
- tracker_states, transition_scores = self.tracker(buffers, stacks)
- # use a softmax function to normalize scores into probabilities,
- # then sample from the distribution these probabilities define
- transition_batch = F.softmax(transition_scores).multinomial()
- transitions.append(transition_batch
然后,跟着批处理一向运行,模型会得出它猜测的类其余精确程度,我可以经由过程这些随机计算图的节点发出嘉奖旌旗灯号,别的在图的其余部分以传统方法进行反向传播:
- # losses should contain a loss per example, while mean and std
- # represent averages across many batches
- rewards = (-losses - mean) / std
- for transition in transitions:
- transition.reinforce(rewards)
- # connect the stochastic nodes to the final loss variable
- # so that backpropagation can find them, multiplying by zero
- # because this trick shouldn’t change the loss value
- loss = losses.mean() + 0 * sum(transitions).sum()
- # perform backpropagation through deterministic nodes and
- # policy gradient RL for stochastic nodesloss.backward()
- from torchtext import data, datasets TEXT = datasets.snli.ParsedTextField(lower=True)
- TRANSITIONS = datasets.snli.ShiftReduceField()
- LABELS = data.Field(sequential=False)train, dev, test = datasets.SNLI.splits( TEXT, TRANSITIONS, LABELS, wv_type='glove.42B')TEXT.build_vocab(train, dev, test)
- train_iter, dev_iter, test_iter = data.BucketIterator.splits( (train, dev, test), batch_size=64)
推荐阅读
【义务编辑:wangxueyan TEL:(010)68476606】 >>>详细阅读
本文标题:如何用PyTorch实现递归神经网络?
地址:http://www.17bianji.com/lsqh/34965.html
1/2 1

网友点评
精彩导读
科技快报
品牌展示