我正在尝试实现一个孪生网络是 Keras 以实现文本相似性,但我的网络似乎并不对称。当我测试时,它为 A、B 给出的相似度分数与 B、A 不同。我该如何解决?我也尝试过点模式,以及所有密集层。我的代码是,
def contrastive(y_true, y_pred):
margin = 1
return K.mean(y_true * K.square(y_pred) + (1 - y_true) * K.square(K.maximum(margin - y_pred, 0)))
def network():
encoder = Sequential()
encoder.add(Embedding(27, 15, input_length=15))
encoder.add(LSTM(15))
encoder.add(Dense(15))
return encoder
l_twin = network()
r_twin = network()
merged = Merge([l_twin, r_twin], mode='cos', dot_axes=1)
siamese = Sequential()
siamese.add(merged)
siamese.add(Dense(1, activation="sigmoid"))
siamese.compile(loss=contrastive, optimizer='adam', metrics=['accuracy'])
history = siamese.fit([l_encodings, r_encodings], target, epochs=5, batch_size=50)
siamese.save("siamese.h5")
siamese.save_weights("siamese_weights.h5")
请您参考如下方法:
在您创建的示例中,您正在创建不同的网络 network(),因此它们将是独立的。
正如 Yu-Yang 所说,检查 original example .
首先,他们只创建一次图层 # 网络定义 base_network = create_base_network(input_shape)
然后他们将网络应用于两个不同的输入:
input_a = Input(shape=input_shape)
input_b = Input(shape=input_shape)
# because we re-use the same instance `base_network`,
# the weights of the network
# will be shared across the two branches
processed_a = base_network(input_a)
processed_b = base_network(input_b)
您应该尝试使用函数式 API 而不是顺序 API 来更正您的代码。
