小编cod*_*tle的帖子

在 Tensorflow 中保留自定义静态张量的未知批量维度

一些注意事项:我使用的是tensorflow 2.3.0、python 3.8.2和numpy 1.18.5(但不确定这是否重要)

我正在编写一个自定义层,它在内部存储形状为 (a, b) 的不可训练张量 N,其中 a, b 是已知值(该张量是在 init 期间创建的)。当调用输入张量时,它会展平输入张量,展平其存储的张量,并将两者连接在一起。不幸的是,我似乎无法弄清楚如何在连接过程中保留未知的批量维度。这是最少的代码:

import tensorflow as tf
from tensorflow.keras.layers import Layer, Flatten

class CustomLayer(Layer):
   def __init__(self, N):                     # N is a tensor of shape (a, b), where a, b > 1
      super(CustomLayer, self).__init__()
      self.N = self.add_weight(name="N", shape=N.shape, trainable=False, initializer=lambda *args, **kwargs: N)

      # correct me if I'm wrong in using this initializer approach, but for some reason, when I
      # just do self.N = N, this variable would disappear …
Run Code Online (Sandbox Code Playgroud)

python keras tensorflow

5
推荐指数
1
解决办法
1414
查看次数

更新 TensorFlow 自定义指标的内部状态(也称为在指标计算中使用非 update_state 变量)

版本:python 3.8.2(我也尝试过3.6.8,但我认为python版本在这里并不重要),tensorflow 2.3.0,numpy 1.18.5

我正在使用稀疏标签张量训练一个用于分类问题的模型。我将如何定义一个指标来计算“0”标签在此之前出现的次数?我在下面的代码示例中尝试做的是将指标在数组中看到的所有标签存储起来,并在y_true每次update_state调用时不断地将现有数组与新数组连接起来。(我知道我可以只存储一个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 …
Run Code Online (Sandbox Code Playgroud)

python metrics graph tensorflow

0
推荐指数
1
解决办法
1294
查看次数

标签 统计

python ×2

tensorflow ×2

graph ×1

keras ×1

metrics ×1