ckpt2npy和npy2ckpt转换

1、ckpt2npy转换

import tensorflow as tf
import numpy as np
import sys
from model import AlexNetModel


# Edit just these
FILE_PATH = '/Users/dgurkaynak/Projects/marvel-finetuning/training/alexnet_20171125_124517/checkpoint/model_epoch7.ckpt'
NUM_CLASSES = 26
OUTPUT_FILE = 'alexnet_20171125_124517_epoch7.npy'


if __name__ == '__main__':
    x = tf.placeholder(tf.float32, [128, 227, 227, 3])
    model = AlexNetModel(num_classes=NUM_CLASSES)
    model.inference(x)

    saver = tf.train.Saver()
    layers = ['conv1', 'conv2', 'conv3', 'conv4', 'conv5', 'fc6', 'fc7', 'fc8']
    data = {
        'conv1': [],
        'conv2': [],
        'conv3': [],
        'conv4': [],
        'conv5': [],
        'fc6': [],
        'fc7': [],
        'fc8': []
    }

    with tf.Session() as sess:
        saver.restore(sess, FILE_PATH)

        for op_name in layers:
          with tf.variable_scope(op_name, reuse = True):
            biases_variable = tf.get_variable('biases')
            weights_variable = tf.get_variable('weights')
            data[op_name].append(sess.run(biases_variable))
            data[op_name].append(sess.run(weights_variable))

        np.save(OUTPUT_FILE, data)

2、npy2ckpt转换

"""Conversion of the .npy weights into the .ckpt ones.
This script converts the weights of the DeepLab-ResNet model
from the numpy format into the TensorFlow one.
"""

from __future__ import print_function

import argparse
import os

import tensorflow as tf
import numpy as np

from deeplab_resnet import DeepLabResNetModel

SAVE_DIR = './'

def get_arguments():
    """Parse all the arguments provided from the CLI.

    Returns:
      A list of parsed arguments.
    """
    parser = argparse.ArgumentParser(description="NPY to CKPT converter.")
    parser.add_argument("npy_path", type=str,
                        help="Path to the .npy file, which contains the weights.")
    parser.add_argument("--save-dir", type=str, default=SAVE_DIR,
                        help="Where to save the converted .ckpt file.")
    return parser.parse_args()

def save(saver, sess, logdir):
    model_name = 'model.ckpt'
    checkpoint_path = os.path.join(logdir, model_name)

    if not os.path.exists(logdir):
        os.makedirs(logdir)

    saver.save(sess, checkpoint_path, write_meta_graph=False)
    print('The weights have been converted to {}.'.format(checkpoint_path))


def main():
    """Create the model and start the training."""
    args = get_arguments()

    # Default image.
    image_batch = tf.constant(0, tf.float32, shape=[1, 321, 321, 3]) 
    # Create network.
    net = DeepLabResNetModel({'data': image_batch})
    var_list = tf.global_variables()

    # Set up tf session and initialize variables. 
    config = tf.ConfigProto()
    config.gpu_options.allow_growth = True

    with tf.Session(config=config) as sess:
          init = tf.global_variables_initializer()
          sess.run(init)

          # Loading .npy weights.
          net.load(args.npy_path, sess)

          # Saver for converting the loaded weights into .ckpt.
          saver = tf.train.Saver(var_list=var_list, write_version=1)
          save(saver, sess, args.save_dir)

if __name__ == '__main__':
    main()

源码来自:
https://github.com/SamXiaosheng/tensorflow-cnn-finetune/blob/master/alexnet/ckpt2npy.py
https://github.com/DrSleep/tensorflow-deeplab-resnet/blob/master/npy2ckpt.py

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值