最近,我一直在玩用TF Keras编写的CNN。不幸的是,我在这里遇到了一个问题:
在这些宏伟的教程中 (https://github.com/Hvass-Labs/TensorFlow-Tutorials/blob/master/vgg16.py;其余代码在这里), 我强烈建议,大师以非常非常丑陋的方式加载预先训练的vgg16.tfmodel。
def __init__(self):
# Now load the model from file. The way TensorFlow
# does this is confusing and requires several steps.
# Create a new TensorFlow computational graph.
self.graph = tf.Graph()
# Set the new graph as the default.
with self.graph.as_default():
# TensorFlow graphs are saved to disk as so-called Protocol Buffers
# aka. proto-bufs which is a file-format that works on multiple
# platforms. In this case it is saved as a binary file.
# Open the graph-def file for binary reading.
path = os.path.join(data_dir, path_graph_def)
with tf.gfile.FastGFile(path, 'rb') as file:
# The graph-def is a saved copy of a TensorFlow graph.
# First we need to create an empty graph-def.
graph_def = tf.GraphDef()
# Then we load the proto-buf file into the graph-def.
graph_def.ParseFromString(file.read())
# Finally we import the graph-def to the default TensorFlow graph.
tf.import_graph_def(graph_def, name='')
# Now self.graph holds the VGG16 model from the proto-buf file.
# Get a reference to the tensor for inputting images to the graph.
self.input = self.graph.get_tensor_by_name(self.tensor_name_input_image)
# Get references to the tensors for the commonly used layers.
self.layer_tensors = [self.graph.get_tensor_by_name(name + ":0") for name in self.layer_names]
问题是-我希望以相同/相似的方式加载我自己的预训练模型,因此我可以将模型放入我稍后要调用的类的图形中,如果可能,获取模型的最后几行代码在这里正常工作。(意味着从图中获取所需层的张量。)
我所有基于keras和comp导入的 load_model 的尝试。图使我失败。另外,我也不想以完全不同的方式加载它,因为以后我不得不更改很多代码-对于一个新手来说是一个大问题。
好吧,我希望这个问题能找到合适的人,而且对您来说,这不是一件小事:D。
顺便说一句:我要解决的复杂问题,就是要在同一github存储库中进行样式转换,以便为您制作照片。 (https://github.com/Hvass-Labs/TensorFlow-Tutorials/blob/master/15_Style_Transfer.ipynb)
答案 0 :(得分:0)
所以您想基本上将keras模型加载到tensorflow中?可以使用以下代码轻松完成:
import keras.backend as k
from keras.models import load_model
import tensorflow as tf
model = load_model("your model.h5") # now it's in the memory of keras
with k.get_session() as sess:
# here you have a tensorflow computational graph, view it by:
tf.summary.FileWriter("folder name", sess.graph)
# if you need a certain tensor do:
sess.graph.get_tensor_by_name("tensor name")
要稍微了解一下get_session函数,click here
要查看图形,您需要使用tensorboard like this从FileWriter加载文件夹:
tensorboard --logdir path/to/folder
希望这可以提供一些帮助,祝您好运!