【发布时间】: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