【问题标题】:How to ignore part of input and output in Keras?如何忽略 Keras 中的部分输入和输出?
【发布时间】:2019-04-12 11:34:44
【问题描述】:

我正在尝试训练一个将 n 值作为输入并输出 n 值的模型。问题是 n 可以从 1 到 700。所以我构建了一个以 700 作为输入和 700 作为输出的网络。额外的输入和输出设置为零。 在训练模型时,我不关心额外的输出是否准确。所以我尝试定义自己的损失函数如下:

def mse_truncate(y_true, y_pred):
    def fn(x):
        return tf.cond(x < 0.01,lambda: 0.0,lambda: 1.0)
    #Ignore the square error if y_true[i] is near zero
    sgn = tf.map_fn(fn,y_true)
    return K.mean(sgn * K.square(y_true-y_pred),axis=-1)

此功能适用于控制台。 但是当我编译模型时,我得到一个错误:

model.compile(optimizer='sgd',loss=mse_truncate, metrics=['accuracy'])
ValueError: Shape must be rank 0 but is rank 1 for 'loss_5/dense_2_loss/map/while/cond/Switch' (op: 'Switch') with input shapes: [?], [?].

谁能告诉我这里出了什么问题? 或者有没有更好的方法来处理可变长度的输入和输出?

注意: 关于这个问题,输入是一个序列(长度

【问题讨论】:

  • 你明白了吗?有同样的问题...

标签: python machine-learning keras conv-neural-network loss-function


【解决方案1】:

您可以使用tf.wheretf.gather 仅考虑您关心的那些值,例如:

indices = tf.where(tf.greater(y_true, 0.01)) #  or `tf.less`, `tf.equal` etc.
loss = K.mean(K.square(tf.gather(y_true, indices) - tf.gather(y_pred, indices))))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-03
    相关资源
    最近更新 更多