东方耀AI技术分享

 找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
热搜: 活动 交友 discuz
查看: 3790|回复: 0

[课堂笔记] 09、如何将tensorflow的ckpt模型文件转换为keras的h5文件

[复制链接]

1365

主题

1856

帖子

1万

积分

管理员

Rank: 10Rank: 10Rank: 10

积分
14418
QQ
发表于 2020-2-23 20:35:21 | 显示全部楼层 |阅读模式
09、如何将tensorflow的ckpt模型文件转换为keras的h5文件


import os
import re
import numpy as np
import tensorflow as tf

import sys
sys.path.append('../code/')
from inception_resnet_v1 import *
print('dfy good!')


tf_model_dir = '../model/tf/20190727-181532/'

npy_weights_dir = '../model/keras/npy_weights/'
weights_dir = '../model/keras/weights/'
model_dir = '../model/keras/model/'

weights_filename = 'facenet_keras_weights.h5'
model_filename = 'facenet_keras.h5'

os.makedirs(npy_weights_dir, exist_ok=True)
os.makedirs(weights_dir, exist_ok=True)
os.makedirs(model_dir, exist_ok=True)


# regex for renaming the tensors to their corresponding Keras counterpart
re_repeat = re.compile(r'Repeat_[0-9_]*b')
re_block8 = re.compile(r'Block8_[A-Za-z]')

def get_filename(key):
    filename = str(key)
    filename = filename.replace('/', '_')
    filename = filename.replace('InceptionResnetV1_', '')

    # remove "Repeat" scope from filename
    filename = re_repeat.sub('B', filename)

    if re_block8.match(filename):
        # the last block8 has different name with the previous 5 occurrences
        filename = filename.replace('Block8', 'Block8_6')

    # from TF to Keras naming
    filename = filename.replace('_weights', '_kernel')
    filename = filename.replace('_biases', '_bias')

    return filename + '.npy'


def extract_tensors_from_checkpoint_file(filename, output_folder):
    reader = tf.train.NewCheckpointReader(filename)

    for key in reader.get_variable_to_shape_map():
        # not saving the following tensors
        if key == 'global_step':
            continue
        if 'AuxLogit' in key:
            continue

        # convert tensor name into the corresponding Keras layer weight name and save
        path = os.path.join(output_folder, get_filename(key))
        arr = reader.get_tensor(key)
        np.save(path, arr)


extract_tensors_from_checkpoint_file(tf_model_dir+'model-20190727-181532.ckpt-19153', npy_weights_dir)

model = InceptionResNetV1()

print('Loading numpy weights from', npy_weights_dir)
for layer in model.layers:
    if layer.weights:
        weights = []
        for w in layer.weights:
            weight_name = os.path.basename(w.name).replace(':0', '')
            weight_file = layer.name + '_' + weight_name + '.npy'
            weight_arr = np.load(os.path.join(npy_weights_dir, weight_file))
            weights.append(weight_arr)
        layer.set_weights(weights)

print('Saving weights...')
model.save_weights(os.path.join(weights_dir, weights_filename))
print('Saving model...')
model.save(os.path.join(model_dir, model_filename))


model.summary()


tf_to_keras.ipynb

109.97 KB, 阅读权限: 188, 下载次数: 5

让天下人人学会人工智能!人工智能的前景一片大好!
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|小黑屋|人工智能工程师的摇篮 ( 湘ICP备2020019608号-1 )

GMT+8, 2024-3-28 22:41 , Processed in 0.186798 second(s), 22 queries .

Powered by Discuz! X3.4

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表