2018-03-11-How to run the trained model from Keras+Linux in C#+Windows

The problem encountered is that the company needs to make online predictions of the trained model, which i trained with Linux & Keras. In order to make a faster calibration, the original image from the fisheye camera will be calibrated and prepossessed on the Halcon software, which must be called in Windows platform.
The C# interface should be designed to connect Halcon (Calibration & Image Preprocessing), axis motor and the network.
Now it is necessary to add the trained model to the C# interface.
reference,Tensorflow win10 c++ run trained model from python

It is mainly divided into the following three steps.

1.formerly the library function of Keras model.save(filepath) be used to save the model。now the model should be saved as model of Tensorflow。

2.change the variables of the model into constants,for example use “freeze graph” to export the model as a file, so that we can call the model in c++。

3.Load trained tensorflow model in windows environment using tensorflow's c++ interface。


Solution of 1.

Referencekeras with tensorflow Hybrid Programming


import tensorflow as tf
from keras import backend as K
from keras.layers import Dense
from keras.objectives import categorical_crossentropy
from keras.metrics import categorical_accuracy as accuracy
from tensorflow.examples.tutorials.mnist import input_data

sess = tf.Session()

K.set_session(sess) 

#Create a TensorFlow session and sign up for Keras.



with tf.name_scope('input'):

    # this place holder is the same with input layer in keras    
    img = tf.placeholder(tf.float32, shape=(None, 784))

    labels = tf.placeholder(tf.float32, shape=(None, 10))

mnist_data = input_data.read_data_sets('MNIST_data', one_hot=True)
def feed_dict(train):    
if train:

        xs, ys = mnist_data.train.next_batch(50)

    else:

        xs, ys = mnist_data.test.images, mnist_data.test.labels
#not suit for my case, input should be changed as keras input

    return {img:xs, labels:ys}# keras layers can be called on tensorflow tensors
with tf.name_scope('NN'):
    #before we call the keras function, we should add with tf.name_scope

    x = Dense(128, activation='relu')(img)

    x = Dense(128, activation='relu')(x)

    preds = Dense(10, activation='softmax')(x)

with tf.name_scope('loss'):

    loss = tf.reduce_mean(categorical_crossentropy(labels, preds))

# do it in master thesis!
writer = tf.summary.FileWriter('./keras_tensorflow_log/')

outloss = tf.summary.scalar('loss', loss)

merged = tf.summary.merge([outloss])with tf.name_scope('train'):

    train_step = tf.train.GradientDescentOptimizer(0.5).minimize(loss)

# initialize all variables

init_op = tf.global_variables_initializer()

sess.run(init_op)with sess.as_default():

    for i in range(1000):

        summary, loss = sess.run([merged, train_step],

                feed_dict=feed_dict(True))

        writer.add_summary(summary, global_step=i)

writer.close() 

reference githubdirect export keras into tensorflow
save keras model as Binary model of tensorflow
best way!not only convert the weights of keras model, but alsoconvert_variables_to_constants,that means frezze weights。


# coding=utf-8
import sys

from keras.models import load_model
import tensorflow as tf
import os
import os.path as osp
from keras import backend as K


def freeze_session(session, keep_var_names=None, output_names=None, clear_devices=True):
    """
    Freezes the state of a session into a prunned computation graph.

    Creates a new computation graph where variable nodes are replaced by
    constants taking their current value in the session. The new graph will be
    prunned so subgraphs that are not neccesary to compute the requested
    outputs are removed.
    @param session The TensorFlow session to be frozen.
    @param keep_var_names A list of variable names that should not be frozen,
                          or None to freeze all the variables in the graph.
    @param output_names Names of the relevant graph outputs.
    @param clear_devices Remove the device directives from the graph for better portability.
    @return The frozen graph definition.
    """
    from tensorflow.python.framework.graph_util import convert_variables_to_constants
    graph = session.graph
    with graph.as_default():
        freeze_var_names = list(set(v.op.name for v in tf.global_variables()).difference(keep_var_names or []))
        output_names = output_names or []
        output_names += [v.op.name for v in tf.global_variables()]
        input_graph_def = graph.as_graph_def()
        if clear_devices:
            for node in input_graph_def.node:
                node.device = ""
        frozen_graph = convert_variables_to_constants(session, input_graph_def,
                                                      output_names, freeze_var_names)
        return frozen_graph


input_fld = sys.path[0]
weight_file = 'your_model.h5'
output_graph_name = 'tensor_model.pb'

output_fld = input_fld + '/tensorflow_model/'
if not os.path.isdir(output_fld):
    os.mkdir(output_fld)
weight_file_path = osp.join(input_fld, weight_file)

K.set_learning_phase(0)
net_model = load_model(weight_file_path)


print('input is :', net_model.input.name)
print ('output is:', net_model.output.name)

sess = K.get_session()

frozen_graph = freeze_session(K.get_session(), output_names=[net_model.output.op.name])

from tensorflow.python.framework import graph_io

graph_io.write_graph(frozen_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))

Solution of 2.
already found in 1!

Solution of 3.
reference githubinstall tensorflow in windows
at least we need python 3.5 64X or python 3.6 64X in windows
so at first, we need install the python 3.5 + tensorflow (maybe need git in windows)

then we should find a C++ Tensorflow interface or C++ TF API, so that TF model could be called in C++.
to be continued!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,684评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,143评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,214评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,788评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,796评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,665评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,027评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,679评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 41,346评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,664评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,766评论 1 331
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,412评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,015评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,974评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,203评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,073评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,501评论 2 343

推荐阅读更多精彩内容