暹罗网络的Keras模型不学习并且总是预测相同的输出 [英] Keras Model for Siamese Network not Learning and always predicting the same ouput
问题描述
我正在尝试使用Keras训练暹罗神经网络,目的是识别2张图像是否属于同一类.我的数据被打乱了,正例和负例的数量相等.我的模型没有学习任何东西,并且总是在预测相同的输出.我每次都得到相同的损失,验证准确性和验证损失.
I am trying to train a Siamese neural network using Keras, with the goal of identifying if 2 images belong to same class or not. My data is shuffled and has equal number of positive examples and negative examples. My model is not learning anything and it is predicting the same output always. I am getting the same loss, validation accuracy, and validation loss every time.
def convert(row):
return imread(row)
def contrastive_loss(y_true, y_pred):
margin = 1
square_pred = K.square(y_pred)
margin_square = K.square(K.maximum(margin - y_pred, 0))
return K.mean(y_true * square_pred + (1 - y_true) * margin_square)
def SiameseNetwork(input_shape):
top_input = Input(input_shape)
bottom_input = Input(input_shape)
# Network
model = Sequential()
model.add(Conv2D(96,(7,7),activation='relu',input_shape=input_shape))
model.add(MaxPooling2D())
model.add(Conv2D(256,(5,5),activation='relu',input_shape=input_shape))
model.add(MaxPooling2D())
model.add(Conv2D(256,(5,5),activation='relu',input_shape=input_shape))
model.add(MaxPooling2D())
model.add(Flatten())
model.add(Dense(4096,activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(1024,activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(512,activation='relu'))
model.add(Dropout(0.5))
encoded_top = model(top_input)
encoded_bottom = model(bottom_input)
L1_layer = Lambda(lambda tensors:K.abs(tensors[0] - tensors[1]))
L1_distance = L1_layer([encoded_top, encoded_bottom])
prediction = Dense(1,activation='sigmoid')(L1_distance)
siamesenet = Model(inputs=[top_input,bottom_input],outputs=prediction)
return siamesenet
data = pd.read_csv('shuffleddata.csv')
print('Converting X1....')
X1 = [convert(x) for x in data['X1']]
print('Converting X2....')
X2 = [convert(x) for x in data['X2']]
print('Converting Y.....')
Y = [0 if data['Y'][i] == 'Negative' else 1 for i in range(len(data['Y']))]
input_shape = (53,121,3,)
model = SiameseNetwork(input_shape)
model.compile(loss=contrastive_loss,optimizer='sgd',metrics=['accuracy'])
print(model.summary())
model.fit(X1,Y,batch_size=32,epochs=20,shuffle=True,validation_split = 0.2)
model.save('Siamese.h5')
推荐答案
为了社区的利益,在本节中(即使在评论"部分中也提到了此问题的解决方案).
Mentioning the resolution to this issue in this section (even though it is present in Comments Section), for the benefit of the community.
由于模型可以与其他标准数据集配合使用,因此解决方案是使用更多数据.模型不是学习型的,因为它的训练数据较少.
Since the Model is working fine with other Standard Datasets, the solution is to use more Data. Model is not learning because it has less data for Training.
这篇关于暹罗网络的Keras模型不学习并且总是预测相同的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!