[英]How to to feed keras pre-trained model to computational graph?
最近,我一直在玩用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 )
所以你想基本上將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函數的一些信息, 請單擊此處。
要查看圖形,您需要使用tensorboard從FileWriter加載文件夾, 如下所示 :
tensorboard --logdir path/to/folder
希望這能提供一些幫助,祝您好運!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.