php网站制作费用,博物馆建设网站的目的及功能,dell公司网站设计特色,网页设计与制作项目设计思路文章目录 前言一、数据加工二、模型搭建三、模型训练1、构建模型2、优化器与损失函数定义3、模型训练 四、模型推理五、所有Demo源码 前言
对话模型是一种人工智能技术#xff0c;旨在使计算机能够像人类一样进行对话和交流。这种模型通常基于深度学习和自然语言处理技术旨在使计算机能够像人类一样进行对话和交流。这种模型通常基于深度学习和自然语言处理技术能够理解自然语言并做出相应的回应。然而现有博客很少介绍对话模型内容也很少用一个简单代码带领大家理解其原理。因此我创建一个简单的对话模型在不适用Hugging Face或LSTM结构旨在使用一个简单的全连接神经网络来实现这个模型且代码基于PyTorch框架搭建意在帮助读者构建对话模型知识。当然模型仅是一个简单模型旨在帮助理解原理不具备很好效果能力。 一、数据加工
文本数据最终都是转为对应字典索引代表其文本内容输入模型加工实现nlp任务对话模型也不列外。因此我们需要构建一个字典映射(可参考点击这里)与文本数据并按照字典映射转换为对应索引id其代码如下
# 定义一个简单的对话数据集
data [(hi, hello),(how are you?, Im fine, thank you.),(whats your name?, Im a chatbot.)
]# 构建词汇表
vocab list(set( .join([x[0] x[1] for x in data])))
vocab.append(SOS)
vocab.append(EOS)word_to_idx {word: i for i, word in enumerate(vocab)}
idx_to_word {i: word for i, word in enumerate(vocab)}# 将对话数据集转换为索引序列
def to_idx_seq(sentence):return [word_to_idx[word] for word in sentence]data_x [to_idx_seq(x[0]) for x in data]
data_y [to_idx_seq(x[1]) for x in data]data_y [[word_to_idx[SOS]]list(x)[word_to_idx[EOS]] for x in data_y]
其字典内容如下
二、模型搭建
这里也是最重要内容如何搭建对话模型我是使用transformer结构搭建(之前模型使用LSTM模型搭建)创建一个简单的对话生成模型也使用一个基于全连接层的神经网络来实现这个模型其代码如下 # 定义一个简单的Transformer生成式对话模型
class ChatbotTransformer(nn.Module):def __init__(self, input_dim, output_dim, nhead, num_encoder_layers, num_decoder_layers):super(ChatbotTransformer, self).__init__()self.input_dim input_dimself.output_dim output_dimself.embedding nn.Embedding(len(vocab), input_dim)self.transformer nn.Transformer(d_modelinput_dim, nheadnhead, num_encoder_layersnum_encoder_layers, num_decoder_layersnum_decoder_layers)self.fc nn.Linear(input_dim, output_dim)def forward(self, src, tgt):src self.embedding(src).permute(1, 0, 2) # 调整输入张量维度tgt self.embedding(tgt).permute(1, 0, 2) # 调整输入张量维度output self.transformer(src, tgt)output self.fc(output)return output
从代码上看我们需要输入src为前面提问数据而答案生成输入是每个tgt字输入按照顺序输出预测。
三、模型训练
1、构建模型
我大概试了一下使用更多层对于简单数据反而效果不佳我的数据又比较简单我构建了较少的层来预测模型。其模型构建代码如下
# 创建模型实例
# model ChatbotTransformer(input_dim256, output_dimlen(vocab), nhead8, num_encoder_layers6, num_decoder_layers6)
model ChatbotTransformer(input_dim16, output_dimlen(vocab), nhead8, num_encoder_layers1, num_decoder_layers1)2、优化器与损失函数定义
优化器定义我将不考虑介绍只说下文本预测是交叉熵方式实际文本基本都采用该方法作为loss计算。其代码如下
# 定义损失函数和优化器
criterion nn.CrossEntropyLoss()
optimizer optim.Adam(model.parameters(), lr0.01)3、模型训练
接下来我们解读如何训练对话模型我们获得对应输入数据与生成预测数据我们开始训练模型其代码如下
# 模型训练
epochs 800
for epoch in range(epochs):total_loss 0for i in range(len(data_x)):optimizer.zero_grad()input_seq torch.tensor(data_x[i])target_seq torch.tensor(data_y[i])for j in range(len(target_seq)-1):if random.random() 0.5:j random.randint(0, len(target_seq)-2)output model(input_seq.unsqueeze(0), target_seq[:j1].unsqueeze(0)) # 使用目标序列的前n-1个词预测后n-1个词loss criterion(output.view(-1, len(vocab)), target_seq[1:j2].view(-1)) # 计算损失需要将输出形状转换成二维loss.backward()optimizer.step()total_loss loss.item()if (epoch1) % 10 0:print(Epoch [{}/{}], Loss: {:.4f}.format(epoch1, epochs, total_loss / len(data_x)))
假设input_seq tensor([17, 6, 0, 15, 1, 8, 9, 15, 7, 6, 11, 4])target_seqtensor([20, 12, 18, 13, 15, 5, 16, 10, 9, 2, 15, 3, 17, 1, 10, 19, 15, 7, 6, 11, 14, 21])vocab为字典映射共22个映射。我将试图模型连续2轮解释一下训练时候相关变化。 第二轮输出结果 第三轮输出结果 后面以此类推迭代。
很明显提问每次都是全部输入而输出则是第一个20开始与输入共同进模型分别是模型src与tgt不断重复与预测完成训练。而loss计算都是往后取一个target文本也发现并不会计算20索引文本。
四、模型推理
最后让我们使用训练好的模型进行推理实际和上面训练讲到方法类似我们开始文本开始不断给出生成对应文本也就是对话内容。
# 进行推理
def generate_response(input_sentence):model.eval()input_seq torch.tensor(to_idx_seq(input_sentence))target_seq torch.tensor([word_to_idx[SOS]]) # 在开始时使用特殊的起始标记with torch.no_grad():for i in range(20): # 限制生成的句子长度为20个词output model(input_seq.unsqueeze(0), target_seq.unsqueeze(0))output_token output.argmax(2)[-1].item()print(idx_to_word[output_token], end )target_seq torch.cat((target_seq, torch.tensor([output_token])), dim0)res [idx_to_word[int(k)] for k in target_seq]print(res[1:-1])return res[1:-1]# 进行对话生成
generate_response(hi)
其结果如下 五、所有Demo源码
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
import random
# 定义一个简单的对话数据集
data [# (hi, hello),(how are you?, Im fine, thank you.),# (whats your name?, Im a chatbot.)
]# 构建词汇表
vocab list(set( .join([x[0] x[1] for x in data])))
vocab.append(SOS)
vocab.append(EOS)word_to_idx {word: i for i, word in enumerate(vocab)}
idx_to_word {i: word for i, word in enumerate(vocab)}# 将对话数据集转换为索引序列
def to_idx_seq(sentence):return [word_to_idx[word] for word in sentence]data_x [to_idx_seq(x[0]) for x in data]
data_y [to_idx_seq(x[1]) for x in data]data_y [[word_to_idx[SOS]]list(x)[word_to_idx[EOS]] for x in data_y]# 定义一个简单的Transformer生成式对话模型
class ChatbotTransformer(nn.Module):def __init__(self, input_dim, output_dim, nhead, num_encoder_layers, num_decoder_layers):super(ChatbotTransformer, self).__init__()self.input_dim input_dimself.output_dim output_dimself.embedding nn.Embedding(len(vocab), input_dim)self.transformer nn.Transformer(d_modelinput_dim, nheadnhead, num_encoder_layersnum_encoder_layers, num_decoder_layersnum_decoder_layers)self.fc nn.Linear(input_dim, output_dim)def forward(self, src, tgt):src self.embedding(src).permute(1, 0, 2) # 调整输入张量维度tgt self.embedding(tgt).permute(1, 0, 2) # 调整输入张量维度output self.transformer(src, tgt)output self.fc(output)return output# 创建模型实例
# model ChatbotTransformer(input_dim256, output_dimlen(vocab), nhead8, num_encoder_layers6, num_decoder_layers6)
model ChatbotTransformer(input_dim16, output_dimlen(vocab), nhead8, num_encoder_layers1, num_decoder_layers1)# 定义损失函数和优化器
criterion nn.CrossEntropyLoss()
optimizer optim.Adam(model.parameters(), lr0.01)# 模型训练
epochs 800
for epoch in range(epochs):total_loss 0for i in range(len(data_x)):optimizer.zero_grad()input_seq torch.tensor(data_x[i])target_seq torch.tensor(data_y[i])for j in range(len(target_seq)-1):if random.random() 0.5:j random.randint(0, len(target_seq)-2)output model(input_seq.unsqueeze(0), target_seq[:j1].unsqueeze(0)) # 使用目标序列的前n-1个词预测后n-1个词loss criterion(output.view(-1, len(vocab)), target_seq[1:j2].view(-1)) # 计算损失需要将输出形状转换成二维loss.backward()optimizer.step()total_loss loss.item()if (epoch1) % 10 0:print(Epoch [{}/{}], Loss: {:.4f}.format(epoch1, epochs, total_loss / len(data_x)))# 进行推理
def generate_response(input_sentence):model.eval()input_seq torch.tensor(to_idx_seq(input_sentence))target_seq torch.tensor([word_to_idx[SOS]]) # 在开始时使用特殊的起始标记with torch.no_grad():for i in range(20): # 限制生成的句子长度为20个词output model(input_seq.unsqueeze(0), target_seq.unsqueeze(0))output_token output.argmax(2)[-1].item()print(idx_to_word[output_token], end )target_seq torch.cat((target_seq, torch.tensor([output_token])), dim0)res [idx_to_word[int(k)] for k in target_seq]print(res[1:-1])return res[1:-1]# 进行对话生成
generate_response(how are you?) 文章转载自: http://www.morning.lwgsk.cn.gov.cn.lwgsk.cn http://www.morning.ityi666.cn.gov.cn.ityi666.cn http://www.morning.lyjwb.cn.gov.cn.lyjwb.cn http://www.morning.hxwrs.cn.gov.cn.hxwrs.cn http://www.morning.nwljj.cn.gov.cn.nwljj.cn http://www.morning.drqrl.cn.gov.cn.drqrl.cn http://www.morning.kqkmx.cn.gov.cn.kqkmx.cn http://www.morning.rfrxt.cn.gov.cn.rfrxt.cn http://www.morning.svrud.cn.gov.cn.svrud.cn http://www.morning.skdhm.cn.gov.cn.skdhm.cn http://www.morning.lnnc.cn.gov.cn.lnnc.cn http://www.morning.mqxrx.cn.gov.cn.mqxrx.cn http://www.morning.rknhd.cn.gov.cn.rknhd.cn http://www.morning.rkwlg.cn.gov.cn.rkwlg.cn http://www.morning.qgjxt.cn.gov.cn.qgjxt.cn http://www.morning.brqjs.cn.gov.cn.brqjs.cn http://www.morning.pndhh.cn.gov.cn.pndhh.cn http://www.morning.dxxnq.cn.gov.cn.dxxnq.cn http://www.morning.jqhrk.cn.gov.cn.jqhrk.cn http://www.morning.dydqh.cn.gov.cn.dydqh.cn http://www.morning.gnkdp.cn.gov.cn.gnkdp.cn http://www.morning.ybmp.cn.gov.cn.ybmp.cn http://www.morning.hwlmy.cn.gov.cn.hwlmy.cn http://www.morning.kgsws.cn.gov.cn.kgsws.cn http://www.morning.jzykw.cn.gov.cn.jzykw.cn http://www.morning.piekr.com.gov.cn.piekr.com http://www.morning.xprzq.cn.gov.cn.xprzq.cn http://www.morning.dfbeer.com.gov.cn.dfbeer.com http://www.morning.thzgd.cn.gov.cn.thzgd.cn http://www.morning.ymjrg.cn.gov.cn.ymjrg.cn http://www.morning.frtb.cn.gov.cn.frtb.cn http://www.morning.zkqsc.cn.gov.cn.zkqsc.cn http://www.morning.csgwd.cn.gov.cn.csgwd.cn http://www.morning.dkgtr.cn.gov.cn.dkgtr.cn http://www.morning.nynlf.cn.gov.cn.nynlf.cn http://www.morning.ssxlt.cn.gov.cn.ssxlt.cn http://www.morning.osshjj.cn.gov.cn.osshjj.cn http://www.morning.knmp.cn.gov.cn.knmp.cn http://www.morning.lxbml.cn.gov.cn.lxbml.cn http://www.morning.nnwpz.cn.gov.cn.nnwpz.cn http://www.morning.jfbrt.cn.gov.cn.jfbrt.cn http://www.morning.wrcgy.cn.gov.cn.wrcgy.cn http://www.morning.nyqm.cn.gov.cn.nyqm.cn http://www.morning.gjlst.cn.gov.cn.gjlst.cn http://www.morning.wkmpx.cn.gov.cn.wkmpx.cn http://www.morning.splkk.cn.gov.cn.splkk.cn http://www.morning.dyght.cn.gov.cn.dyght.cn http://www.morning.gkmwk.cn.gov.cn.gkmwk.cn http://www.morning.mbpfk.cn.gov.cn.mbpfk.cn http://www.morning.rszt.cn.gov.cn.rszt.cn http://www.morning.fwcjy.cn.gov.cn.fwcjy.cn http://www.morning.fkmyq.cn.gov.cn.fkmyq.cn http://www.morning.ymwny.cn.gov.cn.ymwny.cn http://www.morning.nfbxgtj.com.gov.cn.nfbxgtj.com http://www.morning.lpcct.cn.gov.cn.lpcct.cn http://www.morning.rzmlc.cn.gov.cn.rzmlc.cn http://www.morning.nhrkc.cn.gov.cn.nhrkc.cn http://www.morning.rnxw.cn.gov.cn.rnxw.cn http://www.morning.tbkqs.cn.gov.cn.tbkqs.cn http://www.morning.qxjck.cn.gov.cn.qxjck.cn http://www.morning.fhlfp.cn.gov.cn.fhlfp.cn http://www.morning.dzpnl.cn.gov.cn.dzpnl.cn http://www.morning.wtcyz.cn.gov.cn.wtcyz.cn http://www.morning.jtmrx.cn.gov.cn.jtmrx.cn http://www.morning.wdpt.cn.gov.cn.wdpt.cn http://www.morning.mbmtn.cn.gov.cn.mbmtn.cn http://www.morning.csnmd.cn.gov.cn.csnmd.cn http://www.morning.gqryh.cn.gov.cn.gqryh.cn http://www.morning.fchkc.cn.gov.cn.fchkc.cn http://www.morning.tqhpt.cn.gov.cn.tqhpt.cn http://www.morning.dzgmj.cn.gov.cn.dzgmj.cn http://www.morning.mpscg.cn.gov.cn.mpscg.cn http://www.morning.tzrmp.cn.gov.cn.tzrmp.cn http://www.morning.llcsd.cn.gov.cn.llcsd.cn http://www.morning.hwlmy.cn.gov.cn.hwlmy.cn http://www.morning.rbyz.cn.gov.cn.rbyz.cn http://www.morning.rdqzl.cn.gov.cn.rdqzl.cn http://www.morning.rzjfn.cn.gov.cn.rzjfn.cn http://www.morning.rtkz.cn.gov.cn.rtkz.cn http://www.morning.yfqhc.cn.gov.cn.yfqhc.cn