keras的siamese(孪生网络)实现案例

 更新时间:2020年06月12日 14:20:25   作者:李上花开  
这篇文章主要介绍了keras的siamese(孪生网络)实现案例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

代码位于keras的官方样例,并做了微量修改和大量学习?。

最终效果:

import keras
import numpy as np
import matplotlib.pyplot as plt

import random

from keras.callbacks import TensorBoard
from keras.datasets import mnist
from keras.models import Model
from keras.layers import Input, Flatten, Dense, Dropout, Lambda
from keras.optimizers import RMSprop
from keras import backend as K

num_classes = 10
epochs = 20


def euclidean_distance(vects):
 x, y = vects
 sum_square = K.sum(K.square(x - y), axis=1, keepdims=True)
 return K.sqrt(K.maximum(sum_square, K.epsilon()))


def eucl_dist_output_shape(shapes):
 shape1, shape2 = shapes
 return (shape1[0], 1)


def contrastive_loss(y_true, y_pred):
 '''Contrastive loss from Hadsell-et-al.'06
 http://yann.lecun.com/exdb/publis/pdf/hadsell-chopra-lecun-06.pdf
 '''
 margin = 1
 sqaure_pred = K.square(y_pred)
 margin_square = K.square(K.maximum(margin - y_pred, 0))
 return K.mean(y_true * sqaure_pred + (1 - y_true) * margin_square)


def create_pairs(x, digit_indices):
 '''Positive and negative pair creation.
 Alternates between positive and negative pairs.
 '''
 pairs = []
 labels = []
 n = min([len(digit_indices[d]) for d in range(num_classes)]) - 1
 for d in range(num_classes):
  for i in range(n):
   z1, z2 = digit_indices[d][i], digit_indices[d][i + 1]
   pairs += [[x[z1], x[z2]]]
   inc = random.randrange(1, num_classes)
   dn = (d + inc) % num_classes
   z1, z2 = digit_indices[d][i], digit_indices[dn][i]
   pairs += [[x[z1], x[z2]]]
   labels += [1, 0]
 return np.array(pairs), np.array(labels)


def create_base_network(input_shape):
 '''Base network to be shared (eq. to feature extraction).
 '''
 input = Input(shape=input_shape)
 x = Flatten()(input)
 x = Dense(128, activation='relu')(x)
 x = Dropout(0.1)(x)
 x = Dense(128, activation='relu')(x)
 x = Dropout(0.1)(x)
 x = Dense(128, activation='relu')(x)
 return Model(input, x)


def compute_accuracy(y_true, y_pred): # numpy上的操作
 '''Compute classification accuracy with a fixed threshold on distances.
 '''
 pred = y_pred.ravel() < 0.5
 return np.mean(pred == y_true)


def accuracy(y_true, y_pred): # Tensor上的操作
 '''Compute classification accuracy with a fixed threshold on distances.
 '''
 return K.mean(K.equal(y_true, K.cast(y_pred < 0.5, y_true.dtype)))

def plot_train_history(history, train_metrics, val_metrics):
 plt.plot(history.history.get(train_metrics), '-o')
 plt.plot(history.history.get(val_metrics), '-o')
 plt.ylabel(train_metrics)
 plt.xlabel('Epochs')
 plt.legend(['train', 'validation'])


# the data, split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
input_shape = x_train.shape[1:]

# create training+test positive and negative pairs
digit_indices = [np.where(y_train == i)[0] for i in range(num_classes)]
tr_pairs, tr_y = create_pairs(x_train, digit_indices)

digit_indices = [np.where(y_test == i)[0] for i in range(num_classes)]
te_pairs, te_y = create_pairs(x_test, digit_indices)

# 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)

distance = Lambda(euclidean_distance,
     output_shape=eucl_dist_output_shape)([processed_a, processed_b])

model = Model([input_a, input_b], distance)
keras.utils.plot_model(model,"siamModel.png",show_shapes=True)
model.summary()

