【问题标题】:Unsupervised loss function in KerasKeras 中的无监督损失函数
【发布时间】:2017-11-29 09:02:10
【问题描述】:

Keras有没有办法指定一个不需要传递目标数据的损失函数?

我试图指定一个像这样省略y_true 参数的损失函数:

def custom_loss(y_pred):

但我收到以下错误:

Traceback (most recent call last):
  File "siamese.py", line 234, in <module>
    model.compile(loss=custom_loss,optimizer=Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0))
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 911, in compile
    sample_weight, mask)
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 436, in weighted
    score_array = fn(y_true, y_pred)
TypeError: custom_loss() takes exactly 1 argument (2 given)

然后我尝试在不指定任何目标数据的情况下调用fit()

 model.fit(x=[x_train,x_train_warped, affines], batch_size = bs, epochs=1)

但看起来不传递任何目标数据会导致错误:

Traceback (most recent call last):
  File "siamese.py", line 264, in <module>
    model.fit(x=[x_train,x_train_warped, affines], batch_size = bs, epochs=1)
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 1435, in fit
    batch_size=batch_size)
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 1322, in _standardize_user_data
    in zip(y, sample_weights, class_weights, self._feed_sample_weight_modes)]
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 577, in _standardize_weights
    return np.ones((y.shape[0],), dtype=K.floatx())
AttributeError: 'NoneType' object has no attribute 'shape'

我可以手动创建与神经网络输出形状相同的虚拟数据,但这看起来非常混乱。有没有一种简单的方法来指定我缺少的 Keras 中的无监督损失函数?

【问题讨论】:

  • 我认为你没有抓住重点,你的无监督损失究竟会做什么?什么精确计算?
  • 我正在尝试比较神经网络的两个不同输出的相似性。它们越相似,损失应该越低。更具体地说,我正在尝试重新实现paper 中描述的神经网络
  • 我认为你应该使用虚拟数据......是的......它很丑,我也不喜欢它......但我看不到解决方案。
  • 第二个与您的输入/输出数据相关的错误,您需要使用numpy.array。您可以使用x_train 作为目标。

标签: machine-learning keras unsupervised-learning


【解决方案1】:

编写你的损失函数,就好像它有两个参数:

  1. y_true
  2. y_pred

如果你没有y_true,那很好,你不需要在内部使用它来计算损失,但在你的函数原型中留下一个占位符,这样 keras 就不会抱怨了。

def custom_loss(y_true, y_pred):
    # do things with y_pred
    return loss

添加自定义参数

您可能还需要在损失函数中使用另一个参数,例如 margin,即使这样,您的自定义函数也应该只接受这两个参数。但是有一个变通方法,使用 lambda 函数

def custom_loss(y_pred, margin):
    # do things with y_pred
    return loss

但要像使用它

model.compile(loss=lambda y_true, y_pred: custom_loss(y_pred, margin), ...)

【讨论】:

    【解决方案2】:

    我认为最好的解决方案是自定义训练而不是使用model.fit 方法。

    完整的演练发布在Tensorflow tutorials page

    【讨论】:

      猜你喜欢
      • 2018-07-12
      • 1970-01-01
      • 1970-01-01
      • 2020-09-21
      • 1970-01-01
      • 2018-04-03
      • 2019-01-20
      • 1970-01-01
      • 2017-09-04
      相关资源
      最近更新 更多