Для того, чтобы взять «все элементы» выше этого процентиля, вам понадобится другой ответ:
import keras.backend as K
from keras.layers import *
from keras.models import Model
import numpy as np
import tensorflow as tf
def above_percentile(x, p): #assuming the input is flattened: (n,)
samples = K.cast(K.shape(x)[0], K.floatx()) #batch size
p = (100. - p)/100. #100% will return 0 elements, 0% will return all elements
#samples to get:
samples = K.cast(tf.math.floor(p * samples), 'int32')
#you can choose tf.math.ceil above, it depends on whether you want to
#include or exclude one element. Suppose you you want 33% top,
#but it's only possible to get exactly 30% or 40% top:
#floor will get 30% top and ceil will get 40% top.
#(exact matches included in both cases)
#selected samples
values, indices = tf.math.top_k(x, samples)
return values
def custom_loss(p):
def loss(y_true, y_predicted):
ses = K.square(y_true-y_predicted)
above = above_percentile(K.flatten(ses), p)
return K.mean(above)
return loss
Тест:
dataX = np.array([2,3,1,4,7,10,8,5,6]).reshape((-1,1))
dataY = np.ones((9,1))
ins = Input((1,))
outs = Lambda(lambda x: x)(ins)
model = Model(ins, outs)
model.compile(optimizer='adam', loss = custom_loss(70.))
model.fit(dataX, dataY)
Потеря составит 65
, что составляет 130/2
(жадный). И 130 = (10-1)² + (8-1)²
, будучи 10
и 8
двумя верхними k на входе.