【发布时间】:2020-09-11 03:40:00
【问题描述】:
版本:python 3.8.2(我也尝试过 3.6.8,但我认为 python 版本在这里并不重要)、tensorflow 2.3.0、numpy 1.18.5
我正在为带有稀疏标签张量的分类问题训练模型。我将如何定义一个指标来计算“0”标签在该点之前出现的次数?我在下面的代码示例中尝试做的是将度量标准看到的所有标签存储在一个数组中,并在每次调用update_state 时不断地将现有数组与新的y_true 连接起来。 (我知道我可以只存储一个count 变量并使用+=,但在实际使用场景中,连接是理想的,内存不是问题。)这是重现问题的最少代码:
import tensorflow as tf
class ZeroLabels(tf.keras.metrics.Metric):
"""Accumulates a list of all y_true sparse categorical labels (ints) and calculates the number of times the '0' label has appeared."""
def __init__(self, *args, **kwargs):
super(ZeroLabels, self).__init__(name="ZeroLabels")
self.labels = self.add_weight(name="labels", shape=(), initializer="zeros", dtype=tf.int32)
def update_state(self, y_true, y_pred, sample_weight=None):
"""I'm using sparse categorical crossentropy, so labels are 1D array of integers."""
if self.labels.shape == (): # if this is the first time update_state is being called
self.labels = y_true
else:
self.labels = tf.concat((self.labels, y_true), axis=0)
def result(self):
return tf.reduce_sum(tf.cast(self.labels == 0, dtype=tf.int32))
def reset_states(self):
self.labels = tf.constant(0, dtype=tf.int32)
此代码可自行运行,但当我尝试使用此指标训练模型时会引发以下错误:
TypeError: An op outside of the function building code is being passed
a "Graph" tensor. It is possible to have Graph tensors
leak out of the function building context by including a
tf.init_scope in your function building code.
For example, the following function will fail:
@tf.function
def has_init_scope():
my_constant = tf.constant(1.)
with tf.init_scope():
added = my_constant * 2
我认为这可能与调用 update_state 时 self.labels 不是图表的直接部分有关。以下是我尝试过的其他一些事情:
- 存储
tf.int32、shape=()count变量并递增该变量而不是连接新标签 - 使用
.numpy()将所有内容转换为 numpy 并将它们连接起来(我希望强制 TensorFlow 不使用图表) - 使用
try和except块和上面的numpy 转换 - 创建一个全新的类(而不是子类化
tf.keras.metrics.Metric),在可能的情况下专门使用numpy,但这种方法会导致一些加载问题,即使我在tf.keras.models.load_model中使用custom_objects - 在所有方法上使用
@tf.autograph.experimental.do_not_convert装饰器 - 修改全局变量而不是属性并使用
global关键字 - 使用非张量流属性(不使用
self.labels = self.add_weight...)
如果有帮助,这里是这个问题的一个更通用的版本:我们如何在update_state 计算中合并未作为参数传递给update_state 的张量?任何帮助将不胜感激。提前谢谢!
【问题讨论】:
标签: python tensorflow graph metrics