欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

keras实现基于孪生网络的图片相似度计算方式

程序员文章站 2024-01-05 20:44:04
我就废话不多说了,大家还是直接看代码吧!import kerasfrom keras.layers import input,dense,conv2dfrom keras.layers import...

我就废话不多说了,大家还是直接看代码吧!

import keras
from keras.layers import input,dense,conv2d
from keras.layers import maxpooling2d,flatten,convolution2d
from keras.models import model
import os
import numpy as np
from pil import image
from keras.optimizers import sgd
from scipy import misc
root_path = os.getcwd()
train_names = ['bear','blackswan','bus','camel','car','cows','dance','dog','hike','hoc','kite','lucia','mallerd','pigs','soapbox','stro','surf','swing','train','walking']
test_names = ['boat','dance-jump','drift-turn','elephant','libby']
 
def load_data(seq_names,data_number,seq_len): 
#生成图片对
  print('loading data.....')
  frame_num = 51
  train_data1 = []
  train_data2 = []
  train_lab = []
  count = 0
  while count < data_number:
    count = count + 1
    pos_neg = np.random.randint(0,2)
    if pos_neg==0:
      seed1 = np.random.randint(0,seq_len)
      seed2 = np.random.randint(0,seq_len)
      while seed1 == seed2:
       seed1 = np.random.randint(0,seq_len)
       seed2 = np.random.randint(0,seq_len)
      frame1 = np.random.randint(1,frame_num)
      frame2 = np.random.randint(1,frame_num)
      path1 = os.path.join(root_path,'data','simility_data',seq_names[seed1],str(frame1)+'.jpg')
      path2 = os.path.join(root_path, 'data', 'simility_data', seq_names[seed2], str(frame2) + '.jpg')
      image1 = np.array(misc.imresize(image.open(path1),[224,224]))
      image2 = np.array(misc.imresize(image.open(path2),[224,224]))
      train_data1.append(image1)
      train_data2.append(image2)
      train_lab.append(np.array(0))
    else:
     seed = np.random.randint(0,seq_len)
     frame1 = np.random.randint(1, frame_num)
     frame2 = np.random.randint(1, frame_num)
     path1 = os.path.join(root_path, 'data', 'simility_data', seq_names[seed], str(frame1) + '.jpg')
     path2 = os.path.join(root_path, 'data', 'simility_data', seq_names[seed], str(frame2) + '.jpg')
     image1 = np.array(misc.imresize(image.open(path1),[224,224]))
     image2 = np.array(misc.imresize(image.open(path2),[224,224]))
     train_data1.append(image1)
     train_data2.append(image2)
     train_lab.append(np.array(1))
  return np.array(train_data1),np.array(train_data2),np.array(train_lab)
 
def vgg_16_base(input_tensor):
  net = conv2d(64(3,3),activation='relu',padding='same',input_shape=(224,224,3))(input_tensor)
  net = convolution2d(64,(3,3),activation='relu',padding='same')(net)
  net = maxpooling2d((2,2),strides=(2,2))(net)
 
  net = convolution2d(128,(3,3),activation='relu',padding='same')(net)
  net = convolution2d(128,(3,3),activation='relu',padding='same')(net)
  net= maxpooling2d((2,2),strides=(2,2))(net)
 
  net = convolution2d(256,(3,3),activation='relu',padding='same')(net)
  net = convolution2d(256,(3,3),activation='relu',padding='same')(net)
  net = convolution2d(256,(3,3),activation='relu',padding='same')(net)
  net = maxpooling2d((2,2),strides=(2,2))(net)
 
  net = convolution2d(512,(3,3),activation='relu',padding='same')(net)
  net = convolution2d(512,(3,3),activation='relu',padding='same')(net)
  net = convolution2d(512,(3,3),activation='relu',padding='same')(net)
  net = maxpooling2d((2,2),strides=(2,2))(net)
 
  net = convolution2d(512,(3,3),activation='relu',padding='same')(net)
  net = convolution2d(512,(3,3),activation='relu',padding='same')(net)
  net = convolution2d(512,(3,3),activation='relu',padding='same')(net)
  net = maxpooling2d((2,2),strides=(2,2))(net)
  net = flatten()(net)
  return net
 
def siamese(vgg_path=none,siamese_path=none):
  input_tensor = input(shape=(224,224,3))
  vgg_model = model(input_tensor,vgg_16_base(input_tensor))
  if vgg_path:
    vgg_model.load_weights(vgg_path)
  input_im1 = input(shape=(224,224,3))
  input_im2 = input(shape=(224,224,3))
  out_im1 = vgg_model(input_im1)
  out_im2 = vgg_model(input_im2)
  diff = keras.layers.substract([out_im1,out_im2])
  out = dense(500,activation='relu')(diff)
  out = dense(1,activation='sigmoid')(out)
  model = model([input_im1,input_im2],out)
  if siamese_path:
    model.load_weights(siamese_path)
  return model
 
train = true
if train:
  model = siamese(siamese_path='model/simility/vgg.h5')
  sgd = sgd(lr=1e-6,momentum=0.9,decay=1e-6,nesterov=true)
  model.compile(optimizer=sgd,loss='mse',metrics=['accuracy'])
  tensorboard = keras.callbacks.tensorboard(histogram_freq=5,log_dir='log/simility',write_grads=true,write_images=true)
  ckpt = keras.callbacks.modelcheckpoint(os.path.join(root_path,'model','simility','vgg.h5'),
                    verbose=1,period=5)
  train_data1,train_data2,train_lab = load_data(train_names,4000,20)
  model.fit([train_data1,train_data2],train_lab,callbacks=[tensorboard,ckpt],batch_size=64,epochs=50)
else:
  model = siamese(siamese_path='model/simility/vgg.h5')
  test_im1,test_im2,test_labe = load_data(test_names,1000,5)
  tp = 0
  for i in range(1000):
   im1 = np.expand_dims(test_im1[i],axis=0)
   im2 = np.expand_dims(test_im2[i],axis=0)
   lab = test_labe[i]
   pre = model.predict([im1,im2])
   if pre>0.9 and lab==1:
    tp = tp + 1
   if pre<0.9 and lab==0:
    tp = tp + 1
  print(float(tp)/1000)

输入两张图片,标记1为相似,0为不相似。

损失函数用的是简单的均方误差,有待改成siamese的对比损失。

总结:

1.随机生成了几组1000对的图片,测试精度0.7左右,效果一般。

2.问题 1)数据加载没有用生成器,还得继续认真看看文档 2)训练时划分验证集的时候,训练就会报错,什么输入维度的问题,暂时没找到原因 3)输入的shape好像必须给出数字,本想用shape= input_tensor.get_shape(),能训练,不能保存模型,会报(not json serializable,dimension(none))类型错误

补充知识: keras 问答匹配孪生网络文本匹配 rnn 带有数据

用途:

这篇博客解释了如何搭建一个简单的匹配网络。并且使用了keras的lambda层。在建立网络之前需要对数据进行预处理。处理过后,文本转变为id字符序列。将一对question,answer分别编码可以得到两个向量,在匹配层中比较两个向量,计算相似度。

网络图示:

keras实现基于孪生网络的图片相似度计算方式

数据准备:

数据基于网上的淘宝客服对话数据,我也会放在我的下载页面中。原数据是对话,我筛选了其中label为1的对话。然后将对话拆解成qa对,q是用户,a是客服。然后对于每个q,有一个a是匹配的,label为1.再选择一个a,构成新的样本,label为0.

超参数:

比较简单,具体看代码就可以了。

# dialogue max pair q,a
max_pair = 30000
# top k frequent word ,k
max_features = 450
# fixed q,a length
max_sentence_length = 30
embedding_size = 100
batch_size = 600
# learning rate
lr = 0.01
hidden_layer_size = n_hidden_units = 256 # neurons in hidden layer

细节:

导入一些库

# -*- coding: utf-8 -*-
from keras.layers.core import activation, dense, dropout, spatialdropout1d
from keras.layers.embeddings import embedding
from keras.layers.recurrent import lstm
from keras.preprocessing import sequence
from sklearn.model_selection import train_test_split
import collections
import matplotlib.pyplot as plt
import nltk
import numpy as np
import os
import pandas as pd
from alime_data import convert_dialogue_to_pair
from parameter import max_sentence_length,max_features,embedding_size,max_pair,batch_size,hidden_layer_size
data_dir = "../data"
num_epochs = 2
# read training data and generate vocabulary
maxlen = 0
num_recs = 0

数据准备,先统计词频,然后取出top n个常用词,然后将句子转换成 单词id的序列。把句子中的有效id靠右边放,将句子左边补齐padding。然后分成训练集和测试集

word_freqs = collections.counter()
training_data = convert_dialogue_to_pair(max_pair)
num_recs = len([1 for r in training_data.iterrows()])
 
#for line in ftrain:
for line in training_data.iterrows():
  label ,sentence_q = line[1]['label'],line[1]['sentence_q']
  label ,sentence_a = line[1]['label'],line[1]['sentence_a']
  words = nltk.word_tokenize(sentence_q.lower())#.decode("ascii", "ignore")
  if len(words) > maxlen:
    maxlen = len(words)
  for word in words:
    word_freqs[word] += 1
  words = nltk.word_tokenize(sentence_a.lower())#.decode("ascii", "ignore")
  if len(words) > maxlen:
    maxlen = len(words)
  for word in words:
    word_freqs[word] += 1
  #num_recs += 1
## get some information about our corpus
 
# 1 is unk, 0 is pad
# we take max_features-1 featurs to accound for pad
vocab_size = min(max_features, len(word_freqs)) + 2
word2index = {x[0]: i+2 for i, x in enumerate(word_freqs.most_common(max_features))}
word2index["pad"] = 0
word2index["unk"] = 1
index2word = {v:k for k, v in word2index.items()}
# convert sentences to sequences
x_q = np.empty((num_recs, ), dtype=list)
x_a = np.empty((num_recs, ), dtype=list)
y = np.zeros((num_recs, ))
i = 0
def chinese_split(x):
  return x.split(' ')
 
for line in training_data.iterrows():
  label ,sentence_q,sentence_a = line[1]['label'],line[1]['sentence_q'],line[1]['sentence_a']
  #label, sentence = line.strip().split("\t")
  #print(label,sentence)
  #words = nltk.word_tokenize(sentence_q.lower())
  words = chinese_split(sentence_q)
  seqs = []
  for word in words:
    if word in word2index.keys():
      seqs.append(word2index[word])
    else:
      seqs.append(word2index["unk"])
  x_q[i] = seqs
  #print('add_q')
  #words = nltk.word_tokenize(sentence_a.lower())
  words = chinese_split(sentence_a)
  seqs = []
  for word in words:
    if word in word2index.keys():
      seqs.append(word2index[word])
    else:
      seqs.append(word2index["unk"])
  x_a[i] = seqs
  y[i] = int(label)
  i += 1
# pad the sequences (left padded with zeros)
x_a = sequence.pad_sequences(x_a, maxlen=max_sentence_length)
x_q = sequence.pad_sequences(x_q, maxlen=max_sentence_length)
x = []
for i in range(len(x_a)):
  concat = [x_q[i],x_a[i]]
  x.append(concat)
 
# split input into training and test
xtrain, xtest, ytrain, ytest = train_test_split(x, y, test_size=0.2,
                        random_state=42)
#print(xtrain.shape, xtest.shape, ytrain.shape, ytest.shape)
xtrain_q = [e[0] for e in xtrain]
xtrain_a = [e[1] for e in xtrain]
xtest_q = [e[0] for e in xtest]
xtest_a = [e[1] for e in xtest]

最后建立网络。先定义两个函数,一个是句子编码器,另一个是lambda层,计算两个向量的绝对差。将qa分别用encoder处理得到两个向量,把两个向量放入lambda层。最后有了2*hidden size的一层,将这一层接一个dense层,接activation,得到分类概率。

from keras.layers.wrappers import bidirectional
from keras.layers import input,lambda
from keras.models import model
 
def encoder(inputs_seqs,rnn_hidden_size,dropout_rate):
  x_embed = embedding(vocab_size, embedding_size, input_length=max_sentence_length)(inputs_seqs)
  inputs_drop = spatialdropout1d(0.2)(x_embed)
  encoded_q = bidirectional(
    lstm(rnn_hidden_size, dropout=dropout_rate, recurrent_dropout=dropout_rate, name='rnn'))(inputs_drop)
  return encoded_q
 
def absolute_difference(vecs):
  a,b =vecs
  #d = a-b
  return abs(a - b)
 
inputs_q = input(shape=(max_sentence_length,), name="input")
# x_embed = embedding(vocab_size, embedding_size, input_length=max_sentence_length)(inputs_q)
# inputs_drop = spatialdropout1d(0.2)(x_embed)
# encoded_q = bidirectional(lstm(hidden_layer_size, dropout=0.2, recurrent_dropout=0.2,name= 'rnn'))(inputs_drop)
inputs_a = input(shape=(max_sentence_length,), name="input_a")
# x_embed = embedding(vocab_size, embedding_size, input_length=max_sentence_length)(inputs_a)
# inputs_drop = spatialdropout1d(0.2)(x_embed)
# encoded_a = bidirectional(lstm(hidden_layer_size, dropout=0.2, recurrent_dropout=0.2,name= 'rnn'))(inputs_drop)
encoded_q = encoder(inputs_q,hidden_layer_size,0.1)
encoded_a = encoder(inputs_a,hidden_layer_size,0.1)
 
# import tensorflow as tf
# difference = tf.subtract(encoded_q, encoded_a)
# difference = tf.abs(difference)
similarity = lambda(absolute_difference)([encoded_q, encoded_a])
# x = concatenate([encoded_q, encoded_a])
#
# matching_x = dense(128)(x)
# matching_x = activation("sigmoid")(matching_x)
polar = dense(1)(similarity)
prop = activation("sigmoid")(polar)
model = model(inputs=[inputs_q,inputs_a], outputs=prop)
model.compile(loss="binary_crossentropy", optimizer="adam",
       metrics=["accuracy"])
training_history = model.fit([xtrain_q, xtrain_a], ytrain, batch_size=batch_size,
               epochs=num_epochs,
               validation_data=([xtest_q,xtest_a], ytest))
# plot loss and accuracy
def plot(training_history):
  plt.subplot(211)
  plt.title("accuracy")
  plt.plot(training_history.history["acc"], color="g", label="train")
  plt.plot(training_history.history["val_acc"], color="b", label="validation")
  plt.legend(loc="best")
 
  plt.subplot(212)
  plt.title("loss")
  plt.plot(training_history.history["loss"], color="g", label="train")
  plt.plot(training_history.history["val_loss"], color="b", label="validation")
  plt.legend(loc="best")
  plt.tight_layout()
  plt.show()
 
# evaluate
score, acc = model.evaluate([xtest_q,xtest_a], ytest, batch_size = batch_size)
print("test score: %.3f, accuracy: %.3f" % (score, acc))
 
for i in range(25):
  idx = np.random.randint(len(xtest_q))
  #idx2 = np.random.randint(len(xtest_a))
  xtest_q = xtest_q[idx].reshape(1,max_sentence_length)
  xtest_a = xtest_a[idx].reshape(1,max_sentence_length)
  ylabel = ytest[idx]
  ypred = model.predict([xtest_q,xtest_a])[0][0]
  sent_q = " ".join([index2word[x] for x in xtest_q[0].tolist() if x != 0])
  sent_a = " ".join([index2word[x] for x in xtest_a[0].tolist() if x != 0])
  print("%.0f\t%d\t%s\t%s" % (ypred, ylabel, sent_q,sent_a))

最后是处理数据的函数,写在另一个文件里。

import nltk
from parameter import max_features,max_sentence_length
import pandas as pd
from collections import counter
def get_pair(number, dialogue):
  pairs = []
  for conversation in dialogue:
    utterances = conversation[2:].strip('\n').split('\t')
    # print(utterances)
    # break
 
    for i, utterance in enumerate(utterances):
      if i % 2 != 0: continue
      pairs.append([utterances[i], utterances[i + 1]])
      if len(pairs) >= number:
        return pairs
  return pairs
 
 
def convert_dialogue_to_pair(k):
  dialogue = open('dialogue_alibaba2.txt', encoding='utf-8', mode='r')
  dialogue = dialogue.readlines()
  dialogue = [p for p in dialogue if p.startswith('1')]
  print(len(dialogue))
  pairs = get_pair(k, dialogue)
  # break
  # print(pairs)
  data = []
  for p in pairs:
    data.append([p[0], p[1], 1])
  for i, p in enumerate(pairs):
    data.append([p[0], pairs[(i + 8) % len(pairs)][1], 0])
  df = pd.dataframe(data, columns=['sentence_q', 'sentence_a', 'label'])
 
  print(len(data))
  return df

以上这篇keras实现基于孪生网络的图片相似度计算方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

上一篇:

下一篇: