Tensorflow到Keras:在Keras模型上导入图形def错误

Ann*_*ine 5 python keras tensorflow

我有一个Tensorflow代码用于分类我想要转换为Keras代码的图像.但是我遇到了没有我想要的所有代码的高级API的问题.我一直困扰的问题是:

#net = get_vgg_model() <- got tf.VGG16 model
net = tf.keras.applications.VGG16()


g1 = tf.Graph()
with tf.Session(graph=g1, config=config) as sess, g1.device('/cpu:0'):
    tf.import_graph_def(net['graph_def'], name='vgg')
Run Code Online (Sandbox Code Playgroud)

此代码给出错误:

Traceback (most recent call last):
  File "app.py", line 16, in <module>
    from modules.xvision import Xvision
    File "/app/modules/xvision.py", line 84, in <module>
       tf.import_graph_def(net['graph_def'], name='vgg')
   TypeError: 'Model' object has no attribute '__getitem__'
Run Code Online (Sandbox Code Playgroud)

有人可以帮我这个图吗?

Dan*_*ler 7

获取图表

您可以从Keras获取图表:

import keras.backend as K
K.get_session().graph
Run Code Online (Sandbox Code Playgroud)

您可以将其传递给import_graph_def,但我怀疑它已经是Tensorflow的默认图形,因为在下面的链接中,Keras的创建者说只有一个图形.

更多内容:https://github.com/keras-team/keras/issues/3223

工作建议

我不知道你想要实现什么,但如果这个想法经常使用Keras,你可能永远不需要抓住图表.

在Keras中,一旦您创建了模型net = tf.keras.applications.VGG16(),就可以开始使用此模型中的Keras方法,例如:

#compile for training
net.compile(optimizer=someKerasOptimizer, loss=someKerasLoss, metrics=[m1,m2])

#training
net.fit(trainingInputs, trainingTargets, epochs=..., batch_size=..., ...)    
net.fit_generator(someGeneratorThatLoadsBatches, steps_per_epoch=...., ....)

#predicting
net.predict(inputs)
net.predict_generator(someGeneratorThatLoadsInputImages, steps=howManyBatches)    
Run Code Online (Sandbox Code Playgroud)

访问权重和图层将通过以下方式完成:

layer = net.layers[index]
layer = net.get_layer('layer_name')

weights = layer.get_weights()
layer.set_weights(someWeightsList)

allWeights = net.get_weights()
net.set_weights(listWithAllWeights)
Run Code Online (Sandbox Code Playgroud)