在 numpy 中重建 Keras 模型
Recreating Keras model in numpy
我正在尝试从 keras 模型中获取经过训练的权重,并尝试在 numpy 中实现正向模型。目前我得到的结果与我的 keras 模型的输出不同。
我已将差异缩小到我实施的地方 batch_normalisation。只是想知道我在下面的 BN 实现中做错了什么:
weights = model.get_weights()
h1_w = weights[0] #no bias term
h2_w, h2_b, bn2_gamma, bn2_beta, bn2_mean, bn2_var = weights[1:7]
def relu(x, w, b):
return np.maximum(0, np.matmul(x, w) + b)
def bn(x, mean, var, gamma, beta, eps=1e-3):
return (x-mean)/(np.sqrt(var) + eps)*gamma + beta
def reconstruct_model(x, x_offset):
h1_act = np.maximum(0, np.matmul(x, h1_w))
h2_act = relu(h1_act, h2_w, h2_b)
h2 = bn(h2_act, bn2_mean, bn2_var, bn2_gamma, bn2_beta)
return h2
为了比较,我的 Keras 模型如下:
x_in = Input(shape=(X_train.shape[1:]))
h = Dense(20, use_bias=False, activation='relu', kernel_regularizer=l1(1e-5))(x_in)
h = Dense(10, activation='relu')(h)
out = BatchNormalization()(h)
model = Model([x_in], out)
model.compile(loss='mse', optimizer='adam')
还要注意 1. 我知道你没有把 BN 放在最后一层。我只是简单地缩减到我注意到差异的第一层。 2.差异不是由于float64 vs float32问题(我最大的差异是0.6左右)。
总而言之,我的 BN 实现有什么问题。
我没有在 python 中测试实现,但在 c++ 中。我将 eps
放在平方根内,我的结果类似于 10e-4 或更好的 keras 实现:
def bn(x, mean, var, gamma, beta, eps=1e-3):
return (x-mean)/(np.sqrt(var + eps))*gamma + beta
我正在尝试从 keras 模型中获取经过训练的权重,并尝试在 numpy 中实现正向模型。目前我得到的结果与我的 keras 模型的输出不同。
我已将差异缩小到我实施的地方 batch_normalisation。只是想知道我在下面的 BN 实现中做错了什么:
weights = model.get_weights()
h1_w = weights[0] #no bias term
h2_w, h2_b, bn2_gamma, bn2_beta, bn2_mean, bn2_var = weights[1:7]
def relu(x, w, b):
return np.maximum(0, np.matmul(x, w) + b)
def bn(x, mean, var, gamma, beta, eps=1e-3):
return (x-mean)/(np.sqrt(var) + eps)*gamma + beta
def reconstruct_model(x, x_offset):
h1_act = np.maximum(0, np.matmul(x, h1_w))
h2_act = relu(h1_act, h2_w, h2_b)
h2 = bn(h2_act, bn2_mean, bn2_var, bn2_gamma, bn2_beta)
return h2
为了比较,我的 Keras 模型如下:
x_in = Input(shape=(X_train.shape[1:]))
h = Dense(20, use_bias=False, activation='relu', kernel_regularizer=l1(1e-5))(x_in)
h = Dense(10, activation='relu')(h)
out = BatchNormalization()(h)
model = Model([x_in], out)
model.compile(loss='mse', optimizer='adam')
还要注意 1. 我知道你没有把 BN 放在最后一层。我只是简单地缩减到我注意到差异的第一层。 2.差异不是由于float64 vs float32问题(我最大的差异是0.6左右)。
总而言之,我的 BN 实现有什么问题。
我没有在 python 中测试实现,但在 c++ 中。我将 eps
放在平方根内,我的结果类似于 10e-4 或更好的 keras 实现:
def bn(x, mean, var, gamma, beta, eps=1e-3):
return (x-mean)/(np.sqrt(var + eps))*gamma + beta