1.保存变量

先创建(在tf.Session()之前)saver

saver = tf.train.Saver(tf.global_variables(),max_to_keep=1)  #max_to_keep这个保证只保存最后一次training的训练数据

然后在训练的循环里面

checkpoint_path = os.path.join(Path, 'model.ckpt') saver.save(session, checkpoint_path, global_step=step) #这里的step是循环训练的次数,也就是第几次迭代

以下保存的变量文件

2.变量读取

1.若要直接恢复所有变量可以

saver = tf.train.Saver(tf.global_variables())
moudke_file=tf.train.latest_checkpoint('PATH')
saver.restore(sess,moudke_file)

PATH是存放保存变量的路径,会自动找到最近保存的变量文件

2 若想读取其中一部分变量值

def read_checkpoint():
  w = []
  checkpoint_path = '/home/ximao/models/resnet3/variable_logs/model.ckpt-17000'
  reader = tf.train.NewCheckpointReader(checkpoint_path)
  var = reader.get_variable_to_shape_map()
  for key in var:
    if 'weights' in key and 'conv' in key and 'Mo' not in key:
      print('tensorname:', key)
  #   # print(reader.get_tensor(key))

3. 若想恢复其中一部分变量值到新网络

(1)首先你要先获取你想要赋值新网络变量的变量名,这里变量名不是一个字符串,而是<name,shape,dtype>这样的一个结构,

然后把你要赋值的元素转为张量,最后把值赋给你得到变量名 如下:

var=[v for v in weight_pruned if v.op.name=='WRN/conv1/weights']
conv1_temp=tf.convert_to_tensor(conv1,dtype=tf.float32)
sess.run(tf.assign(var[0],conv1_temp))

weight_pruned 存放的是你新网络中所有的变量