[英]custom keras loss function
我想在keras中編寫一個自定義損失函數,該函數還使用輸入的輸出梯度
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Dropout
model = Sequential()
model.add(Dense(200, input_dim=20, activation='relu'))
model.add(Dense(64, input_dim=20, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(64, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
現在,我要替換損失函數。 我只知道如何使用張量流編寫如下:
x = tf.placeholder(tf.float32, shape=[None, 1], name="x")
ext_f0 = tf.placeholder(tf.float32, shape=[None, 1], name="f")
xx0 = tf.concat([[[R_variable['x_start'] * 1.0],[R_variable['x_end'] * 1.0]], x], 0)
yy0 = univAprox(xx0)
Boundary_y = yy0[0:2]
y = yy0[2:]
GradU = tf.gradients(y,x) #***KEY***
GradSum = tf.reduce_sum(tf.square(GradU)) / 2 * dx_train
FSum = tf.reduce_sum(tf.multiply(ext_f0,y)) * dx_train
loss = GradSum + FSum + Beta * tf.reduce_sum(tf.square(Boundary_y))
關鍵是我需要獲得GradU
。 我該怎么做在喀拉拉邦?
您可以編寫自定義損失函數。 您應該知道的是它的形式:
def custom_loss(y_true, y_pred):
# do something to compute loss
...
return loss
就是這樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.