将tensorflow的ckpt模型存储为npy的实例

yipeiwu_com6年前Python基础

实例如下所示:

#coding=gbk
import numpy as np
import tensorflow as tf
from tensorflow.python import pywrap_tensorflow

checkpoint_path='model.ckpt-5000'#your ckpt path
reader=pywrap_tensorflow.NewCheckpointReader(checkpoint_path)
var_to_shape_map=reader.get_variable_to_shape_map()

alexnet={}
alexnet_layer = ['conv1','conv2','conv3','conv4','conv5','fc6','fc7','fc8']
add_info = ['weights','biases']

alexnet={'conv1':[[],[]],'conv2':[[],[]],'conv3':[[],[]],'conv4':[[],[]],'conv5':[[],[]],'fc6':[[],[]],'fc7':[[],[]],'fc8':[[],[]]}


for key in var_to_shape_map:
 #print ("tensor_name",key)

 str_name = key
 # 因为模型使用Adam算法优化的,在生成的ckpt中,有Adam后缀的tensor
 if str_name.find('Adam') > -1:
  continue

 print('tensor_name:' , str_name)

 if str_name.find('/') > -1:
  names = str_name.split('/')
  # first layer name and weight, bias
  layer_name = names[0]
  layer_add_info = names[1]
 else:
  layer_name = str_name
  layer_add_info = None

 if layer_add_info == 'weights':
  alexnet[layer_name][0]=reader.get_tensor(key)
 elif layer_add_info == 'biases':
  alexnet[layer_name][1] = reader.get_tensor(key)
 else:
  alexnet[layer_name] = reader.get_tensor(key)

# save npy
np.save('alexnet_pointing04.npy',alexnet)
print('save npy over...')
#print(alexnet['conv1'][0].shape)
#print(alexnet['conv1'][1].shape)

以上这篇将tensorflow的ckpt模型存储为npy的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

pytorch 在sequential中使用view来reshape的例子

pytorch中view是tensor方法,然而在sequential中包装的是nn.module的子类, 因此需要自己定义一个方法: import torch.nn as nn c...

详解python中executemany和序列的使用方法

详解python中executemany和序列的使用方法 一 代码 import sqlite3 persons=[ ("Jim","Green"), ("Hu","...

对Python3中dict.keys()转换成list类型的方法详解

对Python3中dict.keys()转换成list类型的方法详解

在python3中使用dict.keys()返回的不在是list类型了,也不支持索引,我们可以看一下下面这张图片 那么我们应该怎么办呢,其实解决的方法也是非常简单的,只需要使用list...

python自定义时钟类、定时任务类

这是我使用python写的第一个类(也算是学习面向对象语言以来正式写的第一个解耦的类),记录下改进的过程。 分析需求 最初,因为使用time模块显示日期时,每次都要设置时间字符串的格式,...

Python中使用wxPython开发的一个简易笔记本程序实例

Python中使用wxPython开发的一个简易笔记本程序实例

一、简介 wxPython是Python语言的一套优秀的GUI图形库,允许Python程序员很方便的创建完整的、功能键全的GUI用户界面。 wxPython是作为优秀的跨平台GUI库wx...