我试图实现一个暹罗网络是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")
答案 0 :(得分:2)
在您创建的示例中,您正在创建不同的网络network()
,因此它们将是独立的。
正如余洋所说,检查original example。
首先,他们只创建一次图层 #network definition 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而不是顺序来纠正您的代码。