简体   繁体   English

如何获取/定义我的图形的输入 output 名称或以正确的形式冻结它

[英]How can i obtain/define input output names of my graph or freeze it in proper form

Hi everyone we have been trying to save our model in.bytes format so that we can use it in a c# script.大家好,我们一直在尝试以字节格式保存我们的 model,以便我们可以在 c# 脚本中使用它。 We are using tensorflow 1.7.0 Here is our model:我们正在使用 tensorflow 1.7.0 这是我们的 model:

bsize=16


# define cnn model
def define_model():
    # load model
    model = VGG16(include_top=False, input_shape=(224, 224, 3))
    # mark loaded layers as not trainable
    for layer in model.layers:
        layer.trainable = False
    # add new classifier layers
    flat1 = Flatten()(model.layers[-1].output)
    class1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)
    output = Dense(2, activation='softmax')(class1)
    # define new model
    model = Model(inputs=model.inputs, outputs=output)
    # compile model
    # compile model
    opt = Adam(lr=0.001)
    model.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy'])
    return model

Training:训练:

sess=tf.Session()
tf.global_variables_initializer().run(session=sess)
model = define_model()
# create data generator
datagen = ImageDataGenerator(rescale=1.0/255.0)
# prepare iterators
train_it = datagen.flow_from_directory(mpath+'/train',
class_mode='categorical', batch_size=bsize, target_size=(224, 224))
test_it = datagen.flow_from_directory(mpath+'/test',
class_mode='categorical', batch_size=bsize, target_size=(224, 224))
# fit model
history = model.fit_generator(train_it, steps_per_epoch=len(train_it),
validation_data=test_it, validation_steps=len(test_it), epochs=1, verbose=0)
# evaluate model
_, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=0)
print('> %.3f' % (acc * 100.0))

model.save_weights("weights.h5")

Freeze:冻结:

K.clear_session()
K.set_learning_phase(0)
model = define_model()
model.load_weights("weights.h5")

save_dir = "./out"


tf.saved_model.simple_save(K.get_session(),
                           save_dir,
                           inputs={"input": model.inputs[0]},
                           outputs={"output": model.outputs[0]})

freeze_graph.freeze_graph(None,
                          None,
                          None,
                          None,
                          model.outputs[0].op.name,
                          None,
                          None,
                          os.path.join(save_dir, "frozen_model.bytes"),
                          False,
                          "",
                          input_saved_model_dir=save_dir)

Then we try to see input and output names using:然后我们尝试使用以下命令查看输入和 output 名称:

    model.inputs[0].name
    model.ouputs[0].name

Finally we would like to use this graph in c# as:最后我们想在 c# 中使用这个图:

.AddInput(graph["input_1_1:0"][0], tensor).Fetch(graph["output"][0]);

However, as we understand from the error input and output names are wrong.但是,正如我们从错误输入中了解到的那样,output 名称是错误的。 Moreover whenever we call此外,每当我们调用

model.inputs[0].name
model.ouputs[0].name

they print different input and output names even if we define output name as name="output"即使我们将 output 名称定义为 name="output",它们也会打印不同的输入和 output 名称

Do you have any suggestions about how to freeze this model, obtain input and output names etc您对如何冻结此 model、获取输入和 output 名称等有任何建议吗

regards问候

How about this:这个怎么样:

my_input = tf.keras.layers.Input(shape=[224,224,3], name="my_input")
vgg = tf.keras.applications.VGG16(input_tensor=my_input)
my_output = tf.identity(vgg.output, name="my_output")

Now you know the names of your input and output tensors:现在您知道输入和 output 张量的名称:

In [0]: my_input                                                                                                                                                                    
Out[0]: <tf.Tensor 'my_input:0' shape=(?, 224, 224, 3) dtype=float32>

In [1]: my_output                                                                                                                                                                   
Out[1]: <tf.Tensor 'my_output:0' shape=(?, 1000) dtype=float32>

For those having similar issues:对于那些有类似问题的人:

model.inputs[0].name
model.ouputs[0].name

yield sth like this:产生这样的东西:

input_1:0
dense_2/Softmax:0

but you shouldnt use them directly in.AddInput so instead of:但你不应该直接在.AddInput 中使用它们,而不是:

.AddInput(graph["input_1:0"][0], tensor).Fetch(graph[dense_2/Softmax:0][0]);

do it this way:这样做:

.AddInput(graph["input_1"][0], tensor).Fetch(graph[dense_2/Softmax][0]);

So the code above actually works just omit the:0 part from the name strings and thats all:D所以上面的代码实际上只是从名称字符串中省略了:0 部分,仅此而已:D

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM