最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

keras的siamese(孿生網(wǎng)絡(luò))實(shí)現(xiàn)案例

 更新時(shí)間:2020年06月12日 14:20:25   作者:李上花開(kāi)  
這篇文章主要介紹了keras的siamese(孿生網(wǎng)絡(luò))實(shí)現(xiàn)案例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧

代碼位于keras的官方樣例,并做了微量修改和大量學(xué)習(xí)?。

最終效果:

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(孿生網(wǎng)絡(luò))實(shí)現(xiàn)案例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Python+selenium 獲取瀏覽器窗口坐標(biāo)、句柄的方法

    Python+selenium 獲取瀏覽器窗口坐標(biāo)、句柄的方法

    今天小編就為大家分享一篇Python+selenium 獲取瀏覽器窗口坐標(biāo)、句柄的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2018-10-10
  • linux環(huán)境打包python工程為可執(zhí)行程序的過(guò)程

    linux環(huán)境打包python工程為可執(zhí)行程序的過(guò)程

    本次需求,在ubuntu上面開(kāi)發(fā)的python代碼程序需要打包成一個(gè)可執(zhí)行程序然后交付給甲方,因?yàn)椴荒苤苯咏o源碼給甲方,所以尋找方法將python開(kāi)發(fā)的源碼打包成一個(gè)可執(zhí)行程序,本次在ubuntu上打包python源碼的方法和在window上打包的有點(diǎn)類似,感興趣的朋友跟隨小編一起看看吧
    2024-01-01
  • Python處理文本換行符實(shí)例代碼

    Python處理文本換行符實(shí)例代碼

    這篇文章主要介紹了Python處理文本換行符實(shí)例代碼,分享了相關(guān)代碼示例,小編覺(jué)得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下
    2018-02-02
  • Flask搭建Web應(yīng)用程序的方法示例

    Flask搭建Web應(yīng)用程序的方法示例

    Flask是一個(gè)使用Python編寫的輕量級(jí)Web應(yīng)用框架,本文我們將介紹一個(gè)使用Flask逐步搭建Web應(yīng)用程序的簡(jiǎn)單入門示例,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2024-01-01
  • Python 3.8正式發(fā)布重要新功能一覽

    Python 3.8正式發(fā)布重要新功能一覽

    最新版本的Python發(fā)布了!今年夏天,Python 3.8發(fā)布beta版本,但在2019年10月14日,第一個(gè)正式版本已準(zhǔn)備就緒?,F(xiàn)在,我們都可以開(kāi)始使用新功能并從最新改進(jìn)中受益
    2019-10-10
  • python游戲開(kāi)發(fā)的五個(gè)案例分享

    python游戲開(kāi)發(fā)的五個(gè)案例分享

    本文給大家分享了作者整理的五個(gè)python游戲開(kāi)發(fā)的案例,通過(guò)具體設(shè)計(jì)思路,代碼等方面詳細(xì)了解python游戲開(kāi)發(fā)的過(guò)程,非常的詳細(xì),希望大家能夠喜歡
    2020-03-03
  • Python實(shí)現(xiàn)打印詳細(xì)報(bào)錯(cuò)日志,獲取報(bào)錯(cuò)信息位置行數(shù)

    Python實(shí)現(xiàn)打印詳細(xì)報(bào)錯(cuò)日志,獲取報(bào)錯(cuò)信息位置行數(shù)

    這篇文章主要介紹了Python實(shí)現(xiàn)打印詳細(xì)報(bào)錯(cuò)日志,獲取報(bào)錯(cuò)信息位置行數(shù)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-08-08
  • Python open()文件處理使用介紹

    Python open()文件處理使用介紹

    這篇文章主要介紹了Python open()文件處理使用介紹,需要的朋友可以參考下
    2014-11-11
  • 一篇文章帶你搞定Ubuntu中打開(kāi)Pycharm總是卡頓崩潰

    一篇文章帶你搞定Ubuntu中打開(kāi)Pycharm總是卡頓崩潰

    這篇文章主要介紹了一篇文章帶你搞定Ubuntu中打開(kāi)Pycharm總是卡頓崩潰,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2020-11-11
  • python serial串口通信示例詳解

    python serial串口通信示例詳解

    Python的serial庫(kù)是一個(gè)用于串口通信的強(qiáng)大工具,它提供了一個(gè)簡(jiǎn)單而靈活的接口,可以方便地與串口設(shè)備進(jìn)行通信,包括與驅(qū)動(dòng)電機(jī)進(jìn)行通信,這篇文章主要介紹了python serial串口通信,需要的朋友可以參考下
    2023-12-12

最新評(píng)論

偃师市| 荔浦县| 通渭县| 县级市| 洛川县| 抚远县| 新余市| 永寿县| 沛县| 阿城市| 宝鸡市| 商都县| 奎屯市| 南陵县| 平遥县| 台南市| 嘉义市| 赤水市| 图们市| 涿鹿县| 离岛区| 丹凤县| 湛江市| 拜泉县| 手游| 盐源县| 六安市| 长寿区| 广河县| 赤城县| 罗定市| 冕宁县| 沈阳市| 河东区| 云林县| 吴江市| 贞丰县| 内黄县| 延寿县| 万荣县| 吐鲁番市|