当前位置: 首页 > news >正文

在线搭建网站seo快速排名培训

在线搭建网站,seo快速排名培训,苏州论坛型网站建设,网上做网站网站代理赚钱吗前言 ChatGPT是一种基于语言模型的聊天机器人#xff0c;它使用了GPT#xff08;Generative Pre-trained Transformer#xff09;的深度学习架构来生成与用户的对话。GPT是一种使用Transformer编码器和解码器的预训练模型#xff0c;它已被广泛用于生成自然语言文本的各种…前言 ChatGPT是一种基于语言模型的聊天机器人它使用了GPTGenerative Pre-trained Transformer的深度学习架构来生成与用户的对话。GPT是一种使用Transformer编码器和解码器的预训练模型它已被广泛用于生成自然语言文本的各种应用程序例如文本生成机器翻译和语言理解。 在本文中我们将探讨如何使用Python和PyTorch来训练ChatGPT以及如何使用已经训练的模型来生成对话。 1.准备数据 在训练ChatGPT之前我们需要准备一个大型的对话数据集。这个数据集应该包含足够的对话覆盖各种主题和领域以及各种不同的对话风格。这个数据集可以是从多个来源收集的例如电影脚本电视节目社交媒体上的聊天记录等。 在本文中我们将使用Cornell Movie Dialogs Corpus一个包含电影对话的大型数据集。这个数据集包含超过22,000个对话涵盖了多个主题和风格。 我们可以使用以下代码下载和解压缩Cornell Movie Dialogs Corpus这个数据集也可以从[这里](https://www.cs.cornell.edu/~cristian/Cornell_Movie-Dialogs_Corpus.html)手动下载。 import os import urllib.request import zipfileDATA_URL http://www.cs.cornell.edu/~cristian/data/cornell_movie_dialogs_corpus.zip DATA_DIR ./cornell_movie_dialogs_corpus DATA_FILE os.path.join(DATA_DIR, cornell_movie_dialogs_corpus.zip)if not os.path.exists(DATA_DIR):os.makedirs(DATA_DIR)if not os.path.exists(DATA_FILE):print(Downloading data...)urllib.request.urlretrieve(DATA_URL, DATA_FILE)print(Extracting data...) with zipfile.ZipFile(DATA_FILE, r) as zip_ref:zip_ref.extractall(DATA_DIR) 2.数据预处理 在准备好数据集之后我们需要对数据进行预处理以便将其转换为模型可以处理的格式。在本教程中我们使用了一个简单的预处理步骤该步骤包括下列几步 将数据拆分成句子pairs上下文回答去除标点符号和特殊字符将所有的单词转换成小写将单词映射到一个整数ID将句子填充到相同的长度 下面是用于预处理数据的代码 import re import random import numpy as np import torchdef load_conversations():id2line {}with open(os.path.join(DATA_DIR, movie_lines.txt), errorsignore) as f:for line in f:parts line.strip().split( $ )id2line[parts[0]] parts[4]inputs []outputs []with open(os.path.join(DATA_DIR, movie_conversations.txt), r) as f:for line in f:parts line.strip().split( $ )conversation [id2line[id] for id in parts[3][1:-1].split(,)]for i in range(len(conversation) - 1):inputs.append(conversation[i])outputs.append(conversation[i1])return inputs, outputsdef preprocess_sentence(sentence):sentence re.sub(r([?.!,]), r \1 , sentence)sentence re.sub(r[^a-zA-Z?.!,], r , sentence)sentence sentence.lower()return sentencedef tokenize_sentence(sentence, word2index):tokenized []for word in sentence.split( ):if word not in word2index:continuetokenized.append(word2index[word])return tokenizeddef preprocess_data(inputs, outputs, max_length20):pairs []for i in range(len(inputs)):input_sentence preprocess_sentence(inputs[i])output_sentence preprocess_sentence(outputs[i])pairs.append((input_sentence, output_sentence))word_counts {}for pair in pairs:for sentence in pair:for word in sentence.split( ):if word not in word_counts:word_counts[word] 0word_counts[word] 1word2index {}index2word {0: pad, 1: start, 2: end, 3: unk}index 4for word, count in word_counts.items():if count 10:word2index[word] indexindex2word[index] wordindex 1inputs_tokenized []outputs_tokenized []for pair in pairs:input_sentence, output_sentence pairinput_tokenized [1] tokenize_sentence(input_sentence, word2index) [2]output_tokenized [1] tokenize_sentence(output_sentence, word2index) [2]if len(input_tokenized) max_length and len(output_tokenized) max_length:inputs_tokenized.append(input_tokenized)outputs_tokenized.append(output_tokenized)inputs_padded torch.nn.utils.rnn.pad_sequence(inputs_tokenized, batch_firstTrue, padding_value0)outputs_padded torch.nn.utils.rnn.pad_sequence(outputs_tokenized, batch_firstTrue, padding_value0)return inputs_padded, outputs_padded, word2index, index2word3.训练模型 在完成数据预处理之后我们可以开始训练ChatGPT模型。对于本文中的示例我们将使用PyTorch深度学习框架来实现ChatGPT模型。 首先我们需要定义一个Encoder-Decoder模型结构。这个结构包括一个GPT解码器它将输入的上下文句子转换为一个回答句子。GPT解码器由多个Transformer解码器堆叠而成每个解码器都包括多头注意力和前馈神经网络层。 import torch.nn as nn from transformers import GPT2LMHeadModelclass EncoderDecoder(nn.Module):def __init__(self, num_tokens, embedding_dim256, hidden_dim512, num_layers2, max_length20):super().__init__()self.embedding nn.Embedding(num_tokens, embedding_dim)self.decoder nn.ModuleList([GPT2LMHeadModel.from_pretrained(gpt2) for _ in range(num_layers)])self.max_length max_lengthdef forward(self, inputs, targetsNone):inputs_embedded self.embedding(inputs)outputs inputs_embeddedfor decoder in self.decoder:outputs decoder(inputs_embeddedoutputs)[0]return outputsdef generate(self, inputs, temperature1.0):inputs_embedded self.embedding(inputs)input_length inputs.shape[1]output inputs_embeddedfor decoder in self.decoder:output decoder(inputs_embeddedoutput)[0][:, input_length-1, :]output_logits output / temperatureoutput_probs nn.functional.softmax(output_logits, dim-1)output_token torch.multinomial(output_probs, num_samples1)output_token_embedded self.embedding(output_token)output torch.cat([output, output_token_embedded], dim1)return output[:, input_length:, :] 然后我们需要定义一个训练函数该函数将使用梯度下降方法优化模型参数并将每个epoch的损失和正确率记录到一个日志文件中。 def train(model, inputs, targets, optimizer, criterion):model.train()optimizer.zero_grad()outputs model(inputs, targets[:, :-1])loss criterion(outputs.reshape(-1, outputs.shape[-1]), targets[:, 1:].reshape(-1))loss.backward()optimizer.step()return loss.item()def evaluate(model, inputs, targets, criterion):model.eval()with torch.no_grad():outputs model(inputs, targets[:, :-1])loss criterion(outputs.reshape(-1, outputs.shape[-1]), targets[:, 1:].reshape(-1))return loss.item()def train_model(model, inputs, targets, word2index, index2word, num_epochs10, batch_size64, lr1e-3):device torch.device(cuda if torch.cuda.is_available() else cpu
http://www.w-s-a.com/news/912077/

