提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
tips
写这篇文章的目的是防止在RNN上踩过的坑,以后再来一次。毕竟结构性的内容不难理解,最重要的代码实现往往最容易出问题,相信一起深耕过paper然后写代码的你们应该也经历过。(other:我个人学习能力属于差生,语言沟通也不是很好,所以文章的问题还望多提意见)
rnn 的核心内容
此处借用了沐神、教父…(后面的名字越来越离谱)的图来说明
参考:https://zh-v2.d2l.ai/chapter_recurrent-neural-networks/rnn.html

非常简单的两个公式
H t = W x h × X t − 1 + W h h × H t − 1 + b h X p r e d i c t = W q × H t + b q H_t = W_{xh} \times X_{t-1} + W_{hh} \times H_{t-1} + b_h \\ X_{predict} = W_{q} \times Ht + b_q Ht=Wxh×Xt−1+Whh×Ht−1+bhXpredict=Wq×Ht+bq
在此有一个编码中的误区,那就是如果输入 X t − 1 X_{t-1} Xt−1 ,在得到预测结果 X p r e d i c t X_{predict} Xpredict,
得到的 H t H_t Ht在图解中,需要参与下一次 X t X_t Xt纵向的预测,以及生成 H t + 1 H_{t+1} Ht+1
rnn 单个句子的实验代码设计
根据上述原理可以初步设计一个,只有一个句子情况下的rnn编码。
import torch
from torch import nn
import re
import collections
from torch.nn import functional as F
sentence = "this is a difficult problem,is not simple"
def get_words_from_sentence(str):
return re.sub("[^a-zA-Z]", " ", str).split()
def get_token_to_idx(words):
words_corpus = collections.Counter(words)
return {
token: idx for idx, (token, _) in enumerate(words_corpus.items())}
def get_idx_to_token(words):
return [k for k in get_token_to_idx(words)]
def sgd(params, lr=0.01):
with torch.no_grad():
for param in params:
slope = param

最低0.47元/天 解锁文章
554

被折叠的 条评论
为什么被折叠?



