Skip to main content
 首页 » 编程设计

python之TensorFlow:创建一个图的近似副本作为原始图的扩展来测试验证数据集是否会消耗大量内存

2025年02月15日26zhujiabin

意思是说我最初是否在我的图中有以下用于训练目的的操作:

with tf.Graph.as_default() as g: 
  images, labels = load_batch(...) 
  with slim.argscope(...): 
    logits, end_points = inceptionResnetV2(images, num_classes..., is_training = True) 
 
  loss = slim.losses.softmax_cross_entropy(logits, labels) 
 
  optimizer = tf.train.AdamOptimizer(learning_rate = 0.002) 
 
  train_op = slim.learning.create_train_op(loss, optimizer) 
 
  sv = tf.train.Supervisor(...) 
 
  with sv.managed_session() as sess: 
    #perform your regular training loop here with sess.run(train_op) 

这让我可以很好地训练我的模型,但我想运行一个小型验证数据集,每隔一段时间在我的 sess 中评估我的模型,这会占用太多内存吗在同一张图中使用几乎完全相同的副本,例如:

images_val, labels_val = load_batch(...) 
with slim.argscope(...): 
  logits_val, end_points_val = inceptionResnetV2(images, num_classes..., is_training = False) 
 
  predictions = end_points_val['Predictions'] 
 
  acc, acc_updates = tf.contrib.metrics.streaming_accuracy(predictions, labels_val) 
 
  #and then following this, we can run acc_updates in a session to update the accuracy, which we can then print to monitor 

我担心的是,为了评估我的验证数据集,我需要将 is_training 参数设置为 False 以便我可以禁用 dropout。但是从头开始创建整个 inception-resnet-v2 模型只是为了在同一个图中进行验证会消耗太多内存吗?还是我应该创建一个全新的文件来自行运行验证?

理想情况下,我想要 3 种数据集 - 训练数据集、训练期间测试的小型验证数据集和最终评估数据集。这个小型验证数据集将帮助我查看我的模型是否过度拟合训练数据。但是,如果我提出的想法消耗太多内存,是否相当于只是偶尔监控训练数据得分?在训练时测试验证集是否有更好的想法?

请您参考如下方法:

TensorFlow 的开发人员考虑了这一点,并准备好共享变量。 可以看到here the doc .

以正确的方式使用作用域可以重用一些变量。 一个很好的例子(上下文是语言模型但没关系)是 TensorFlow PTB Word LM .

这种方法的全局伪代码是这样的:

class Model: 
  def __init__(self, train=True, params): 
  """ Build the model """ 
 
  tf.placeholder( ... )  
 
  tf.get_variable( ...)  
 
 
 
def main(_): 
  with tf.Graph.as_default() as g: 
    with tf.name_scope("Train"): 
      with tf.variable_scope("Model", reuse=None): 
        train = Model(train=True, params )  
    with tf.name_scope("Valid"): 
      # Now reuse variables = no memory cost 
      with tf.variable_scope("Model", reuse=True): 
        # But you can set different parameters 
        valid = Model(train=False, params) 
 
    session = tf.Session 
    ... 

因此您可以共享一些变量而无需完全相同的模型,因为参数可能会改变模型本身。

希望对你有帮助
pltrdy