• 关于Tensorflow 加载和使用多个模型的方式


      在Tensorflow中,所有操作对象都包装到相应的Session中的,所以想要使用不同的模型就需要将这些模型加载到不同的Session中并在使用的时候申明是哪个Session,从而避免由于Session和想使用的模型不匹配导致的错误。而使用多个graph,就需要为每个graph使用不同的Session,但是每个graph也可以在多个Session中使用,这个时候就需要在每个Session使用的时候明确申明使用的graph。

    g1 = tf.Graph() # 加载到Session 1的graph
    g2 = tf.Graph() # 加载到Session 2的graph
    
    sess1 = tf.Session(graph=g1) # Session1
    sess2 = tf.Session(graph=g2) # Session2
    
    # 加载第一个模型
    with sess1.as_default(): 
        with g1.as_default():
            tf.global_variables_initializer().run()
            model_saver = tf.train.Saver(tf.global_variables())
            model_ckpt = tf.train.get_checkpoint_state(“model1/save/path”)
            model_saver.restore(sess, model_ckpt.model_checkpoint_path)
    # 加载第二个模型
    with sess2.as_default():  # 1
        with g2.as_default():  
            tf.global_variables_initializer().run()
            model_saver = tf.train.Saver(tf.global_variables())
            model_ckpt = tf.train.get_checkpoint_state(“model2/save/path”)
            model_saver.restore(sess, model_ckpt.model_checkpoint_path)
    
    ...
    
    # 使用的时候
    with sess1.as_default():
        with sess1.graph.as_default():  # 2
            ...
    
    with sess2.as_default():
        with sess2.graph.as_default():
            ...
    
    # 关闭sess
    sess1.close()
    sess2.close()
    

    注意事项:

    1、在1处使用as_default使session在离开的时候并不关闭,在后面可以继续使用知道手动关闭;

    2、由于有多个graph,所以sess.graph与tf.get_default_value的值是不相等的,因此在进入sess的时候必须sess.graph.as_default()明确申明sess.graph为当前默认graph,否则就会报错。

    3、不同框架的模型(tf, caffe, torch等)在加载的很有可能导致底层的cuDNN分配出现问题从而报错,这种一般可以尝试通过模型的加载顺序来解决。

     
  • 相关阅读:
    简易总结react-hook三大进阶
    每天25分钟总结(3)
    每天25分钟总结(2)
    PSAM卡与CPU(用户卡)的操作过程
    Flash Media Server 4.5 序列号 (fms4.5 激活码)
    张杰 我在这里 二炮手 插曲 24集 视频截取录制
    Android 模拟器 获得 root权限
    c#编程指南(十) 平台调用P-INVOKE完全掌握, 字符串和指针
    IIS7 php wordpress 中文url 标签tag中文URL404解决方法
    调整win7 Windows7下时间同步的频率时 钟同步间隔
  • 原文地址:https://www.cnblogs.com/llfctt/p/10308525.html
Copyright © 2020-2023  润新知