在Tensorflow中训练网络时忽略特定的输入损失

时间:2016-06-12 20:19:24

标签: python numpy tensorflow training-data

我有一个二进制分类问题,其中只有在数据集中注释了积极事件的开始3个时间实例,并且我有先验知识,他们可以持续多达15个时间实例。为了解决这个问题,我决定在训练网络时忽略注释后的15-3 = 12次实例中的丢失值。

我正在使用Python中的Tensorflow训练LSTM网络,我的训练批次为sequence_len=240,在任何迭代中,序列中的任何时间都可能发生正面事件。

基本上,我的费用指标是(使用AdamOptimizer

loss = tf.nn.softmax_cross_entropy_with_logits(logits, self._targets)
cost = tf.reduce_mean(loss)

我正在考虑我只需要将loss中的不需要的元素移到tf.reduce_mean()之前。我开发了一种算法来假设目标是一个numpy数组:

v = targets[:, 0]
w = np.where(np.multiply(v[:-1] == 1, v[1:] < 1))[0]
m = np.ones(v.shape, dtype=bool)
    for i in w:
    i1 = i + 1
    i2 = np.min((i + 13, len(v)))
    ind = np.arange(i1, i2, dtype=np.int)
    m[ind] = False
return m

此算法有效,但在Tensorflow范围内无效!显然因为输入是张量而不是numpy数组。

因此,我的问题是:如何将此小算法/掩码迁移到Tensorflow?

1 个答案:

答案 0 :(得分:0)

在发布这个问题之后我很快就找到了明显的答案。我将包含一个占位符,用于&#34;错误权重&#34;在网络中:

self._mask = tf.placeholder(tf.float32, [None])

然后在成本函数中,我将对这些进行加权损失。

loss = tf.nn.softmax_cross_entropy_with_logits(logits, self._targets)
cost = tf.reduce_sum(tf.mul(loss, self._mask) / tf.reduce_sum(self._mask)

然后在我的输入数据旁边生成掩码。这也更好,因为我可以弥补在新序列之前发生的正面事件,而之前的解决方案是无法做到的。