AnnieTheKatsu :
私は(X_1)、...、F(x_nに関する)fの入力変数x_1、...、x_nに関する及びd次元の出力を有しKerasモデルを持っています。d次元ターゲットはY_1と私は回帰問題に取り組んでいる、...、y_n。
Iは、損失関数を最小化したい:0と1の間の固定されたメタパラメータAについてのA ^番目(経験的)分位を返します|f(x_i)-y_i|^2
。
ここで私はこれまでにコード化されたものです。
def keras_custom_loss(y_true,y_predicted):
SEs = K.square(y_true-y_predicted)
out_custom = tfp.stats.percentile(SEs, 50.0, interpolation='midpoint')
return out_custom
1つの問題は、私はtensorflow_probabilityを使用しないようしたいと私はKerasで行わ全体の実装を好むだろうということです。
しかし、私はどのように把握することはできません。
ダニエル・メーラー:
そのパーセンタイル以上の「すべての要素を」取るために、あなたは別の答えが必要になります。
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
入力の2トップのk。