【问题标题】:Why MSE from Keras is not the same as what I calculate?为什么 Keras 的 MSE 与我计算的不一样?
【发布时间】:2019-09-27 02:21:34
【问题描述】:

我使用以下代码:

import numpy as np
import math
import keras
from keras.models import Model, Sequential
from keras.layers import Input, Dense, Activation
from keras import regularizers
from keras import backend as K

a=1

def my_regularizer(inputs):
    means=K.mean((inputs),axis=1)
    return a*K.sum(means)**2

x_train=np.random.uniform(low=-1,high=1,size=(200,2))
x_test=np.random.uniform(low=-1,high=1,size=(20,2))
model=Sequential([
     Dense(20,input_shape=(2,),activity_regularizer=my_regularizer),
     Activation('tanh'),
     Dense(2,),
     Activation('linear')
])

model.compile(optimizer='adam',loss='mean_squared_error')
hist=model.fit(x_train,x_train,epochs=10,verbose=1,validation_data=(x_test,x_test))

print('MSE from Keras: ',hist.history['val_loss'][-1])
y_pred=model.predict(x_test)
print('Calculated MSE: ', np.mean((y_pred-x_test)**2))

输出是:

MSE from Keras:  0.1555381715297699
Calculated MSE:  0.12031101597786406

如果我删除activity_regularizer=my_regularizer,那么它们会更接近,但仍然不同:

MSE from Keras:  0.09773887693881989
Calculated MSE:  0.09773887699599623

【问题讨论】:

标签: keras neural-network


【解决方案1】:

嗯,答案很明确。你有一个正则化器。 正则化器的作用是在损失函数中添加一个项,因此损失更大是预期的行为。

对于另一个小区别,它只是精确度。也许使用 float 32 vs float 64,或者在 GPU x CPU 上使用不同的算法进行计算。我不会担心这种差异。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-16
    • 2018-07-29
    • 1970-01-01
    • 1970-01-01
    • 2017-01-21
    • 1970-01-01
    相关资源
    最近更新 更多