nlp深度学习代码总结--pytoch

2024-03-05 01:18

本文主要是介绍nlp深度学习代码总结--pytoch,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

代码总结

文本清洗

去除网址

def remove_URL(text):url = re.compile(r'https?://\S+|www\.\S+')return url.sub(r'', text)

去除表情符号

def remove_emoji(text):emoji_pattern = re.compile('['u'\U0001F600-\U0001F64F'  # emoticonsu'\U0001F300-\U0001F5FF'  # symbols & pictographsu'\U0001F680-\U0001F6FF'  # transport & map symbolsu'\U0001F1E0-\U0001F1FF'  # flags (iOS)u'\U00002702-\U000027B0'u'\U000024C2-\U0001F251'']+',flags=re.UNICODE)return emoji_pattern.sub(r'', text)

去掉网页标签

def remove_html(text):html = re.compile(r'<.*?>|&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-f]{1,6});')return re.sub(html, '', text)

去掉标点符号

def remove_punct(text):#所有的标点字符table = str.maketrans('', '', string.punctuation)return text.translate(table)def remove_punct(s):s = re.sub(r"([.!?])", r" \1", s)s = re.sub(r"[^a-zA-Z.!?]+", r" ", s)s = re.sub(r"\s+", r" ", s).strip()return s

字符编码转换

def unicodeToAscii(s):return ''.join(c for c in unicodedata.normalize('NFD', s)if unicodedata.category(c) != 'Mn')

去除低频单词

去除停用词

from nltk.corpus import stopwordsdef remove_stopword(x):return [y for y in x if y not in stopwords.words('english')]
train['temp_list'] = train['temp_list'].apply(lambda x:remove_stopword(x))

文本处理

def clean_text(text):'''Make text lowercase, remove text in square brackets,remove links,remove punctuationand remove words containing numbers.'''text = str(text).lower()text = re.sub('\[.*?\]', '', text)text = re.sub('https?://\S+|www\.\S+', '', text)text = re.sub('<.*?>+', '', text)text = re.sub('[%s]' % re.escape(string.punctuation), '', text)text = re.sub('\n', '', text)text = re.sub('\w*\d\w*', '', text)return texttrain['text'] = train['text'].apply(lambda x:clean_text(x))
nltk
#语料库和词典
from nltk.corpus import stopwords, wordnet
#分词
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import word_tokenize
#频率分布和平滑概率
from nltk.probability import FreqDist

数据分析及可视化

分析数据
#可以看到训练数据的数目以及不同值的数目
train.describe()#统计某变量不同值的种类
temp = train.groupby('sentiment').count()['text'].reset_index().sort_values(by='text',ascending=False)
#也可直接使用sns可视化
sns.countplot(x='sentiment',data=train)#迭代pandas读取的数据
for ind,row in train.iterrows()#创建dataframe观察数据
temp = pd.DataFrame(top.most_common(20))
temp.columns = ['Common_words','count']
temp.style.background_gradient(cmap='Blues')
数据集词频统计
from collections import Counterc = Counter()
#默认按出现顺序输入字典元素
most = counter.most_common()fig = px.bar(temp, x="count", y="Common_words", title='Commmon Words in Selected Text', orientation='h', width=700, height=700,color='Common_words')
两变量之间的关系
iris.plot(kind="scatter", x="SepalLengthCm", y="SepalWidthCm")sns.jointplot(x="SepalLengthCm", y="SepalWidthCm", data=iris, size=5)sns.boxplot(x="Species", y="PetalLengthCm", data=iris)
两对变量之间的关系
sns.pairplot(iris.drop("Id", axis=1), hue="Species", size=3)

处理输入数据

去除空白值
train.dropna(inplace=True)
划分数据集
from torch.utils.data import TensorDataset, random_splittrain_dataset, val_dataset = random_split(dataset, [train_size, val_size])
分词转换

bert

tokenizer = BertTokenizer.from_pretrained('bert-large-uncased', do_lower_case=True)#适配分词器
tokenizer.tokenize(combined[0])
#转换为id,不包含csl,sep等
tokenizer.convert_tokens_to_ids(tokenizer.tokenize(combined[0]))
#编码
tokenizer.encode(combined[0],max_length = 512)encoded_dict = tokenizer.encode_plus(
text,                      # Sentence to encode.
add_special_tokens = True, # Add '[CLS]' and '[SEP]'
truncation='longest_first', # Activate and control truncation
max_length = 84,           # Max length according to our text data.
pad_to_max_length = True, # Pad & truncate all sentences.
return_attention_mask = True,   # Construct attn. masks.
return_tensors = 'pt',     # Return pytorch tensors.
)
input_ids.append(encoded_dict['input_ids'])
attention_masks.append(encoded_dict['attention_mask'])

手动创建tokenizer

#填充
def pad_and_truncate(sequence, maxlen, dtype='int64', padding='post', truncating='post', value=0):x = (np.ones(maxlen) * value).astype(dtype)if truncating == 'pre':trunc = sequence[-maxlen:]else:trunc = sequence[:maxlen]trunc = np.asarray(trunc, dtype=dtype)if padding == 'post':x[:len(trunc)] = truncelse:x[-len(trunc):] = truncreturn xclass Tokenizer(object):def __init__(self, max_seq_len, lower=True):self.lower = lowerself.max_seq_len = max_seq_lenself.word2idx = {}self.idx2word = {}self.idx = 1def fit_on_text(self, text):if self.lower:text = text.lower()words = text.split()for word in words:if word not in self.word2idx:self.word2idx[word] = self.idxself.idx2word[self.idx] = wordself.idx += 1def text_to_sequence(self, text, reverse=False, padding='post', truncating='post'):if self.lower:text = text.lower()words = text.split()unknownidx = len(self.word2idx)+1sequence = [self.word2idx[w] if w in self.word2idx else unknownidx for w in words]if len(sequence) == 0:sequence = [0]if reverse:sequence = sequence[::-1]return pad_and_truncate(sequence, self.max_seq_len, padding=padding, truncating=truncating)
#使用分词器在对应文本上  
tokenizer.fit_on_text(text)
#保存分词器
pickle.dump(tokenizer, open(dat_fname, 'wb'))
#使用分词器
tokenizer = pickle.load(open(dat_fname, 'rb'))
转换为向量矩阵
embedding_matrix = np.zeros((len(word2idx) + 2, embed_dim))#使用glove
fname = './glove.twitter.27B/glove.twitter.27B.' + str(embed_dim) + 'd.txt' \ if embed_dim != 300 else './glove.42B.300d.txt' word_vec = _load_word_vec(fname, word2idx=word2idx, embed_dim=embed_dim)for word, i in word2idx.items():vec = word_vec.get(word)if vec is not None:
# words not found in embedding index will be all-zeros.embedding_matrix[i] = vecpickle.dump(embedding_matrix, open(dat_fname, 'wb'))
打包数据
for x in train:temp_ids = tokenizer.encode(x, add_special_tokens=True)max_len = max(max_len, len(temp_ids))input_ids.append(temp_ids)
#转换得到imput_ids和attention_masks
input_ids = np.array([i + [0]*(max_len-len(i)) for i in input_ids])
attention_masks = np.where(input_ids != 0, 1, 0)dataset = TensorDataset(input_ids, attention_masks, labels)
封装数据

自定义的Dataset需要继承它并且实现两个成员方法:
getitem() 该方法定义用索引(0 到 len(self))获取一条数据或一个样本
len()该方法返回数据集的总长度

from torch.utils.data import Dataset,DataLoader
class MRPCDataset(Dataset):def __init__(self, dataset):self.data = datasetdef __getitem__(self, index):#这里可以有很多操作return self.data[index][0], self.data[index][1], self.data[index][2]def __len__(self):return len(self.data)#实例化 并送入DataLoader
train_dataset = MRPCDataset(train_dataset)
train_loader = DataLoader(dataset=train_dataset, batch_size=32, shuffle=True)# 随机:shuffle=True

bert

# TensorDataset对tensor进行打包
train_ids = TensorDataset(a, b) 
for x_train, y_label in train_ids:print(x_train, y_label)# dataloader进行数据封装
train_loader = DataLoader(dataset=train_ids, batch_size=4, shuffle=True)
for i, data in enumerate(train_loader, 1):  
# 注意enumerate返回值有两个,一个是序号,一个是数据(包含训练数据和标签)x_data, label = data

定义加载模型

bert
model = BertForSequenceClassification.from_pretrained(
'bert-large-uncased', # Use the 124-layer, 1024-hidden, 16-heads, 340M parameters BERT model with an uncased vocab.
num_labels = 2, # The number of output labels--2 for binary classification. You can increase this for multi-class tasks.   
output_attentions = False, # Whether the model returns attentions weights.
output_hidden_states = False, # Whether the model returns all hidden-states.
)
自定义模型
import torch
#自定义前向传播,自动反向传播
class FCModel(torch.nn.Module):#注意继承自 torch.nn.Moduledef __init__(self):super(FCModel, self).__init__() # init父类#多种方式定义model的层self.fc = torch.nn.Linear(in_features=768, out_features=1)def forward(self, input):#使用model的层score = self.fc(input)result = torch.sigmoid(score)return result

GPU/CPU

#获取设备类型
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
#让model适应相应设备
model = FCModel()	#模型实例化
model = model.to(device)
#让数据适应相应设备
input_ids = input_ids.to(device)
显卡设置
#多GPU并行运行
model = nn.DataParallel(model)#清除显存
torch.cuda.empty_cache()

优化器

optimizer = AdamW(model.parameters(),lr = 6e-6, # args.learning_rateeps = 1e-8 # args.adam_epsilon)#学习率预热
scheduler = get_linear_schedule_with_warmup(
optimizer, 
num_warmup_steps = 0, # Default value in run_glue.py
num_training_steps = total_steps
)
RMSProp

思想:梯度震动较大的项,在下降时,减小其下降速度;对于震动幅度小的项,在下降时,加速其下降速度

RMSprop采用均方根作为分母,可缓解Adagrad学习率下降较快的问题,对于RNN有很好的效果

torch.optim.RMSprop(params, lr=0.01, alpha=0.99, eps=1e-08, weight_decay=0, momentum=0, centered=False)

优点:可缓解Adagrad学习率下降较快的问题,并且引入均方根,可以减少摆动,适合处理非平稳目标,对于RNN效果很好

缺点:依然依赖于全局学习率

Adam

将Momentum算法和RMSProp算法结合起来使用的一种算法,既用动量来累积梯度,又使得收敛速度更快同时使得波动的幅度更小,并进行了偏差修正

torch.optim.Adam(params, lr=0.001, betas=(0.9, 0.999), eps=1e-08, weight_decay=0)

优点:
1、对目标函数没有平稳要求,即loss function可以随着时间变化
2、参数的更新不受梯度的伸缩变换影响
3、更新步长和梯度大小无关,只和alpha、beta_1、beta_2有关系。并且由它们决定步长的理论上限
4、更新的步长能够被限制在大致的范围内(初始学习率)
5、能较好的处理噪音样本,能天然地实现步长退火过程(自动调整学习率)
6、很适合应用于大规模的数据及参数的场景、不稳定目标函数、梯度稀疏或梯度存在很大噪声的

训练和评估

for epoch_i in range(0, epochs):#model.train()#model.eval():告诉网络的所有层,你在eval模式,也就是说,像batchNorm和dropout这样的层会工作在eval模式而非training模式#model.eval()for step, batch in enumerate(train_dataloader):model.zero_grad()loss, logits = model(b_input_ids, token_type_ids=None, attention_mask=b_input_mask, labels=b_labels)optimizer.zero_grad()loss.backward()optimizer.step()scheduler.step()

模型保存加载

一般模型
# 保存模型的全部 (大模型不建议)
torch.save(model, "./model_fc.pth")
model = torch.load("./model_fc.pth")
# 只保存各层的参数 (大模型建议)
torch.save(model.state_dict(), "./model_fc.pt")
model = FCModel()#加载前需要构造一个模型实例
model.load_state_dict(torch.load("./model_fc.pt"))
huggingface
#save tokenizer若未修改不用保存
bert_model.save_pretrained('./Fine_tune_BERT/')
#load
bert_model = TFBertModel.from_pretrained('./Fine_tune_BERT/')
tokenizer = BertTokenizer.from_pretrained('bert-base-cased')

可视化注意力

def showAttention(input_sentence, output_words, attentions):# 用colorbar设置图fig = plt.figure()ax = fig.add_subplot(111)cax = ax.matshow(attentions.numpy(), cmap='bone')fig.colorbar(cax)# 设置坐标ax.set_xticklabels([''] + input_sentence.split(' ') +['<EOS>'], rotation=90)ax.set_yticklabels([''] + output_words)# 在每个刻度处显示标签ax.xaxis.set_major_locator(ticker.MultipleLocator(1))ax.yaxis.set_major_locator(ticker.MultipleLocator(1))plt.show()def evaluateAndShowAttention(input_sentence):output_words, attentions = evaluate(encoder1, attn_decoder1, input_sentence)print('input =', input_sentence)print('output =', ' '.join(output_words))showAttention(input_sentence, output_words, attentions)

https://i.loli.net/2021/08/20/L1AfQu6evprKdbM.png

这篇关于nlp深度学习代码总结--pytoch的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/774870

相关文章

使用Java将DOCX文档解析为Markdown文档的代码实现

《使用Java将DOCX文档解析为Markdown文档的代码实现》在现代文档处理中,Markdown(MD)因其简洁的语法和良好的可读性,逐渐成为开发者、技术写作者和内容创作者的首选格式,然而,许多文... 目录引言1. 工具和库介绍2. 安装依赖库3. 使用Apache POI解析DOCX文档4. 将解析

C++使用printf语句实现进制转换的示例代码

《C++使用printf语句实现进制转换的示例代码》在C语言中,printf函数可以直接实现部分进制转换功能,通过格式说明符(formatspecifier)快速输出不同进制的数值,下面给大家分享C+... 目录一、printf 原生支持的进制转换1. 十进制、八进制、十六进制转换2. 显示进制前缀3. 指

使用Python实现全能手机虚拟键盘的示例代码

《使用Python实现全能手机虚拟键盘的示例代码》在数字化办公时代,你是否遇到过这样的场景:会议室投影电脑突然键盘失灵、躺在沙发上想远程控制书房电脑、或者需要给长辈远程协助操作?今天我要分享的Pyth... 目录一、项目概述:不止于键盘的远程控制方案1.1 创新价值1.2 技术栈全景二、需求实现步骤一、需求

Java中Date、LocalDate、LocalDateTime、LocalTime、时间戳之间的相互转换代码

《Java中Date、LocalDate、LocalDateTime、LocalTime、时间戳之间的相互转换代码》:本文主要介绍Java中日期时间转换的多种方法,包括将Date转换为LocalD... 目录一、Date转LocalDateTime二、Date转LocalDate三、LocalDateTim

jupyter代码块没有运行图标的解决方案

《jupyter代码块没有运行图标的解决方案》:本文主要介绍jupyter代码块没有运行图标的解决方案,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录jupyter代码块没有运行图标的解决1.找到Jupyter notebook的系统配置文件2.这时候一般会搜索到

Python通过模块化开发优化代码的技巧分享

《Python通过模块化开发优化代码的技巧分享》模块化开发就是把代码拆成一个个“零件”,该封装封装,该拆分拆分,下面小编就来和大家简单聊聊python如何用模块化开发进行代码优化吧... 目录什么是模块化开发如何拆分代码改进版:拆分成模块让模块更强大:使用 __init__.py你一定会遇到的问题模www.

springboot循环依赖问题案例代码及解决办法

《springboot循环依赖问题案例代码及解决办法》在SpringBoot中,如果两个或多个Bean之间存在循环依赖(即BeanA依赖BeanB,而BeanB又依赖BeanA),会导致Spring的... 目录1. 什么是循环依赖?2. 循环依赖的场景案例3. 解决循环依赖的常见方法方法 1:使用 @La

使用C#代码在PDF文档中添加、删除和替换图片

《使用C#代码在PDF文档中添加、删除和替换图片》在当今数字化文档处理场景中,动态操作PDF文档中的图像已成为企业级应用开发的核心需求之一,本文将介绍如何在.NET平台使用C#代码在PDF文档中添加、... 目录引言用C#添加图片到PDF文档用C#删除PDF文档中的图片用C#替换PDF文档中的图片引言在当

C#使用SQLite进行大数据量高效处理的代码示例

《C#使用SQLite进行大数据量高效处理的代码示例》在软件开发中,高效处理大数据量是一个常见且具有挑战性的任务,SQLite因其零配置、嵌入式、跨平台的特性,成为许多开发者的首选数据库,本文将深入探... 目录前言准备工作数据实体核心技术批量插入:从乌龟到猎豹的蜕变分页查询:加载百万数据异步处理:拒绝界面

用js控制视频播放进度基本示例代码

《用js控制视频播放进度基本示例代码》写前端的时候,很多的时候是需要支持要网页视频播放的功能,下面这篇文章主要给大家介绍了关于用js控制视频播放进度的相关资料,文中通过代码介绍的非常详细,需要的朋友可... 目录前言html部分:JavaScript部分:注意:总结前言在javascript中控制视频播放