【问题标题】:Logging tf.variable during custom training loop在自定义训练循环期间记录 tf.variable
【发布时间】:2020-06-04 17:59:31
【问题描述】:

我在 TensorFlow 中为 TD(Lambda) 编写了一个自定义训练循环,我想创建一个日志来存储在每个 epoch 期间计算的一​​些变量。

在 numpy 中,我会写类似 list.append(variable_that_I_want_to_save) 在每个纪元结束时

但是在 tf eager execution 中这是不可能的。

如何保存 tf.function 中的 tf.Variable 在迭代期间采用的值?

非常感谢您的回复 - 我想这一定是一件非常微不足道的事情。

PS: 我应该补充一点,训练发生在一个类中,所以 tf.concat 不能解决问题,因为我无法将连接的张量重复分配给 training_loop 类的实例变量......

这是我所做的伪代码:

class Trainer:
   def __init__(self, model):
      self.model = model

   def train(xs,ys,lambda):
      for x,y in zip(xs,ys):
         learn(x,y,lambda)

   def learn(x,y,lambda):
      err = y - self.model(x)
      model.apply_weights( grad(err) * self.custom_alpha( self.model.weights )

   def custom_optimizer(  weights ):
      x = some operations with weights 
      alpha = some operation with x
      return alpha

由于保密协议,我无法分享更具体的信息,但我想记录的是 x 采用的值

【问题讨论】:

  • 请添加自定义训练循环的代码
  • 嗨,基本上,培训班是这样的:

标签: python tensorflow machine-learning logging


【解决方案1】:

这样的东西对你有用吗? 我已向将存储日志的类添加了一个属性。

class Trainer:
    def __init__(self, model):
        self.model = model
        self.log_variable = []

    def train(self, xs, ys, lambda):
        for x,y in zip(xs,ys):
            v = learn(x,y,lambda)
            self.log_variable.append(v.numpy())

    @tf.function
    def learn(self, x, y, lambda):
        err = y - self.model(x)
        model.apply_weights( grad(err) * self.custom_alpha( self.model.weights )
        return variable_that_I_want_to_save

    def custom_optimizer( weights ):
        x = some operations with weights 
        alpha = some operation with x
        return alpha

    def get_log(self):
        return self.log_variable

trainer = Trainer(model)
trainer.train(xs, ys, lambda)
log = trainer.log_variable()

【讨论】:

  • 您好,感谢您的回复,很抱歉延迟回复。我也有类似的想法,但似乎 .numpy() 属性在急切执行中不可用。我收到此错误消息: AttributeError: in user code: learn_sequence * alphas, mask = self.optimizer.alpha( py:309 alpha * self.norm_trace.append( norms.numpy() ) AttributeError: 'Tensor' object has no attribute 'numpy'
  • 你可以试试 tf.make_ndarray(tf.make_tensor_proto(norms)) tensorflow.org/api_docs/python/tf/make_ndarray 而不是 .numpy(),它从张量创建一个 numpy ndarray。
  • 您使用的是哪个版本的 TensorFlow?
  • 谢谢!我现在得到错误:TypeError: Expected any non-tensor type, got a tensor instead (因为 norms 确实是张量)。如果我删除 tf.make_tensor_proto,我得到: AttributeError: 'Tensor' object has no attribute 'tensor_shape' 我在 tensorflow 2.2.0 中工作!非常感谢您的帮助。
  • 附言。知道 learn() 函数包装在 @tf.function 装饰器中可能会有所帮助
猜你喜欢
  • 1970-01-01
  • 2021-08-02
  • 2020-02-22
  • 2020-06-23
  • 1970-01-01
  • 2020-04-13
  • 1970-01-01
  • 1970-01-01
  • 2021-12-28
相关资源
最近更新 更多