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

相关文章

使用Spring Cache本地缓存示例代码

《使用SpringCache本地缓存示例代码》缓存是提高应用程序性能的重要手段,通过将频繁访问的数据存储在内存中,可以减少数据库访问次数,从而加速数据读取,:本文主要介绍使用SpringCac... 目录一、Spring Cache简介核心特点:二、基础配置1. 添加依赖2. 启用缓存3. 缓存配置方案方案

深度剖析SpringBoot日志性能提升的原因与解决

《深度剖析SpringBoot日志性能提升的原因与解决》日志记录本该是辅助工具,却为何成了性能瓶颈,SpringBoot如何用代码彻底破解日志导致的高延迟问题,感兴趣的小伙伴可以跟随小编一起学习一下... 目录前言第一章:日志性能陷阱的底层原理1.1 日志级别的“双刃剑”效应1.2 同步日志的“吞吐量杀手”

MySQL的配置文件详解及实例代码

《MySQL的配置文件详解及实例代码》MySQL的配置文件是服务器运行的重要组成部分,用于设置服务器操作的各种参数,下面:本文主要介绍MySQL配置文件的相关资料,文中通过代码介绍的非常详细,需要... 目录前言一、配置文件结构1.[mysqld]2.[client]3.[mysql]4.[mysqldum

MySQL中查询和展示LONGBLOB类型数据的技巧总结

《MySQL中查询和展示LONGBLOB类型数据的技巧总结》在MySQL中LONGBLOB是一种二进制大对象(BLOB)数据类型,用于存储大量的二进制数据,:本文主要介绍MySQL中查询和展示LO... 目录前言1. 查询 LONGBLOB 数据的大小2. 查询并展示 LONGBLOB 数据2.1 转换为十

Python多线程实现大文件快速下载的代码实现

《Python多线程实现大文件快速下载的代码实现》在互联网时代,文件下载是日常操作之一,尤其是大文件,然而,网络条件不稳定或带宽有限时,下载速度会变得很慢,本文将介绍如何使用Python实现多线程下载... 目录引言一、多线程下载原理二、python实现多线程下载代码说明:三、实战案例四、注意事项五、总结引

Unity新手入门学习殿堂级知识详细讲解(图文)

《Unity新手入门学习殿堂级知识详细讲解(图文)》Unity是一款跨平台游戏引擎,支持2D/3D及VR/AR开发,核心功能模块包括图形、音频、物理等,通过可视化编辑器与脚本扩展实现开发,项目结构含A... 目录入门概述什么是 UnityUnity引擎基础认知编辑器核心操作Unity 编辑器项目模式分类工程

深度解析Python yfinance的核心功能和高级用法

《深度解析Pythonyfinance的核心功能和高级用法》yfinance是一个功能强大且易于使用的Python库,用于从YahooFinance获取金融数据,本教程将深入探讨yfinance的核... 目录yfinance 深度解析教程 (python)1. 简介与安装1.1 什么是 yfinance?

IDEA与MyEclipse代码量统计方式

《IDEA与MyEclipse代码量统计方式》文章介绍在项目中不安装第三方工具统计代码行数的方法,分别说明MyEclipse通过正则搜索(排除空行和注释)及IDEA使用Statistic插件或调整搜索... 目录项目场景MyEclipse代码量统计IDEA代码量统计总结项目场景在项目中,有时候我们需要统计

MySQL设置密码复杂度策略的完整步骤(附代码示例)

《MySQL设置密码复杂度策略的完整步骤(附代码示例)》MySQL密码策略还可能包括密码复杂度的检查,如是否要求密码包含大写字母、小写字母、数字和特殊字符等,:本文主要介绍MySQL设置密码复杂度... 目录前言1. 使用 validate_password 插件1.1 启用 validate_passwo

MySQL实现多源复制的示例代码

《MySQL实现多源复制的示例代码》MySQL的多源复制允许一个从服务器从多个主服务器复制数据,这在需要将多个数据源汇聚到一个数据库实例时非常有用,下面就来详细的介绍一下,感兴趣的可以了解一下... 目录一、多源复制原理二、多源复制配置步骤2.1 主服务器配置Master1配置Master2配置2.2 从服