相关疑难解决方法(0)

在keras中制作自定义丢失功能

嗨,我一直在尝试在keras中为dice_error_coefficient创建自定义丢失函数.它有它的实现tensorboard,我尝试使用相同的功能与tensorflow keras但它一直返回NoneType当我用model.train_on_batchmodel.fit其中在模型中的指标使用时,它提供正确的价值观.可以请有人帮我解决我该怎么办?我曾经尝试过像ahundt这样的Keras-FCN这样的库,在那里他使用了自定义丢失函数,但似乎都没有.代码中的目标和输出分别是y_true和y_pred,如keras中的losses.py文件中所使用的那样.

def dice_hard_coe(target, output, threshold=0.5, axis=[1,2], smooth=1e-5):
    """References
    -----------
    - `Wiki-Dice <https://en.wikipedia.org/wiki/Sørensen–Dice_coefficient>`_
    """

    output = tf.cast(output > threshold, dtype=tf.float32)
    target = tf.cast(target > threshold, dtype=tf.float32)
    inse = tf.reduce_sum(tf.multiply(output, target), axis=axis)
    l = tf.reduce_sum(output, axis=axis)
    r = tf.reduce_sum(target, axis=axis)
    hard_dice = (2. * inse + smooth) / (l + r + smooth)
    hard_dice = tf.reduce_mean(hard_dice)
    return hard_dice
Run Code Online (Sandbox Code Playgroud)

python machine-learning keras tensorflow

30
推荐指数
2
解决办法
4万
查看次数

Keras 中带有权重的自定义损失函数

我是神经网络新手。我想在 TensorFlow 中制作一个自定义损失函数,但我需要获取权重向量,所以我这样做了:

def my_loss(weights):
  def custom_loss(y, y_pred):
    return weights*(y - y_pred)
  return custom_loss
model.compile(optimizer='adam', loss=my_loss(weights), metrics=['accuracy'])
model.fit(x_train, y_train, batch_size=None,  validation_data=(x_test, y_test), epochs=100)

Run Code Online (Sandbox Code Playgroud)

当我启动它时,我收到此错误:

InvalidArgumentError:  Incompatible shapes: [50000,10] vs. [32,10]
Run Code Online (Sandbox Code Playgroud)

形状是:

print(weights.shape)
print(y_train.shape)
Run Code Online (Sandbox Code Playgroud)
(50000, 10)
(50000, 10)
Run Code Online (Sandbox Code Playgroud)

所以我认为这是批次的问题,我没有很强的TensorFlow背景,所以我尝试使用全局变量以简单的方式解决

batch_index = 0
Run Code Online (Sandbox Code Playgroud)

然后在自定义回调中将其更新到“on_batch_begin”挂钩中。但这没有用,而且是一个糟糕的解决方案。那么,如何才能得到对应y的权重的精确部分呢?我有办法获取自定义损失中的当前批次索引吗?预先感谢您的帮助

python neural-network keras tensorflow loss-function

8
推荐指数
1
解决办法
1万
查看次数