Сиамская сеть - как это реализовать - PullRequest
1 голос
/ 05 октября 2019

Я бы попытался реализовать этот сиамский NN, используя Keras:

enter image description here

Эта нейронная сеть должна использоваться для классификации онлайн-подписей как подлинников или подделок.

Так как я новичок в машинном обучении и нейронных сетях, я бы попросил вас помочь с кодом.

Я пытался найти какой-то готовый код в Google, но я не нашел ничего подходящеготочно моя цель

Это класс, который я реализовал в python с использованием библиотек keras

import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Activation, Dropout

def buildModel(X_train, Y_train):

    batch_size = 512  
    n_epoch = 20

    # We have 2 inputs, 1 for each signature;
    left_input = Input((1, 16000))
    right_input = Input((1, 16000))

    convnet = Sequential()
    convnet.add(ConvLSTM2D(filters=40, kernel_size=(3, 3),
                       input_shape=(1, 16000),
                       padding='same', return_sequences=True))
    convnet.add(BatchNormalization())
    # Connect each 'leg' of the network to each input
    # Remember, they have the same weights
    encoded_l = convnet(left_input)
    encoded_r = convnet(right_input)

    # Getting the L1 Distance between the 2 encodings
    L1_layer = np.concatenate(encoded_l, encoded_r)

    # Add the distance function to the network
    L1_distance = L1_layer([encoded_l, encoded_r])

    prediction = Dense(1, activation='sigmoid')(L1_distance)
    siamese_net = Model(inputs=[left_input, right_input], outputs=prediction)

    optimizer = Adam(0.001, decay=2.5e-4) #don't know the use of these parameters
    siamese_net.compile(loss="binary_crossentropy", optimizer=optimizer, metrics=['accuracy'])

    return model

if __name__ == "__main__":

    forgeries = np.loadtxt('/content/forgeries.txt', delimiter=',')
    genuines = np.loadtxt('/content/genuines.txt', delimiter=',')

    X = np.vstack((genuines, forgeries))
    Y1 = np.ones((376, 1))
    Y2 = np.zeros((94, 1))
    y = np.concatenate((Y1, Y2))

    model = buildModel(X_train, y)

    prediction = []
    for i in range(len(X_test)):

      prediction.append(np.ndarray.tolist(model.predict(np.array([X_test[i]])))[0][0])


    thresh = np.mean(np.array([prediction]))


    result = []; counter = 1; flag = 1
    for i in range(len(prediction)):

        if flag == 1 and prediction[i] > thresh:
            result.append(1)
        elif flag == 0 and prediction[i] < thresh:
            result.append(1)
        else:
            result.append(0)

        counter+=1
        if counter>2:
            flag = not flag
            counter = 1

    # print prediction
    # print result

    accuracy = (float(result.count(1))/len(result))*100
    print accuracy

Я бы попросил вас уточнить, какие параметры я должен настраивать и как я должен это делать;также я знаю, что мне не хватает слоя (последний), но я не знаю, как добавить его в код

...