# train
rms = RMSprop()
model.compile(loss=contrastive_loss, optimizer=rms, metrics=[accuracy])
history=model.fit([tr_pairs[:, 0], tr_pairs[:, 1]], tr_y,
   batch_size=128,
   epochs=epochs,verbose=2,
   validation_data=([te_pairs[:, 0], te_pairs[:, 1]], te_y))

plt.figure(figsize=(8, 4))
plt.subplot(1, 2, 1)
plot_train_history(history, 'loss', 'val_loss')
plt.subplot(1, 2, 2)
plot_train_history(history, 'accuracy', 'val_accuracy')
plt.show()


# compute final accuracy on training and test sets
y_pred = model.predict([tr_pairs[:, 0], tr_pairs[:, 1]])
tr_acc = compute_accuracy(tr_y, y_pred)
y_pred = model.predict([te_pairs[:, 0], te_pairs[:, 1]])
te_acc = compute_accuracy(te_y, y_pred)

print('* Accuracy on training set: %0.2f%%' % (100 * tr_acc))
print('* Accuracy on test set: %0.2f%%' % (100 * te_acc))

以上这篇keras的siamese(孪生网络)实现案例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • Python+selenium 获取浏览器窗口坐标、句柄的方法

    Python+selenium 获取浏览器窗口坐标、句柄的方法

    今天小编就为大家分享一篇Python+selenium 获取浏览器窗口坐标、句柄的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-10-10
  • linux环境打包python工程为可执行程序的过程

    linux环境打包python工程为可执行程序的过程

    本次需求,在ubuntu上面开发的python代码程序需要打包成一个可执行程序然后交付给甲方,因为不能直接给源码给甲方,所以寻找方法将python开发的源码打包成一个可执行程序,本次在ubuntu上打包python源码的方法和在window上打包的有点类似,感兴趣的朋友跟随小编一起看看吧
    2024-01-01
  • Python处理文本换行符实例代码

    Python处理文本换行符实例代码

    这篇文章主要介绍了Python处理文本换行符实例代码,分享了相关代码示例,小编觉得还是挺不错的,具有一定借鉴价值,需要的朋友可以参考下
    2018-02-02
  • Flask搭建Web应用程序的方法示例

    Flask搭建Web应用程序的方法示例

    Flask是一个使用Python编写的轻量级Web应用框架,本文我们将介绍一个使用Flask逐步搭建Web应用程序的简单入门示例,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习吧
    2024-01-01
  • Python 3.8正式发布重要新功能一览

    Python 3.8正式发布重要新功能一览

    最新版本的Python发布了!今年夏天,Python 3.8发布beta版本,但在2019年10月14日,第一个正式版本已准备就绪。现在,我们都可以开始使用新功能并从最新改进中受益
    2019-10-10
  • python游戏开发的五个案例分享

    python游戏开发的五个案例分享

    本文给大家分享了作者整理的五个python游戏开发的案例,通过具体设计思路,代码等方面详细了解python游戏开发的过程,非常的详细,希望大家能够喜欢
    2020-03-03
  • Python实现打印详细报错日志,获取报错信息位置行数

    Python实现打印详细报错日志,获取报错信息位置行数

    这篇文章主要介绍了Python实现打印详细报错日志,获取报错信息位置行数方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-08-08
  • Python open()文件处理使用介绍

    Python open()文件处理使用介绍

    这篇文章主要介绍了Python open()文件处理使用介绍,需要的朋友可以参考下
    2014-11-11
  • 一篇文章带你搞定Ubuntu中打开Pycharm总是卡顿崩溃

    一篇文章带你搞定Ubuntu中打开Pycharm总是卡顿崩溃

    这篇文章主要介绍了一篇文章带你搞定Ubuntu中打开Pycharm总是卡顿崩溃,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-11-11
  • python serial串口通信示例详解

    python serial串口通信示例详解

    Python的serial库是一个用于串口通信的强大工具,它提供了一个简单而灵活的接口,可以方便地与串口设备进行通信,包括与驱动电机进行通信,这篇文章主要介绍了python serial串口通信,需要的朋友可以参考下
    2023-12-12

最新评论