【深度学习】sentencepiece工具之BPE训练使用

2023-11-23 15:40

本文主要是介绍【深度学习】sentencepiece工具之BPE训练使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

为什么要使用BPE,BPE是什么

BPE:迭代的将字符串里出现频率最高的子串进行合并
训练过程
在这里插入图片描述
在这里插入图片描述

使用教程

代码使用的语料在这里

# -*- coding: utf-8 -*-
#/usr/bin/python3import os
import errno
import sentencepiece as spm
import re
import logginglogging.basicConfig(level=logging.INFO)def prepro(hp):print("# Check if raw files exist")train1 = "iwslt2016/de-en/train.tags.de-en.de"train2 = "iwslt2016/de-en/train.tags.de-en.en"eval1 = "iwslt2016/de-en/IWSLT16.TED.tst2013.de-en.de.xml"eval2 = "iwslt2016/de-en/IWSLT16.TED.tst2013.de-en.en.xml"test1 = "iwslt2016/de-en/IWSLT16.TED.tst2014.de-en.de.xml"test2 = "iwslt2016/de-en/IWSLT16.TED.tst2014.de-en.en.xml"for f in (train1, train2, eval1, eval2, test1, test2):if not os.path.isfile(f):raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), f)print("# Preprocessing")# train_prepro = lambda x:  [line.strip() for line in open(x, mode='r',encoding="utf-8").read().split("\n") \if not line.startswith("<")]prepro_train1, prepro_train2 = _prepro(train1), _prepro(train2)assert len(prepro_train1)==len(prepro_train2), "Check if train source and target files match."# eval_prepro = lambda x: [re.sub("<[^>]+>", "", line).strip() \for line in open(x, mode='r',encoding="utf-8").read().split("\n") \if line.startswith("<seg id")]prepro_eval1, prepro_eval2 = _prepro(eval1), _prepro(eval2)assert len(prepro_eval1) == len(prepro_eval2), "Check if eval source and target files match."# testprepro_test1, prepro_test2 = _prepro(test1), _prepro(test2)assert len(prepro_test1) == len(prepro_test2), "Check if test source and target files match."print("Let's see how preprocessed data look like")print("prepro_train1:", prepro_train1[0])print("prepro_train2:", prepro_train2[0])print("prepro_eval1:", prepro_eval1[0])print("prepro_eval2:", prepro_eval2[0])print("prepro_test1:", prepro_test1[0])print("prepro_test2:", prepro_test2[0])print("# write preprocessed files to disk")os.makedirs("iwslt2016/prepro", exist_ok=True)def _write(sents, fname):with open(fname, mode='w',encoding="utf-8") as fout:fout.write("\n".join(sents))_write(prepro_train1, "iwslt2016/prepro/train.de")_write(prepro_train2, "iwslt2016/prepro/train.en")_write(prepro_train1+prepro_train2, "iwslt2016/prepro/train")_write(prepro_eval1, "iwslt2016/prepro/eval.de")_write(prepro_eval2, "iwslt2016/prepro/eval.en")_write(prepro_test1, "iwslt2016/prepro/test.de")_write(prepro_test2, "iwslt2016/prepro/test.en")print("# Train a joint BPE model with sentencepiece")os.makedirs("iwslt2016/segmented", exist_ok=True)train = '--input=iwslt2016/prepro/train --pad_id=0 --unk_id=1 \--bos_id=2 --eos_id=3\--model_prefix=iwslt2016/segmented/bpe --vocab_size={} \--model_type=bpe'.format(hp.vocab_size)spm.SentencePieceTrainer.Train(train)print("# Load trained bpe model")sp = spm.SentencePieceProcessor()sp.Load("iwslt2016/segmented/bpe.model")print("# Segment")def _segment_and_write(sents, fname):with open(fname,mode= "w",encoding="utf-8") as fout:for sent in sents:pieces = sp.EncodeAsPieces(sent)fout.write(" ".join(pieces) + "\n")_segment_and_write(prepro_train1, "iwslt2016/segmented/train.de.bpe")_segment_and_write(prepro_train2, "iwslt2016/segmented/train.en.bpe")_segment_and_write(prepro_eval1, "iwslt2016/segmented/eval.de.bpe")_segment_and_write(prepro_eval2, "iwslt2016/segmented/eval.en.bpe")_segment_and_write(prepro_test1, "iwslt2016/segmented/test.de.bpe")print("Let's see how segmented data look like")print("train1:", open("iwslt2016/segmented/train.de.bpe",mode='r',encoding="utf-8").readline())print("train2:", open("iwslt2016/segmented/train.en.bpe", mode='r',encoding="utf-8").readline())print("eval1:", open("iwslt2016/segmented/eval.de.bpe", mode='r',encoding="utf-8").readline())print("eval2:", open("iwslt2016/segmented/eval.en.bpe", mode='r',encoding="utf-8").readline())print("test1:", open("iwslt2016/segmented/test.de.bpe", mode='r',encoding="utf-8").readline())if __name__ == '__main__':hparams = Hparams()parser = hparams.parserhp = parser.parse_args()prepro(hp)print("Done")

