如何在简单的数学运算中定义keras自定义损失函数

How to define a keras custom loss function in simple mathematical operation

我定义了一个自定义函数 my_sigmoid 如下:

import math
def my_sigmoid(x):
    a =  1/  ( 1+math.exp( -(x-300)/30 ) )
    return a

然后定义一个自定义的损失函数叫做my_cross_entropy:

import keras.backend as K

def my_cross_entropy(y_true, y_pred):
    diff = abs(y_true-y_pred)
    y_pred_transform = my_sigmoid(diff)
    return K.categorical_crossentropy(0, y_pred_transform)

我的 keras 后端使用的是 tensorflow。 错误显示

TypeError: must be real number, not Tensor

我对tensorflow不熟悉,不知道如何使用自定义损失。

以下是我的模型结构和报错信息:

import keras.backend as K
from keras.models import Sequential
from keras.layers import Conv2D, Dropout, Flatten, Dense

model=Sequential()
model.add(Conv2D(512,(5,X_train.shape[2]),input_shape=X_train.shape[1:4],activation="relu"))
model.add(Flatten())
model.add(Dropout(0.1))
model.add(Dense(100,activation="relu"))
model.add(Dense(100,activation="relu"))
model.add(Dense(50,activation="relu"))
model.add(Dense(10,activation="relu"))
model.add(Dense(1,activation="relu"))
model.compile(optimizer='adam', loss=my_cross_entropy)
model.fit(X_train,Y_train,batch_size = 10,epochs=200,validation_data=(X_test,Y_test))

X_trainY_train 的形状是: (120, 30, 80, 1)(120,)

改变

diff = abs(y_true-y_pred)

进入

diff = K.abs(y_true-y_pred)

相同
math.exp()

将其更改为

K.exp()

abs 和 Math.exp 是无法处理张量的函数。如果还有问题请参考: