zoukankan      html  css  js  c++  java
  • Tensorflow 模型保存和加载

    原文链接:http://cv-tricks.com/tensorflow-tutorial/save-restore-tensorflow-models-quick-complete-tutorial/

    什么是tensorflow model

    模型训练完毕之后,你可能需要在产品上使用它。那么tensorflow model是什么?tensorflow模型主要包含网络的结构的定义或者叫graph和训练好的网络结构里的参数。因此tensorflow model包含2个文件

    a)Meta graph:

    使用protocol buffer来保存整个tensorflow graph.例如所有的variables, operations, collections等等。这个文件使用.meta后缀

    b) Checkpoint file:

    二进制文件包含所有的weights,biases,gradients和其他variables的值。这个文件使用.ckpt后缀,有2个文件:

    mymodel.data-00000-of-00001
    mymodel.index

    .data文件就是保存训练的variables我们将要使用它。

    和这些文件一起,tensorflow还有一个文件叫checkpoint用来简单保存最近一次保存checkpoint文件的记录。

    所以,总结起来就是 tensorflow models 对于版本0.11以上看起来是这样:

    -rw-rw-r-- 1 yyai yyai 88102292  6月  8 22:36 model.ckpt-50.data-00001-of-00002
    -rw-rw-r-- 1 yyai yyai     1614  6月  8 22:36 model.ckpt-50.index
    -rw-rw-r-- 1 yyai yyai  2208508  6月  8 22:36 model.ckpt-50.meta
    -rw-rw-r-- 1 yyai yyai      255  6月  8 22:36 checkpoint

    现在我们知道一个tensorflow model的样子,可以看怎样保存模型。

    保存模型

    假设你训练一个卷积网络来做图片分类。通常你可以观察loss和accuracy值。当你观察到网络已经收敛,你可以手动停止训练或者你可以等到设定的epochs值跑完。 训练完毕以后,你希望保存所有的variables和network graph以便将来使用。如果你希望保存graph和所有parameters的值,可以使用tensorflow,来创建一个tf.train.Saver()的实例 saver = tf.train.Saver()

    记住tensorflow里的variables在session才存活,所有,你需要在session里保存model,使用刚刚创建的saver对象里的save 方法。

    saver.save(sees, ‘my-test-model’)

    这里,sess就是session对象,’my-test-model’就是你给你的model起的名字,我们来看一个完整的样子:

    import tensorflow as tf
    w1 = tf.Variable(tf.random_normal(shape=[2]), name='w1')
    w2 = tf.Variable(tf.random_normal(shape=[5]), name='w2')
    saver = tf.train.Saver()
    sess = tf.Session()
    sess.run(tf.global_variables_initializer())
    saver.save(sess, 'my_test_model')
    
    # This will save following files in Tensorflow v >= 0.11
    # my_test_model.data-00000-of-00001
    # my_test_model.index
    # my_test_model.meta
    # checkpoint

    如果我们想要每1000个iteration保存一次model,可以使用save方法给他传递一个步长:

    saver.save(sess, 'my_test_model',global_step=1000)

    它将会在model名称的后面加上’-1000’,例如下面文件:

    my_test_model-1000.index
    my_test_model-1000.meta
    my_test_model-1000.data-00000-of-00001
    checkpoint

    如果,我们每1000个iteration保存一次model,但是.meta文件只在第一次创建也就是第1000个iteration并且我们不需要每次都重新创建.meta文件。我们只需每次保存model,graph不会有变化。因此,当我们不需要写meta-graph文件时可以这样做:

    saver.save(sess, 'my-model', global_step=step,write_meta_graph=False)

    如果我们只是想保存4个最近的model并且当训练2小时之后想要保存一个model,我们可以使用maxtokeep和keepcheckpointeverynhours例如:

    #saves a model every 2 hours and maximum 4 latest models are saved.
    saver = tf.train.Saver(max_to_keep=4, keep_checkpoint_every_n_hours=2)

    注意,如果我们没有在tr.tran.Saver()的参数里指定任何值,它将会保存所有的variables。要是我们不想保存所有variables而只想保存其中的一些改怎么办呢。我们而已指定想要保存的variables/collections。当创建tf.train.Saver实例,我们传递一个想要保存的variables字典或者列表参数给它。例如:

    import tensorflow as tf
    w1 = tf.Variable(tf.random_normal(shape=[2]), name='w1')
    w2 = tf.Variable(tf.random_normal(shape=[5]), name='w2')
    saver = tf.train.Saver([w1,w2])
    sess = tf.Session()
    sess.run(tf.global_variables_initializer())
    saver.save(sess, 'my_test_model',global_step=1000)

    Importing 一个 pre-trained model

    如果你想使用别人的pre-trained model 来 fine-tuning, 有2件事你可以需要做:

    a) 创建network:

    你可以写python代码来创建network的每一个和每一层model,然后,想想你会发现,我们已经保存了network在.metafile里,我们可以使用tf.train.import()函数来重新创建network例如:saver = tf.train.importmetagraph('mytestmodel-1000.meta')

    记住,importmetagraph 附加上了.meta文件里之前定义的network到当前的graph里。所以,这样会为你创建graph/network,但是我们还是需要在当前的graph里加载之前训练好的paramters的值

    b)加载parameters: 我们可以恢复network里的parameters,值需要调用saver里restore函数

    with tf.Session() as sess:
      new_saver = tf.train.import_meta_graph('my_test_model-1000.meta')
      new_saver.restore(sess, tf.train.latest_checkpoint('./‘))

    然后,tensors的值 比如w1和w2就被加载了并且可以被访问到:

    with tf.Session() as sess:    
        saver = tf.train.import_meta_graph('my-model-1000.meta')
        saver.restore(sess,tf.train.latest_checkpoint('./'))
        print(sess.run('w1:0'))
    ##Model has been restored. Above statement will print the saved value of w1.

    4 恢复models来工作

    下面给出一个实际的列子,创建一个小的network 使用placeholders并且保存它,注意network被保存的时候,placeholders的值不会被保存:

    import tensorflow as tf
    
    #Prepare to feed input, i.e. feed_dict and placeholders
    w1 = tf.placeholder("float", name="w1")
    w2 = tf.placeholder("float", name="w2")
    b1= tf.Variable(2.0,name="bias")
    feed_dict ={w1:4,w2:8}
    
    #Define a test operation that we will restore
    w3 = tf.add(w1,w2)
    w4 = tf.multiply(w3,b1,name="op_to_restore")
    sess = tf.Session()
    sess.run(tf.global_variables_initializer())
    
    #Create a saver object which will save all the variables
    saver = tf.train.Saver()
    
    #Run the operation by feeding input
    print sess.run(w4,feed_dict)
    #Prints 24 which is sum of (w1+w2)*b1 
    
    #Now, save the graph
    saver.save(sess, 'my_test_model',global_step=1000)

    现在,当我们想要恢复model的时候, 我们不仅需要恢复graph和weights, 还需准备新的feeddict作为训练数据给到network.我们可以。我们可以使用graph.gettensorbyname()方法 来获取保存的operations和placeholder variables

    #How to access saved variable/Tensor/placeholders 
    w1 = graph.get_tensor_by_name("w1:0")
    
    ## How to access saved operation
    op_to_restore = graph.get_tensor_by_name("op_to_restore:0")

    如果我们只是想使用不通的数据来运行同样的网络,可以简单地通过feed_dict向network输入新数据

    import tensorflow as tf
    
    sess=tf.Session()    
    #First let's load meta graph and restore weights
    saver = tf.train.import_meta_graph('my_test_model-1000.meta')
    saver.restore(sess,tf.train.latest_checkpoint('./'))
    
    
    # Now, let's access and create placeholders variables and
    # create feed-dict to feed new data
    
    graph = tf.get_default_graph()
    w1 = graph.get_tensor_by_name("w1:0")
    w2 = graph.get_tensor_by_name("w2:0")
    feed_dict ={w1:13.0,w2:17.0}
    
    #Now, access the op that you want to run. 
    op_to_restore = graph.get_tensor_by_name("op_to_restore:0")
    
    print sess.run(op_to_restore,feed_dict)
    #This will print 60 which is calculated 
    #using new values of w1 and w2 and saved value of b1.   

    如果你想要在graph里添加更多的operations来增加更多的layers然后再训练它,你可以这样做:

    import tensorflow as tf
    
    sess=tf.Session()    
    #First let's load meta graph and restore weights
    saver = tf.train.import_meta_graph('my_test_model-1000.meta')
    saver.restore(sess,tf.train.latest_checkpoint('./'))
    
    
    # Now, let's access and create placeholders variables and
    # create feed-dict to feed new data
    
    graph = tf.get_default_graph()
    w1 = graph.get_tensor_by_name("w1:0")
    w2 = graph.get_tensor_by_name("w2:0")
    feed_dict ={w1:13.0,w2:17.0}
    
    #Now, access the op that you want to run. 
    op_to_restore = graph.get_tensor_by_name("op_to_restore:0")
    
    #Add more to the current graph
    add_on_op = tf.multiply(op_to_restore,2)
    
    print sess.run(add_on_op,feed_dict)
    #This will print 120.

    你也可以只使用之前训练好的网络里的一部分内容。例如这里,我们加载一个vgg pre-trained network 使用meta graph并且在最后一个层改变输出的个数为2来使用新数据进行fine-tuning 

    ......
    ......
    saver = tf.train.import_meta_graph('vgg.meta')
    # Access the graph
    graph = tf.get_default_graph()
    ## Prepare the feed_dict for feeding data for fine-tuning 
    
    #Access the appropriate output for fine-tuning
    fc7= graph.get_tensor_by_name('fc7:0')
    
    #use this if you only want to change gradients of the last layer
    fc7 = tf.stop_gradient(fc7) # It's an identity function
    fc7_shape= fc7.get_shape().as_list()
    
    new_outputs=2
    weights = tf.Variable(tf.truncated_normal([fc7_shape[3], num_outputs], stddev=0.05))
    biases = tf.Variable(tf.constant(0.05, shape=[num_outputs]))
    output = tf.matmul(fc7, weights) + biases
    pred = tf.nn.softmax(output)
    
    # Now, you run this with fine-tuning data in sess.run()
  • 相关阅读:
    python实战===用python调用jar包
    Django连接数据库写入数据报错
    Niginx主配置文件参数详解
    uwsgi参数详解
    JSON序列化和反序列化
    ServiceBroker创建流程
    WCF和WebService中获取当前请求报文的方法
    python 关于文件的操作
    关于函数对象的理解
    python,关于用户登录与注册问题
  • 原文地址:https://www.cnblogs.com/azheng333/p/6972619.html
Copyright © 2011-2022 走看看