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通过驱动包(jar包)连接MySQL数据库的步骤总结及验证方式

《Java通过驱动包(jar包)连接MySQL数据库的步骤总结及验证方式》本文详细介绍如何使用Java通过JDBC连接MySQL数据库,包括下载驱动、配置Eclipse环境、检测数据库连接等关键步骤,... 目录一、下载驱动包二、放jar包三、检测数据库连接JavaJava 如何使用 JDBC 连接 mys

深度解析Java DTO(最新推荐)

《深度解析JavaDTO(最新推荐)》DTO(DataTransferObject)是一种用于在不同层(如Controller层、Service层)之间传输数据的对象设计模式,其核心目的是封装数据,... 目录一、什么是DTO?DTO的核心特点:二、为什么需要DTO?(对比Entity)三、实际应用场景解析

深度解析Java项目中包和包之间的联系

《深度解析Java项目中包和包之间的联系》文章浏览阅读850次,点赞13次,收藏8次。本文详细介绍了Java分层架构中的几个关键包:DTO、Controller、Service和Mapper。_jav... 目录前言一、各大包1.DTO1.1、DTO的核心用途1.2. DTO与实体类(Entity)的区别1

JavaSE正则表达式用法总结大全

《JavaSE正则表达式用法总结大全》正则表达式就是由一些特定的字符组成,代表的是一个规则,:本文主要介绍JavaSE正则表达式用法的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考下... 目录常用的正则表达式匹配符正则表China编程达式常用的类Pattern类Matcher类PatternSynta

Java中调用数据库存储过程的示例代码

《Java中调用数据库存储过程的示例代码》本文介绍Java通过JDBC调用数据库存储过程的方法,涵盖参数类型、执行步骤及数据库差异,需注意异常处理与资源管理,以优化性能并实现复杂业务逻辑,感兴趣的朋友... 目录一、存储过程概述二、Java调用存储过程的基本javascript步骤三、Java调用存储过程示

Visual Studio 2022 编译C++20代码的图文步骤

《VisualStudio2022编译C++20代码的图文步骤》在VisualStudio中启用C++20import功能,需设置语言标准为ISOC++20,开启扫描源查找模块依赖及实验性标... 默认创建Visual Studio桌面控制台项目代码包含C++20的import方法。右键项目的属性:

深度解析Python装饰器常见用法与进阶技巧

《深度解析Python装饰器常见用法与进阶技巧》Python装饰器(Decorator)是提升代码可读性与复用性的强大工具,本文将深入解析Python装饰器的原理,常见用法,进阶技巧与最佳实践,希望可... 目录装饰器的基本原理函数装饰器的常见用法带参数的装饰器类装饰器与方法装饰器装饰器的嵌套与组合进阶技巧

深度解析Spring Boot拦截器Interceptor与过滤器Filter的区别与实战指南

《深度解析SpringBoot拦截器Interceptor与过滤器Filter的区别与实战指南》本文深度解析SpringBoot中拦截器与过滤器的区别,涵盖执行顺序、依赖关系、异常处理等核心差异,并... 目录Spring Boot拦截器(Interceptor)与过滤器(Filter)深度解析:区别、实现

MySQL数据库的内嵌函数和联合查询实例代码

《MySQL数据库的内嵌函数和联合查询实例代码》联合查询是一种将多个查询结果组合在一起的方法,通常使用UNION、UNIONALL、INTERSECT和EXCEPT关键字,下面:本文主要介绍MyS... 目录一.数据库的内嵌函数1.1聚合函数COUNT([DISTINCT] expr)SUM([DISTIN

深度解析Spring AOP @Aspect 原理、实战与最佳实践教程

《深度解析SpringAOP@Aspect原理、实战与最佳实践教程》文章系统讲解了SpringAOP核心概念、实现方式及原理,涵盖横切关注点分离、代理机制(JDK/CGLIB)、切入点类型、性能... 目录1. @ASPect 核心概念1.1 AOP 编程范式1.2 @Aspect 关键特性2. 完整代码实