在PyTorch中使用Seq2Seq构建的神经机器翻译模型(三)

简介: 在PyTorch中使用Seq2Seq构建的神经机器翻译模型

9.Seq2Seq(编码器+解码器)代码实现

classSeq2Seq(nn.Module):
def__init__(self, Encoder_LSTM, Decoder_LSTM):
super(Seq2Seq, self).__init__()
self.Encoder_LSTM=Encoder_LSTMself.Decoder_LSTM=Decoder_LSTMdefforward(self, source, target, tfr=0.5):
#Shape-Source : (10, 32) [(SentencelengthGerman+somepadding), NumberofSentences]
batch_size=source.shape[1]
#Shape-Source : (14, 32) [(SentencelengthEnglish+somepadding), NumberofSentences]
target_len=target.shape[0]
target_vocab_size=len(english.vocab)
#Shape-->outputs (14, 32, 5766)
outputs=torch.zeros(target_len, batch_size, target_vocab_size).to(device)
#Shape--> (hs, cs) (2, 32, 1024) ,(2, 32, 1024) [num_layers, batch_sizesize, hidden_size] (containsencoder's hs, cs - context vectors)hidden_state_encoder, cell_state_encoder = self.Encoder_LSTM(source)# Shape of x (32 elements)x = target[0] # Trigger token <SOS>for i in range(1, target_len):# Shape --> output (32, 5766)output, hidden_state_decoder, cell_state_decoder = self.Decoder_LSTM(x, hidden_state_encoder, cell_state_encoder)outputs[i] = outputbest_guess = output.argmax(1) # 0th dimension is batch size, 1st dimension is word embeddingx = target[i] if random.random() < tfr else best_guess # Either pass the next word correctly from the dataset or use the earlier predicted word# Shape --> outputs (14, 32, 5766)return outputsprint(model)************************************************ OUTPUT ************************************************Seq2Seq((Encoder_LSTM): EncoderLSTM((dropout): Dropout(p=0.5, inplace=False)(embedding): Embedding(5376, 300)(LSTM): LSTM(300, 1024, num_layers=2, dropout=0.5))(Decoder_LSTM): DecoderLSTM((dropout): Dropout(p=0.5, inplace=False)(embedding): Embedding(4556, 300)(LSTM): LSTM(300, 1024, num_layers=2, dropout=0.5)(fc): Linear(in_features=1024, out_features=4556, bias=True)))

10.Seq2Seq模型训练

epoch_loss=0.0num_epochs=100best_loss=999999best_epoch=-1sentence1="ein mann in einem blauen hemd steht auf einer leiter und putzt ein fenster"ts1= []
forepochinrange(num_epochs):
print("Epoch - {} / {}".format(epoch+1, num_epochs))
model.eval()
translated_sentence1=translate_sentence(model, sentence1, german, english, device, max_length=50)
print(f"Translated example sentence 1: \n {translated_sentence1}")
ts1.append(translated_sentence1)
model.train(True)
forbatch_idx, batchinenumerate(train_iterator):
input=batch.src.to(device)
target=batch.trg.to(device)
#Passtheinputandtargetformodel's forward methodoutput = model(input, target)output = output[1:].reshape(-1, output.shape[2])target = target[1:].reshape(-1)# Clear the accumulating gradientsoptimizer.zero_grad()# Calculate the loss value for every epochloss = criterion(output, target)# Calculate the gradients for weights & biases using back-propagationloss.backward()# Clip the gradient value is it exceeds > 1torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1)# Update the weights values using the gradients we calculated using bpoptimizer.step()step += 1epoch_loss += loss.item()writer.add_scalar("Training loss", loss, global_step=step)if epoch_loss < best_loss:best_loss = epoch_lossbest_epoch = epochcheckpoint_and_save(model, best_loss, epoch, optimizer, epoch_loss)if ((epoch - best_epoch) >= 10):print("no improvement in 10 epochs, break")breakprint("Epoch_Loss - {}".format(loss.item()))print()print(epoch_loss / len(train_iterator))score = bleu(test_data[1:100], model, german, english, device)print(f"Bleu score {score*100:.2f}")************************************************ OUTPUT ************************************************Bleu score 15.62

例句训练进度:

640.png

训练损失:

640.png

11.Seq2Seq模型推理

现在,让我们将我们训练有素的模型与SOTA Google Translate的模型进行比较。

640.png

model.eval()
test_sentences= ["Zwei Männer gehen die Straße entlang", "Kinder spielen im Park.",
"Diese Stadt verdient eine bessere Klasse von Verbrechern. Der Spaßvogel"]
actual_sentences= ["Two men are walking down the street", "Children play in the park",
"This city deserves a better class of criminals. The joker"]
pred_sentences= []
foridx, iinenumerate(test_sentences):
model.eval()
translated_sentence=translate_sentence(model, i, german, english, device, max_length=50)
progress.append(TreebankWordDetokenizer().detokenize(translated_sentence))
print("German : {}".format(i))
print("Actual Sentence in English : {}".format(actual_sentences[idx]))
print("Predicted Sentence in English : {}".format(progress[-1]))
print()
*******************************************OUTPUT*******************************************German : "Zwei Männer gehen die Straße entlang"ActualSentenceinEnglish : "Two men are walking down the street"PredictedSentenceinEnglish : "two men are walking on the street . <eos>"German : "Kinder spielen im Park."ActualSentenceinEnglish : "Children play in the park"PredictedSentenceinEnglish : "children playing in the park . <eos>"German : "Diese Stadt verdient eine bessere Klasse von Verbrechern. Der Spaßvogel"ActualSentenceinEnglish : "This city deserves a better class of criminals. The joker"PredictedSentenceinEnglish : "this <unk>'s <unk> from a <unk> green team <unk> by the sidelines . <eos>"