相关文章:

  • 江门站排名优化建立什么网站赚钱
  • 科普文章在那个网站做招聘网站代做
  • 监控设备东莞网站建设游戏网站域名
  • 对商家而言网站建设的好处网址导航怎么彻底删除
  • app设计网站模板企业展厅策划设计公司有哪些
  • wordpress销售主题手机网站关键词优化
  • 怎么查一个网站是什么程序做的三亚城乡建设局网站
  • 深圳分销网站设计公司做网站一般需要多久
  • 企业网站设计代码丹东seo排名公司
  • 企业网站建设定制开发服务网站建设说课ppt
  • 大连市城乡建设局网站网站免费网站入口
  • 做暧网站网站备案ps
  • 知名网站建设公司电话长子网站建设
  • 网站建设的意义与目的建立什么船籍港
  • 广州注册公司营业执照网站建设代码优化
  • 百度网站官网马克互联网主题 wordpress
  • 网站制作 客户刁难深圳自助建站
  • 怎么去推广一个网站广东餐饮品牌设计
  • 网站代码加密了怎么做兰州最新大事
  • 现在ui做的比较好的网站去年做啥网站致富
  • 广东网站建设咨询电话好牌子网
  • 公司怎样制作网站南阳网站关键词
  • 营销型网站建设与网盟完整php网站开发
  • 网站做微信链接怎么做的石桥铺网站建设公司
  • 济南mip网站建设公司做图书馆网站模板
  • app 门户网站网站项目框架
  • 做网站视频网站备案 新闻审批号
  • 织梦网站怎么居中视频网站开发与制作
  • 网站上海备案佛山网站seo哪家好
  • 品牌形象网站有哪些珠海市区工商年报在哪个网站做