tensorflow之inception_v3模型的部分加载及权重的部分恢复(23)---《深度学习》

大家都知道,在加载模型及对应的权重进行训练的时候,我们可以整个使用所提供的模型,但是有时候呢?所提供的模型不能很好的满足我们的要求,有时候我们只需要模型的前几层然后进行对应的权重赋值,这时候,我们应该怎么办呢?tensorflow为我们提供了两种方法(探索了好久才找到解决办法,不过感觉蛮有用的,分享给大家啦!):

1)在加载模型的时候,使用final_endpoint参数,指定模型阶段点:

import tensorflow.contrib.slim.nets as nets
#from tensorflow.contrib.slim.nets.inception import inception_v3, inception_v3_arg_scope
import numpy as np
import os

height = 299
width = 299
channels = 3
num_classes=1001

X = tf.placeholder(tf.float32, shape=[None, height, width, channels])
y = tf.placeholder(tf.float32,shape=[None,182])
with slim.arg_scope(nets.inception.inception_v3_arg_scope()):
    logits, end_points = nets.inception.inception_v3_base(X,final_endpoint = "Mixed_7a")
    variables_to_restore=slim.get_variables_to_restore()

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    saver=tf.train.Saver(variables_to_restore)
    saver.restore(sess,os.path.join("E:\\","inception_v3.ckpt"))
    print("Done")

2)在恢复模型的时候,部分层不使用ckpt文件中提供的参数:

#-*-coding=utf-8-*-
import tensorflow as tf
import tensorflow.contrib.slim as slim
import tensorflow.contrib.slim.nets as nets
#from tensorflow.contrib.slim.nets.inception import inception_v3, inception_v3_arg_scope
import numpy as np
import os

height = 299
width = 299
channels = 3
num_classes=1001

X = tf.placeholder(tf.float32, shape=[None, height, width, channels])
y = tf.placeholder(tf.float32,shape=[None,182])
with slim.arg_scope(nets.inception.inception_v3_arg_scope()):
    logits, end_points = nets.inception.inception_v3(X, num_classes=num_classes,is_training=False)
with tf.Session() as sess:
    exclude=['Mixed_7c','Mixed_7b','AuxLogits','AuxLogits','Logits','Predictions']
    variables_to_restore=slim.get_variables_to_restore(exclude=exclude)
    sess.run(tf.global_variables_initializer())
    saver=tf.train.Saver(variables_to_restore)
    saver.restore(sess,os.path.join("E:\\","inception_v3.ckpt"))
    print("Done")

需要的inception_v3.ckpt
参考:tensorflow选择性读取权重

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值