【问题标题】:Comprehension list in Keras backend for custom loss functionKeras后端自定义损失函数的理解列表
【发布时间】:2018-08-23 10:10:35
【问题描述】:

我正在尝试在 Keras 中实现自定义损失函数。

在意识到它需要在 Tensorflow/Keras 后端之前,我在“标准”python/numpy 中编写了我的自定义损失函数。我看到 Keras 后端实现了一些简单的函数,例如均值或求和,因此我尝试翻译它们。但是,我不知道如何翻译下面使用的理解列表或 cdist 函数。

python/numpy 中的原始行是注释的行,未注释的行是我尝试使用 keras 后端编写的行:

def loss_zhang(y_true, y_pred):

    predictions = y_pred[0]
    features = y_pred[1]

    # Parameter ~ hypersphere radius
    m = 0.5

    # Find the center of the features for the reference class
    # center = np.mean(features[np.where(y_true==1)], axis=0)
    center = K.mean(features[K.tf.where(y_true==1)], axis=0)

    # Compute the distances between all the features and the center
    # dist = cdist(features, [center], metric='euclidean')
    dist = [K.sqrt(K.sum(K.square(u - center), axis=-1)) for u in features]

    # Compute the loss for each sample (based on distance to center)
    # losses = [ofRef*d**2 + (1-ofRef)*(np.max([0, m-d]))**2 for d, ofRef in zip(dist, y_true)]
    losses = y_true*K.square(dist) + (1-y_true)*K.square(K.max([0, m-d]))

    # Total loss = sum of individual losses
    # return 0.5*np.sum(losses)
    return 0.5*K.sum(losses)

【问题讨论】:

    标签: python tensorflow neural-network keras


    【解决方案1】:

    找到了:

    y_true = y_true[0]
    predictions = y_pred[0]
    features = y_pred[1]
    
    # Parameter ~ hypersphere radius
    m = K.constant(0.35)
    
    # Find the center of the features for the reference class
    center = tf.reduce_mean(tf.gather_nd(features, K.tf.where(tf.squeeze (tf.equal(y_true, 1)))), axis=0)
    
    # Compute the distances between all the features and the center
    dist = K.sqrt(K.sum(K.square(features - center), axis=-1))
    
    # Compute the loss for each sample (based on distance to center)
    losses = y_true*K.square(dist) + (1-y_true)*K.square(tf.maximum(0., m-dist))
    
    return 0.5*K.sum(losses)
    

    【讨论】:

      猜你喜欢
      • 2022-12-06
      • 2018-12-26
      • 2018-08-06
      • 2019-11-07
      • 1970-01-01
      • 2020-12-19
      • 2017-12-18
      • 2020-03-27
      • 1970-01-01
      相关资源
      最近更新 更多