不错,但是很明显,该模型不能理解复杂的句子。因此,在接下来的系列文章中,我将通过更改模型的体系结构来提高上述模型的性能,例如使用双向LSTM,添加注意力机制或将LSTM替换为Transformers模型来克服这些明显的缺点。

希望我能够对Seq2Seq模型如何处理数据有一些直观的了解,在评论部分告诉我您的想法。

目录
相关文章
|
8月前
|
机器学习/深度学习 存储 PyTorch
Neural ODE原理与PyTorch实现:深度学习模型的自适应深度调节
Neural ODE将神经网络与微分方程结合,用连续思维建模数据演化,突破传统离散层的限制,实现自适应深度与高效连续学习。
756 3
Neural ODE原理与PyTorch实现:深度学习模型的自适应深度调节
|
7月前
|
边缘计算 人工智能 PyTorch
130_知识蒸馏技术:温度参数与损失函数设计 - 教师-学生模型的优化策略与PyTorch实现
随着大型语言模型(LLM)的规模不断增长,部署这些模型面临着巨大的计算和资源挑战。以DeepSeek-R1为例,其671B参数的规模即使经过INT4量化后,仍需要至少6张高端GPU才能运行,这对于大多数中小型企业和研究机构来说成本过高。知识蒸馏作为一种有效的模型压缩技术,通过将大型教师模型的知识迁移到小型学生模型中,在显著降低模型复杂度的同时保留核心性能,成为解决这一问题的关键技术之一。
629 6
|
9月前
|
PyTorch 算法框架/工具 异构计算
PyTorch 2.0性能优化实战:4种常见代码错误严重拖慢模型
我们将深入探讨图中断(graph breaks)和多图问题对性能的负面影响,并分析PyTorch模型开发中应当避免的常见错误模式。
519 9
|
11月前
|
机器学习/深度学习 存储 PyTorch
PyTorch + MLFlow 实战:从零构建可追踪的深度学习模型训练系统
本文通过使用 Kaggle 数据集训练情感分析模型的实例,详细演示了如何将 PyTorch 与 MLFlow 进行深度集成,实现完整的实验跟踪、模型记录和结果可复现性管理。文章将系统性地介绍训练代码的核心组件,展示指标和工件的记录方法,并提供 MLFlow UI 的详细界面截图。
492 2
PyTorch + MLFlow 实战:从零构建可追踪的深度学习模型训练系统
|
11月前
|
机器学习/深度学习 PyTorch 算法框架/工具
提升模型泛化能力:PyTorch的L1、L2、ElasticNet正则化技术深度解析与代码实现
本文将深入探讨L1、L2和ElasticNet正则化技术,重点关注其在PyTorch框架中的具体实现。关于这些技术的理论基础,建议读者参考相关理论文献以获得更深入的理解。
366 4
提升模型泛化能力:PyTorch的L1、L2、ElasticNet正则化技术深度解析与代码实现
|
存储 自然语言处理 PyTorch
从零开始用Pytorch实现LLaMA 4的混合专家(MoE)模型
近期发布的LLaMA 4模型引入混合专家(MoE)架构,以提升效率与性能。尽管社区对其实际表现存在讨论,但MoE作为重要设计范式再次受到关注。本文通过Pytorch从零实现简化版LLaMA 4 MoE模型,涵盖数据准备、分词、模型构建(含词元嵌入、RoPE、RMSNorm、多头注意力及MoE层)到训练与文本生成全流程。关键点包括MoE层实现(路由器、专家与共享专家)、RoPE处理位置信息及RMSNorm归一化。虽规模小于实际LLaMA 4,但清晰展示MoE核心机制:动态路由与稀疏激活专家,在控制计算成本的同时提升性能。完整代码见链接,基于FareedKhan-dev的Github代码修改而成。
663 9
从零开始用Pytorch实现LLaMA 4的混合专家(MoE)模型
|
12月前
|
机器学习/深度学习 PyTorch 编译器
深入解析torch.compile:提升PyTorch模型性能、高效解决常见问题
PyTorch 2.0推出的`torch.compile`功能为深度学习模型带来了显著的性能优化能力。本文从实用角度出发,详细介绍了`torch.compile`的核心技巧与应用场景,涵盖模型复杂度评估、可编译组件分析、系统化调试策略及性能优化高级技巧等内容。通过解决图断裂、重编译频繁等问题,并结合分布式训练和NCCL通信优化,开发者可以有效提升日常开发效率与模型性能。文章为PyTorch用户提供了全面的指导,助力充分挖掘`torch.compile`的潜力。
1276 17
|
12月前
|
机器学习/深度学习 搜索推荐 PyTorch
基于昇腾用PyTorch实现CTR模型DIN(Deep interest Netwok)网络
本文详细讲解了如何在昇腾平台上使用PyTorch训练推荐系统中的经典模型DIN(Deep Interest Network)。主要内容包括:DIN网络的创新点与架构剖析、Activation Unit和Attention模块的实现、Amazon-book数据集的介绍与预处理、模型训练过程定义及性能评估。通过实战演示,利用Amazon-book数据集训练DIN模型,最终评估其点击率预测性能。文中还提供了代码示例,帮助读者更好地理解每个步骤的实现细节。

热门文章

最新文章

推荐镜像

更多