[英]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:必須為實數,而不是張量
我對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_train
和Y_train
的形狀分別為( X_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是無法處理張量的函數。 如果仍有問題,請參閱: 自定義損失函數Keras Tensorflow
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.