2

我使用 Keras 训练了一个带有 2 层 LSTM 和 dropout 的简单 RNN。我想在 tensorflow C API 中加载 .pb 图并将其用于以后的预测,但我遇到了分段错误。后来我发现如果我保持网络不变,只删除 dropout 选项并重新训练它,那么一切运行正常。但是我想使用带有 Dropout 的那个,因为预测测试数据的准确性更好。有人有建议吗?使用 tensorflow C API 的示例很少。

这是我遇到分段错误的地方:

TF_SessionRun(session, NULL,
                  &inputs[0], &input_values[0], static_cast<int>(inputs.size()),
                  &outputs[0], &output_values[0], static_cast<int>(outputs.size()),
                  NULL, 0, NULL, status);
    // Assign the values from the output tensor to a variable and iterate over them
    ASSERT(!output_values.empty());
float* out_vals = static_cast<float*>(TF_TensorData(output_values[0]));

顺便说一句,我使用网站上的以下代码将 Keras 中的 .mdl 更改为 tensorflow 中的 .pb。将 tensorflow 导入为 tf 导入 sys 将 numpy 导入为 np

# Create function to convert saved keras model to tensorflow graph
def convert_to_pb(weight_file,input_fld='',output_fld=''):

    import os
    import os.path as osp
    from tensorflow.python.framework import graph_util
    from tensorflow.python.framework import graph_io
    from keras.models import load_model
    from keras import backend as K


    # weight_file is a .h5 keras model file
    output_node_names_of_input_network = ["pred0"]
    output_node_names_of_final_network = 'output_node'

    # change filename to a .pb tensorflow file
    output_graph_name = weight_file[:-3]+'pb'
    weight_file_path = osp.join(input_fld, weight_file)

    net_model = load_model(weight_file_path)

    num_output = len(output_node_names_of_input_network)
    pred = [None]*num_output
    pred_node_names = [None]*num_output

    for i in range(num_output):
        pred_node_names[i] = output_node_names_of_final_network+str(i)
        pred[i] = tf.identity(net_model.output[i], name=pred_node_names[i])
    print('output nodes names are: ', pred_node_names)
    sess = K.get_session()

    constant_graph = graph_util.convert_variables_to_constants(sess, sess.graph.as_graph_def(), pred_node_names)
    graph_io.write_graph(constant_graph, output_fld, output_graph_name, as_text=False)
    print('saved the constant graph (ready for inference) at: ', osp.join(output_fld, output_graph_name))

    return output_fld+output_graph_name

tfpath = convert_to_pb(sys.argv[1],'./','./')
print 'tfpath: ', tfpath

然后

4

0 回答 0