pytorch_pretrained_bert将tensorflow转为pytorch pytorch_pretrained_bert怎样将tensorflow模型转化为pytorch模型

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

pytorch_pretrained_bert将tensorflow转为pytorch pytorch_pretrained_bert怎样将tensorflow模型转化为pytorch模型

乐清sss   2021-06-07 我要评论
想了解pytorch_pretrained_bert怎样将tensorflow模型转化为pytorch模型的相关内容吗,乐清sss在本文为您仔细讲解pytorch_pretrained_bert将tensorflow转为pytorch的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:pytorch_pretrained_bert,tensorflow模型,pytorch模型,下面大家一起来学习吧。

pytorch_pretrained_bert将tensorflow模型转化为pytorch模型

BERT仓库里的模型是TensorFlow版本的,需要进行相应的转换才能在pytorch中使用

Google BERT仓库里下载需要的模型,这里使用的是中文预训练模型(chinese_L-12_H-768_A_12)

在这里插入图片描述

下载chinese_L-12_H-768_A-12.zip后解压,里面有5个文件

chinese_L-12_H-768_A-12.zip后解压,里面有5个文件

bert_config.json

bert_model.ckpt.data-00000-of-00001

bert_model.ckpt.index

bert_model.ckpt.meta

vocab.txt

使用bert仓库里的convert_bert_original_tf_checkpoint_to_pytorch.py将此模型转化为pytorch版本的,这里我的文件夹位置为:D:\Work\BISHE\BERT-Dureader\data\chinese_L-12_H-768_A-12,替换为自己的即可

python convert_tf_checkpoint_to_pytorch.py --tf_checkpoint_path D:\Work\BISHE\BERT-Dureader\data\chinese_L-12_H-768_A-12\bert_model.ckpt --bert_config_file D:\Work\BISHE\BERT-Dureader\data\chinese_L-12_H-768_A-12\bert_config.json --pytorch_dump_path D:\Work\BISHE\BERT-Dureader\data\chinese_L-12_H-768_A-12\pytorch_model.bin

注:这里让我疑惑的是模型有5个文件,为什么转化的时候使用的是bert_model.ckpt,而且这个文件也不存在呀,是我对TensorFlow的模型不太熟悉,查阅资料之后将5个文件的作用说明如下:

$ tree chinese_L-12_H-768_A-12/
chinese_L-12_H-768_A-12/
├── bert_config.json                     <- 模型配置文件
├── bert_model.ckpt.data-00000-of-00001  <- 保存断点文件列表,可以用来迅速查找最近一次的断点文件
├── bert_model.ckpt.index                <- 为数据文件提供索引,存储的核心内容是以tensor name为键以BundleEntry为值的表格entries,BundleEntry主要内容是权值的类型、形状、偏移、校验和等信息。
├── bert_model.ckpt.meta                 <- 是MetaGraphDef序列化的二进制文件,保存了网络结构相关的数据,包括graph_def和saver_def等
└── vocab.txt                            <- 模型词汇表文件

0 directories, 5 files

在调用模型时使用chinese_L-12_H-768_A-12\bert_model.ckpt即可。

TensorFlow 读取ckpt文件中的tensor,将ckpt模型转为pytorch模型

想用MobileNet V1训练自己的数据,发现pytorch没有MobileNet V1的预训练权重,只好先下载TensorFlow的预训练权重,再转成pytorch模型。

读取ckpt中的Tensor名称以及Tensor值

TensorFlow的MobileNet V1预训练权重文件如下:

解压完文件后,发现没有.ckpt文件,文件名只需'./my_model/mobilenet_v1_1.0_224/mobilenet_v1_1.0_224.ckpt'这样写就行。

写一半发现Tensor名称好难对应起来。希望能给大家一个参考,也希望大家多多支持

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们