RNN及其简单Python代码示例

本文介绍了递归神经网络RNN的基本概念、优缺点、应用场景和相关概念,重点阐述了RNN的网络结构和公式推导。通过一个Python代码示例展示了RNN如何实现八位二进制数加法,同时提到了为解决RNN梯度消失问题的LSTM网络。
摘要由CSDN通过智能技术生成

1 概述

递归神经网络是时间递归神经网络(recurrent neural network)和结构递归神经网络(recursive neural network)的总称。RNN一般指代时间递归神经网络。

RNN早先被提到的可以追溯到1989年Axel Cleeremans的论文。
详情查看:http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.160.2979&rep=rep1&type=pdf
RNN被提出的初衷是用来处理序列数据的。
RNN相对于传统神经网络最大的不同是神经元的输入的改变。RNN隐藏层神经元的输入不止是上一层神经元的输出,还包括了本层的输出。
但是鉴于RNN误差反向传播时候梯度消失的问题。1997年Sepp Hochreiter等人提出了典型的LSTM网络。
详情查看:http://www.bioinf.jku.at/publications/older/2604.pdf
LMST是RNN的升级版,它的隐藏层神经元的输入和输出会在RNN的基础上做进一步的处理,在本文末有提到。

RNN背后的思想是利用顺序信息。它包含循环的网络,允许信息的持久化。

2 优缺点

优点:时间递归神经网络可以描述动态时间行为,因为和前馈神经网络接受较特定结构的输入不同,RNN将状态在自身网络中循环传递,因此可以接受更广泛的时间序列结构输入。

缺点:简单递归神经网络无法处理随着递归,梯度爆炸或者梯度消失的问题,并且难以捕捉长期时间关联;有效的处理方法是忘掉错误的信息,记住正确的信息。LSTM能够比较好的解决这个问题。

3 应用

RNN已经被在实践中证明对NLP是非常成功的。如词向量表达,语句合法性检查,词性标注等。在RNN中,目前使用最广泛最成功的模型是LSTM模型。
基于LSTM的系统可以学习翻译语言、控制机器人、图像分析、文档摘要、语音识别图像识别、手写识别、控制聊天机器人、预测疾病、点击率和股票、合成音乐等等任务。举个例子,在2015年,谷歌通过基于CTC训练的LSTM程序大幅提升了安卓手机和其他设备中语音识别的能力,使用了我的实验室在2006年发表的方法。百度也使用了CTC;苹果的iPhone在QucikType和Siri中使用了LSTM;微软不仅将LSTM用于语音识别,还将这一技术用于虚拟对话形象生成和编写程序代码等等。亚马逊Alexa通过双向LSTM在家中与你交流,而谷歌使用LSTM的范围更加广泛,它可以生成图像字幕,自动回复电子邮件,它包含在新的智能助手Allo中,也显著地提高了谷歌翻译的质量(从2016年开始)。事实上,谷歌数据中心的很大一部分计算资源现在都在执行LSTM任务。
内容链接地址:https://www.zhihu.com/question/37082800/answer/173870605

4 相关概念

序列: 序列是被排成一列的对象(或事件)。可以是一句话,一串数字等。RNN训练数据时,会以序列为单位训练数据。同一序列中的每次训练代表一个时刻t。

5 RNN网路结构

从上图我们可以看出,RNN隐藏层神经元的连接方式和普通神经网路的连接方式有一个非常明显的区别,就是同一层的神经元的输出也成为了这一层神经元的输入。当然同一时刻的输出是不可能作为这个时刻的输入的。所以是前一个时刻(t-1)的输出作为这个时刻(t)的输入。

上图就是一个序列的结构展开示意图。

6 公式推导

设输入层到隐层的权重矩阵为V;隐层自循环的权重矩阵为U;隐层到输出层的权重矩阵为W;对应的偏置为 bh

