欧拉距离损失函数

时间:2019-05-09 12:32:45

标签: python keras

我对Keras自定义损失函数有一些问题。 当我使用此损失函数运行Keras模型时,我的损失值为NaN

def euc_dist_keras(y_true, y_pred):
    return K.mean(K.sqrt(K.sum(K.square(y_true - y_pred), axis = -1, keepdims = True)))

这是我的代码。

(X_train,Y_train),(X_test,Y_test) = mnist.load_data()
X_train4D = X_train.reshape(X_train.shape[0],28,28,1).astype("float32")
X_test4D = X_test.reshape(X_test.shape[0],28,28,1).astype("float32")

X_train4D_normalize = X_train4D/255
X_test4D_normalize = X_test4D/255

Y_trainOneHot = np_utils.to_categorical(Y_train)
Y_testOneHot = np_utils.to_categorical(Y_test)

model = Sequential()
model.add(Conv2D(filters=16,kernel_size=(5,5),padding='same',input_shape=(28,28,1),activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Conv2D(filters=36,kernel_size=(5,5),padding='same',input_shape=(14,14,1),activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128,activation='relu'))
model.add(Dropout(0.5))
#output layer
model.add(Dense(10,activation='softmax'))
print(model.summary())


model.compile(loss=euc_dist_keras,optimizer='adam',metrics=['accuracy'])
train_history = model.fit(x=X_train4D_normalize,y=Y_trainOneHot,validation_split=0.2\
                          ,epochs=10,batch_size=1,verbose=1)

0 个答案:

没有答案