keras 쌍둥이 네트워크 기반 이미지 싱크로 율 계산 방식 실현
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 를 각각 인 코딩 하면 두 개의 벡터 를 얻 을 수 있 고 일치 층 에서 두 개의 벡터 를 비교 하여 싱크로 율 을 계산 할 수 있 습 니 다.
네트워크 그림:
데이터 준비:
데 이 터 는 인터넷 의 타 오 바 오 고객 센터 대화 데 이 터 를 바탕 으로 저도 다운로드 페이지 에 넣 을 것 입 니 다.원 데 이 터 는 대화 입 니 다.그 중에서 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 의 1 층 이 있 습 니 다.이 층 을 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('
').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 는 쌍둥이 네트워크 를 바탕 으로 한 사진 싱크로 율 계산 방식 을 실현 하 는 것 이 바로 편집장 이 여러분 에 게 공유 한 모든 내용 입 니 다.여러분 께 참고 가 되 고 저희 도 많이 응원 해 주시 기 바 랍 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
KERA의 반복 레이어 시각적 안내서따라서 그림에서 우리는 크기가 4인 숨겨진 상태가 어떻게 RNN 블록 따라서 전체 문장에 대해 우리는 RNN 층에서 크기가 4인 벡터를 출력합니다. 그림에서 보듯이 우리는 무작위 입력 데이터를 만들었는데 그 중 한 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.