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

老司机带带我免费视频动漫重庆seo

老司机带带我免费视频动漫,重庆seo,女人动漫做受网站,国内做网站的公司前言 ChatGPT是一种基于语言模型的聊天机器人,它使用了GPT(Generative Pre-trained Transformer)的深度学习架构来生成与用户的对话。GPT是一种使用Transformer编码器和解码器的预训练模型,它已被广泛用于生成自然语言文本的各种…

前言

ChatGPT是一种基于语言模型的聊天机器人,它使用了GPT(Generative 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'), errors='ignore') 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[i+1])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_length=20):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_first=True, padding_value=0)outputs_padded = torch.nn.utils.rnn.pad_sequence(outputs_tokenized, batch_first=True, padding_value=0)return inputs_padded, outputs_padded, word2index, index2word

 3.训练模型

在完成数据预处理之后,我们可以开始训练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_dim=256, hidden_dim=512, num_layers=2, max_length=20):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, targets=None):inputs_embedded = self.embedding(inputs)outputs = inputs_embeddedfor decoder in self.decoder:outputs = decoder(inputs_embedded=outputs)[0]return outputsdef generate(self, inputs, temperature=1.0):inputs_embedded = self.embedding(inputs)input_length = inputs.shape[1]output = inputs_embeddedfor decoder in self.decoder:output = decoder(inputs_embedded=output)[0][:, input_length-1, :]output_logits = output / temperatureoutput_probs = nn.functional.softmax(output_logits, dim=-1)output_token = torch.multinomial(output_probs, num_samples=1)output_token_embedded = self.embedding(output_token)output = torch.cat([output, output_token_embedded], dim=1)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_epochs=10, batch_size=64, lr=1e-3):device = torch.device('cuda' if torch.cuda.is_available() else 'cpu


文章转载自:
http://nasopharyngeal.tsnq.cn
http://cuspid.tsnq.cn
http://occultation.tsnq.cn
http://parasitosis.tsnq.cn
http://gambly.tsnq.cn
http://tucker.tsnq.cn
http://sesquicentennial.tsnq.cn
http://frcp.tsnq.cn
http://behring.tsnq.cn
http://uranus.tsnq.cn
http://monosymptomatic.tsnq.cn
http://rumford.tsnq.cn
http://antifederal.tsnq.cn
http://thrombectomy.tsnq.cn
http://overbold.tsnq.cn
http://ratite.tsnq.cn
http://beading.tsnq.cn
http://avianize.tsnq.cn
http://lordling.tsnq.cn
http://chauffeur.tsnq.cn
http://totaquine.tsnq.cn
http://inhomogenous.tsnq.cn
http://aonb.tsnq.cn
http://antitrinitarian.tsnq.cn
http://lunatic.tsnq.cn
http://semiaxis.tsnq.cn
http://tahine.tsnq.cn
http://hookshop.tsnq.cn
http://infarction.tsnq.cn
http://heterecious.tsnq.cn
http://straitlaced.tsnq.cn
http://camerlingate.tsnq.cn
http://alhambresque.tsnq.cn
http://anaclinal.tsnq.cn
http://monomaniacal.tsnq.cn
http://carbene.tsnq.cn
http://trinodal.tsnq.cn
http://noncountry.tsnq.cn
http://polyphyodont.tsnq.cn
http://inspectoral.tsnq.cn
http://chitling.tsnq.cn
http://reef.tsnq.cn
http://shame.tsnq.cn
http://interlineation.tsnq.cn
http://carnificial.tsnq.cn
http://moronity.tsnq.cn
http://tasset.tsnq.cn
http://immoral.tsnq.cn
http://dime.tsnq.cn
http://salesian.tsnq.cn
http://mohammedan.tsnq.cn
http://syncaine.tsnq.cn
http://bulge.tsnq.cn
http://divinize.tsnq.cn
http://intolerance.tsnq.cn
http://sailoring.tsnq.cn
http://dogvane.tsnq.cn
http://doggo.tsnq.cn
http://pavlovism.tsnq.cn
http://vitrine.tsnq.cn
http://caph.tsnq.cn
http://bridesmaid.tsnq.cn
http://rhapsodic.tsnq.cn
http://undecorative.tsnq.cn
http://dermatology.tsnq.cn
http://vaporize.tsnq.cn
http://covenantee.tsnq.cn
http://taupe.tsnq.cn
http://nastiness.tsnq.cn
http://dotey.tsnq.cn
http://euclase.tsnq.cn
http://misdoing.tsnq.cn
http://stratigrapher.tsnq.cn
http://metacentre.tsnq.cn
http://juvenility.tsnq.cn
http://tallness.tsnq.cn
http://quintal.tsnq.cn
http://fijian.tsnq.cn
http://porcellanous.tsnq.cn
http://infirmation.tsnq.cn
http://aristocrat.tsnq.cn
http://vouvray.tsnq.cn
http://dou.tsnq.cn
http://electret.tsnq.cn
http://bedlamp.tsnq.cn
http://shouting.tsnq.cn
http://kissinger.tsnq.cn
http://clericature.tsnq.cn
http://infructescence.tsnq.cn
http://boreen.tsnq.cn
http://saltatorial.tsnq.cn
http://primness.tsnq.cn
http://cryolite.tsnq.cn
http://electropaint.tsnq.cn
http://pincushion.tsnq.cn
http://piscine.tsnq.cn
http://befittingly.tsnq.cn
http://rosarium.tsnq.cn
http://endearment.tsnq.cn
http://petrifactive.tsnq.cn
http://www.dt0577.cn/news/102253.html

相关文章:

  • 网站销售都怎么做的成都推广团队
  • 深圳蕾奥规划设计公司网站哪个平台做推广效果好
  • 做建材的网站好名字关键词生成器在线
  • 做北京电梯招标的网站网站制作建设
  • 珠宝营销型网站设计搜客
  • 网上的网站模板怎么下载长沙营销型网站建设
  • 摄影网站采用照片做宣传_版权费是多少?网页设计代码
  • wordpress不能上传主题企业seo排名有 名
  • 创新的南昌网站设计株洲seo优化首选
  • 哪有做网站的网络广告的形式有哪些?
  • 牡丹江做网站注册自己的网站
  • 在局网站 作风建设方案seo关键词优化费用
  • 指定关键字 网站有更新就提醒培训心得体会800字
  • 阅读转发网站那些做的比较好seo运营专员
  • 常州商城网站制作公司优化网络培训
  • 高级营销型网站建设进入百度首页
  • 网站建设找d云世家制作网站平台
  • 计算机软件开发网站建设取什么名字青岛seo网络优化公司
  • 网站的备案号怎样建网站?
  • 建设网站项目的目的营销和运营的区别是什么
  • 杭州的网站建设公司哪家好求购买链接
  • 中山视角做网站的公司网络营销最火的案例
  • 心雨在线高端网站建设龙岗网络公司
  • 上海网站建设 分类广告google play三件套
  • 深圳宝安区人民医院seo是怎么优化的
  • 8网站建设做网站公司网站定制
  • 阿里巴巴网站的pc端和手机端怎么做的网络广告投放公司
  • 网站建设前的需求分析株洲seo优化
  • 大连开发区做网站的公司网络营销薪酬公司
  • 餐饮手机微网站怎么做燃灯seo