这篇关于【深度学习】sentencepiece工具之BPE训练使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

使用Python提取PDF大纲(书签)的完整指南

《使用Python提取PDF大纲(书签)的完整指南》PDF大纲(Outline)​​是PDF文档中的导航结构,通常显示在阅读器的侧边栏中,方便用户快速跳转到文档的不同部分,大纲通常以层级结构组织,包含... 目录一、PDF大纲简介二、准备工作所需工具常见安装问题三、代码实现完整代码核心功能解析四、使用效果控

C#异步编程ConfigureAwait的使用小结

《C#异步编程ConfigureAwait的使用小结》本文介绍了异步编程在GUI和服务器端应用的优势,详细的介绍了async和await的关键作用,通过实例解析了在UI线程正确使用await.Conf... 异步编程是并发的一种形式,它有两大好处:对于面向终端用户的GUI程序,提高了响应能力对于服务器端应

MySQL慢查询工具的使用小结

《MySQL慢查询工具的使用小结》使用MySQL的慢查询工具可以帮助开发者识别和优化性能不佳的SQL查询,本文就来介绍一下MySQL的慢查询工具,具有一定的参考价值,感兴趣的可以了解一下... 目录一、启用慢查询日志1.1 编辑mysql配置文件1.2 重启MySQL服务二、配置动态参数(可选)三、分析慢查

MYSQL中information_schema的使用

《MYSQL中information_schema的使用》information_schema是MySQL中的一个虚拟数据库,用于提供关于MySQL服务器及其数据库的元数,这些元数据包括数据库名称、表... 目录关键要点什么是information_schema?主要功能使用示例mysql 中informa

Spring Boot项目如何使用外部application.yml配置文件启动JAR包

《SpringBoot项目如何使用外部application.yml配置文件启动JAR包》文章介绍了SpringBoot项目通过指定外部application.yml配置文件启动JAR包的方法,包括... 目录Spring Boot项目中使用外部application.yml配置文件启动JAR包一、基本原理

gorm乐观锁使用小结

《gorm乐观锁使用小结》本文主要介绍了gorm乐观锁使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录前言grom乐观锁机制gorm乐观锁依赖安装gorm乐观锁使用创建一个user表插入数据版本号更新总结前言乐观锁,顾名

Python 函数详解:从基础语法到高级使用技巧

《Python函数详解:从基础语法到高级使用技巧》本文基于实例代码,全面讲解Python函数的定义、参数传递、变量作用域及类型标注等知识点,帮助初学者快速掌握函数的使用技巧,感兴趣的朋友跟随小编一起... 目录一、函数的基本概念与作用二、函数的定义与调用1. 无参函数2. 带参函数3. 带返回值的函数4.

MySQL中DATE_FORMAT时间函数的使用小结

《MySQL中DATE_FORMAT时间函数的使用小结》本文主要介绍了MySQL中DATE_FORMAT时间函数的使用小结,用于格式化日期/时间字段,可提取年月、统计月份数据、精确到天,对大家的学习或... 目录前言DATE_FORMAT时间函数总结前言mysql可以使用DATE_FORMAT获取日期字段

Go语言使用sync.Mutex实现资源加锁

《Go语言使用sync.Mutex实现资源加锁》数据共享是一把双刃剑,Go语言为我们提供了sync.Mutex,一种最基础也是最常用的加锁方式,用于保证在任意时刻只有一个goroutine能访问共享... 目录一、什么是 Mutex二、为什么需要加锁三、实战案例:并发安全的计数器1. 未加锁示例(存在竞态)

基于Python实现进阶版PDF合并/拆分工具

《基于Python实现进阶版PDF合并/拆分工具》在数字化时代,PDF文件已成为日常工作和学习中不可或缺的一部分,本文将详细介绍一款简单易用的PDF工具,帮助用户轻松完成PDF文件的合并与拆分操作... 目录工具概述环境准备界面说明合并PDF文件拆分PDF文件高级技巧常见问题完整源代码总结在数字化时代,PD