首先跑通xnli的代码,根据xnli的中间结果或者数据格式来修改我们自己的任务.
修改 xnli 任务记得的几个坑:
1. 下载 XNLI-1.0.zip 报错了, 下载地址的问题, 根据ReadMe找到原始的下载地址, 修改为
xnli_http="https://www.nyu.edu/projects/bowman/xnli"
2. 安装
pip install jieba
conda install faiss-cpu -c pytorch (不能直接pip安装)
pip install transliterate
3. 在 .bashrc 文件中加入
export LC_ALL=C
并source .bashrc
4. 记得第一次把数据下载之后,要注释掉, 然后每次重新运行最好是将 embd 目录下面的文件清除一下, 前面错误导致生成的文件是空的或者错的, 会导致后面训练分类器的时候报错.
只要文件都生成正确了, 训练的代码没有什么问题.
查看生成的数据格式
1. XNLI的数据格式, 以 XNLI-1.0/xnli.dev.tsv 为例:
languageType neutral (global label) sentence1 | sentence2 1(pairID) 等其他用不到的label信息
2. 在embd文件下面对于每个文件都会生成三个后缀的文件分别是, tok, bpe, enc. 以及 cl 文件
比如 train 的 hyp 文件, 另外 prem 文件也是一样的:
xnli.train.hyp.tok.en # token 序列
i havent spoken to him again .
i was so upset that i just started talking to him again .
xnli.train.hyp.bpe.en # bpe序列
i ha@@ vent spo@@ ken to him again .
i was so up@@ set that i just started talking to him again .
xnli.train.hyp.enc.en # 看代码是网络输出embedding序列
全是乱码, 可能是 pytorch 数据文件
xnli.train.cl.en 存放label文件
2
0
3. 然后用这些生成的数据进行训练网络
最后只需要按照文件格式修改为自己的 Paraphrase 任务.
坑1, 当处理中文的时候,如果文件不是utf-8编码, 则会在生成 BPE 编码的时候失败:
https://github.com/facebookresearch/LASER/issues/41
编码转换代码:
def transfer2utf8_v1(filepath):
import chardet
with open(filepath, "rb") as f:
data = f.read()
source_encoding = chardet.detect(data) # {'encoding': None, 'language': None, 'confidence': 0.0}
print(source_encoding)
if source_encoding['encoding'] is None:
print("Can't detect the encoding information!")
exit(0)
data.decode(source_encoding).encode('utf-8')
with open(filepath, 'w', encoding='utf-8') as f:
f.write(data)
def transfer2utf8_v2(filepath):
'''
当 chardetect, enca 工具都检测不到文件编码时, 就很难处理了, 一个最简单的方式就是vim 打开 然后 set fileencoding=utf-8
但是当文件比较多的时候, 没法这么操作, 只能手动去尝试所有可能的编码
:param filepath:
:return:
'''
import codecs
f = open(filepath, 'rb')
content = f.read()
source_encoding = 'utf-8'
try:
content.decode('utf-8').encode('utf-8')
source_encoding = 'utf-8'
except:
try:
content.decode('gbk').encode('utf-8')
source_encoding = 'gbk'
except:
try:
content.decode('gb2312').encode('utf-8')
source_encoding = 'gb2312'
except:
try:
content.decode('gb18030').encode('utf-8')
source_encoding = 'gb18030'
except:
try:
content.decode('big5').encode('utf-8')
source_encoding = 'big5'
except:
try:
content.decode('iso-8859-1').encode('utf-8')
source_encoding = 'iso-8859-1'
except:
try:
content.decode('cp936').encode('utf-8')
source_encoding = 'cp936'
except:
print("***Error: Please try others!")
exit(0)
f.close()
print("the file encoding is {}".format(source_encoding))
os.system("cp {} {}".format(filepath, filepath + '.temp'))
temp_file = filepath + '.temp'
with open(temp_file, 'r', encoding=source_encoding) as f1:
content = f1.read()
with open(filepath, 'w', encoding='utf-8') as f2:
f2.write(content)
os.system("rm {}".format(temp_file))