以下是使用Python和Hugging Face Transformers库以及PyTorch构建智能问答模型的步骤: 1. 安装所需的库 在开始之前,请确保已经安装了以下库: - PyTorch - Hugging Face Transformers - numpy - pandas 2. 数据预处理 为了训练我们的模型,我们需要先准备一个数据集。在这个例子中,我们将使用SQuAD2.0数据集,这是一个流行的问答数据集。 SQuAD数据集包含大量的文本,因此我们需要将它们预处理为可以输入模型的格式。具体地说,在构建智能问答模型时,需要将每个数据点分成三个部分: - 输入文本段 - 问题 - 答案 我们可以使用pandas库来读取并处理SQuAD数据集中包含的JSON文件。以下是一个示例代码,它使用pandas将数据加载到进DataFrame中: ```python import pandas as pd import json # Load the data from the JSON file with open('squad.json') as f: data = json.load(f) # Convert the data to a DataFrame df = pd.DataFrame(data) ``` 在这里,我们将SQuAD数据集中的每个问题及其相应的答案转换为一个数据点。对于每个数据点,我们需要将文本及其相应的问题及答案分别存储在不同的变量中: ```python # Initialize empty lists to store the input text, questions and answers texts = [] questions = [] answers = [] # Loop over the rows in the DataFrame and extract the information we need for i, row in df.iterrows(): for qa in row['qas']: # Get the context text text = row['context'] # Get the question text question = qa['question'] # Get the answer text answer = qa['answers'][0]['text'] # Append the input text, question and answer to their respective lists texts.append(text) questions.append(question) answers.append(answer) ``` 3. 构建模型 接下来,我们需要构建我们的智能问答模型。在这个例子中,我们将使用Hugging Face Transformers库中的DistilBERT模型。 我们需要使用transformers库中的AutoTokenizer和AutoModelForQuestionAnswering类分别对输入进行标记化和模型训练。以下是示例代码: ```python from transformers import AutoTokenizer, AutoModelForQuestionAnswering # Load the DistilBERT tokenizer tokenizer = AutoTokenizer.from_pretrained('distilbert-base-uncased') # Load the DistilBERT model model = AutoModelForQuestionAnswering.from_pretrained('distilbert-base-uncased') ``` 4. 训练模型 我们已经准备好训练我们的智能问答模型了。在这个例子中,我们将使用PyTorch库实现训练过程。以下是一个简单的训练循环示例: ```python import torch # Set the device to run the model on device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # Move the model to the device model.to(device) # Set the optimizer and loss function optimizer = torch.optim.Adam(model.parameters(), lr=5e-5) criterion = torch.nn.CrossEntropyLoss() # Set the batch size and number of epochs batch_size = 16 num_epochs = 3 # Loop over the training data for the specified number of epochs for epoch in range(num_epochs): # Loop over the batches in the training data for i in range(0, len(texts), batch_size): # Get a batch of input and target data batch_texts = texts[i:i+batch_size] batch_questions = questions[i:i+batch_size] batch_answers = answers[i:i+batch_size] # Tokenize the input data inputs = tokenizer(batch_texts, batch_questions, padding=True, truncation=True, max_length=512, return_tensors='pt') # Move the input data to the device for key in inputs: inputs[key] = inputs[key].to(device) # Get the start and end tokens for each answer start_tokens = [] end_tokens = [] for j in range(len(batch_answers)): answer_tokens = tokenizer(batch_answers[j], add_special_tokens=False)['input_ids'] context_tokens = inputs['input_ids'][j] start, end = find_answer_tokens(context_tokens, answer_tokens) start_tokens.append(start) end_tokens.append(end) # Convert the start and end tokens to PyTorch tensors start_tokens = torch.tensor(start_tokens).to(device) end_tokens = torch.tensor(end_tokens).to(device) # Zero the gradients optimizer.zero_grad() # Forward pass outputs = model(**inputs) # Calculate the loss start_loss = criterion(outputs.start_logits, start_tokens) end_loss = criterion(outputs.end_logits, end_tokens) loss = start_loss + end_loss # Backward pass loss.backward() # Update the model parameters optimizer.step() # Print the loss every 100 batches if i % 100 == 0: print(f'Epoch {epoch + 1}, Batch {i + 1}/{len(texts)}, Loss {loss.item():.4f}') ``` 5. 预测答案 最后,我们可以使用我们训练好的模型来预测给定的问题的答案。以下是一个示例代码: ```python # Set the example input text and question example_text = 'The Eiffel Tower is a wrought-iron lattice tower on the Champ de Mars in Paris, France. It is named after the engineer Gustave Eiffel, whose company designed and built the tower.' example_question = 'What is the Eiffel Tower named after?' # Tokenize the input text and question inputs = tokenizer(example_text, example_question, padding=True, truncation=True, max_length=512, return_tensors='pt') # Move the input data to the device for key in inputs: inputs[key] = inputs[key].to(device) # Forward pass outputs = model(**inputs) # Get the predicted start and end tokens for the answer start_token = torch.argmax(outputs.start_logits) end_token = torch.argmax(outputs.end_logits) # Decode the start and end tokens to get the answer text answer_ids = inputs['input_ids'][0][start_token:end_token+1] answer_tokens = tokenizer.convert_ids_to_tokens(answer_ids, skip_special_tokens=True) answer_text = tokenizer.convert_tokens_to_string(answer_tokens) ``` 以上是使用Python和Hugging Face Transformers库以及PyTorch构建智能问答模型的步骤。您可以使用自己的数据集和模型参数来训练您自己的模型。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值