다국어 범용 문장 인코더 Q&A 검색

이 사용하는 데모입니다 유니버설 인코더 다국어 Q & A 모델 , 텍스트의 질의 응답 검색을위한을 question_encoder 및 모델의 response_encoder의 사용을 설명. 우리는에서 문장을 사용하는 분대 response_encoder 높은 차원 묻어로 인코딩 된 데모 세트, 각 문장과 문맥 (문장을 둘러싸고있는 텍스트)로 단락. 이 묻어은 사용하여 구축 인덱스에 저장됩니다 simpleneighbors의 질의 응답 검색을위한 라이브러리를.

검색에 임의의 질문은에서 선택되는 분대 데이터 세트와 question_encoder과 의미 공간에서 대략 가까운 이웃의 목록을 반환하는 쿼리 simpleneighbors 지수와 내장 높은 차원으로 인코딩.

더 많은 모델

당신은 모델을 내장 현재의 모든 호스트 텍스트 찾을 수 있습니다 여기에 잘 같은 팀에서 훈련을받은 모든 모델 여기를 .

설정

설정 환경

%%capture
# Install the latest Tensorflow version.
!pip install -q tensorflow_text
!pip install -q simpleneighbors[annoy]
!pip install -q nltk
!pip install -q tqdm

일반적인 가져오기 및 기능 설정

import json
import nltk
import os
import pprint
import random
import simpleneighbors
import urllib
from IPython.display import HTML, display
from tqdm.notebook import tqdm

import tensorflow.compat.v2 as tf
import tensorflow_hub as hub
from tensorflow_text import SentencepieceTokenizer

nltk
.download('punkt')


def download_squad(url):
 
return json.load(urllib.request.urlopen(url))

def extract_sentences_from_squad_json(squad):
  all_sentences
= []
 
for data in squad['data']:
   
for paragraph in data['paragraphs']:
      sentences
= nltk.tokenize.sent_tokenize(paragraph['context'])
      all_sentences
.extend(zip(sentences, [paragraph['context']] * len(sentences)))
 
return list(set(all_sentences)) # remove duplicates

def extract_questions_from_squad_json(squad):
  questions
= []
 
for data in squad['data']:
   
for paragraph in data['paragraphs']:
     
for qas in paragraph['qas']:
       
if qas['answers']:
          questions
.append((qas['question'], qas['answers'][0]['text']))
 
return list(set(questions))

def output_with_highlight(text, highlight):
  output
= "<li> "
  i
= text.find(highlight)
 
while True:
   
if i == -1:
      output
+= text
     
break
    output
+= text[0:i]
    output
+= '<b>'+text[i:i+len(highlight)]+'</b>'
    text
= text[i+len(highlight):]
    i
= text.find(highlight)
 
return output + "</li>\n"

def display_nearest_neighbors(query_text, answer_text=None):
  query_embedding
= model.signatures['question_encoder'](tf.constant([query_text]))['outputs'][0]
  search_results
= index.nearest(query_embedding, n=num_results)

 
if answer_text:
    result_md
= '''
    <p>Random Question from SQuAD:</p>
    <p>&nbsp;&nbsp;<b>%s</b></p>
    <p>Answer:</p>
    <p>&nbsp;&nbsp;<b>%s</b></p>
    '''
% (query_text , answer_text)
 
else:
    result_md
= '''
    <p>Question:</p>
    <p>&nbsp;&nbsp;<b>%s</b></p>
    '''
% query_text

  result_md
+= '''
    <p>Retrieved sentences :
    <ol>
  '''


 
if answer_text:
   
for s in search_results:
      result_md
+= output_with_highlight(s, answer_text)
 
else:
   
for s in search_results:
      result_md
+= '<li>' + s + '</li>\n'

  result_md
+= "</ol>"
  display
(HTML(result_md))

[nltk_data] Downloading package punkt to /home/kbuilder/nltk_data...
[nltk_data]   Unzipping tokenizers/punkt.zip.

다음 코드 블록을 실행하여 SQuAD 데이터 세트를 다운로드하고 추출합니다.

  • NLTK 라이브러리와 문장 및 단락 텍스트를 형성한다 (텍스트, 문맥) 튜플을 사용하여 문장으로 갈라되는 데이터 세트 스쿼드에서 각 단락 - 문장 (텍스트, 문맥) 튜플의 목록입니다.
  • 질문 (질문, 답) 튜플의 목록입니다.

SQUAD 데이터 다운로드 및 추출

squad_url = 'https://rajpurkar.github.io/SQuAD-explorer/dataset/dev-v1.1.json'

squad_json
= download_squad(squad_url)
sentences
= extract_sentences_from_squad_json(squad_json)
questions
= extract_questions_from_squad_json(squad_json)
print("%s sentences, %s questions extracted from SQuAD %s" % (len(sentences), len(questions), squad_url))

print("\nExample sentence and context:\n")
sentence
= random.choice(sentences)
print("sentence:\n")
pprint
.pprint(sentence[0])
print("\ncontext:\n")
pprint
.pprint(sentence[1])
print()
10455 sentences, 10552 questions extracted from SQuAD https://rajpurkar.github.io/SQuAD-explorer/dataset/dev-v1.1.json

Example sentence and context:

sentence:

('The Mongol Emperors had built large palaces and pavilions, but some still '
 'continued to live as nomads at times.')

context:

("Since its invention in 1269, the 'Phags-pa script, a unified script for "
 'spelling Mongolian, Tibetan, and Chinese languages, was preserved in the '
 'court until the end of the dynasty. Most of the Emperors could not master '
 'written Chinese, but they could generally converse well in the language. The '
 'Mongol custom of long standing quda/marriage alliance with Mongol clans, the '
 'Onggirat, and the Ikeres, kept the imperial blood purely Mongol until the '
 'reign of Tugh Temur, whose mother was a Tangut concubine. The Mongol '
 'Emperors had built large palaces and pavilions, but some still continued to '
 'live as nomads at times. Nevertheless, a few other Yuan emperors actively '
 'sponsored cultural activities; an example is Tugh Temur (Emperor Wenzong), '
 'who wrote poetry, painted, read Chinese classical texts, and ordered the '
 'compilation of books.')

다음 코드 블록 설정와 tensorflow 그래프 g 세션 범용 언어 인코더 Q & A 모델question_encoderresponse_encoder 서명.

tensorflow 허브에서 모델 로드

module_url = "https://tfhub.dev/google/universal-sentence-encoder-multilingual-qa/3"
model
= hub.load(module_url)

다음 코드 블록은 모든 텍스트, 상황에 맞는 튜플에 대한 묻어을 계산하고에 저장 simpleneighbors의 response_encoder를 사용하여 인덱스입니다.

임베딩 계산 및 simpleneighbors 인덱스 구축

batch_size = 100

encodings
= model.signatures['response_encoder'](
  input
=tf.constant([sentences[0][0]]),
  context
=tf.constant([sentences[0][1]]))
index
= simpleneighbors.SimpleNeighbors(
    len
(encodings['outputs'][0]), metric='angular')

print('Computing embeddings for %s sentences' % len(sentences))
slices
= zip(*(iter(sentences),) * batch_size)
num_batches
= int(len(sentences) / batch_size)
for s in tqdm(slices, total=num_batches):
  response_batch
= list([r for r, c in s])
  context_batch
= list([c for r, c in s])
  encodings
= model.signatures['response_encoder'](
    input
=tf.constant(response_batch),
    context
=tf.constant(context_batch)
 
)
 
for batch_index, batch in enumerate(response_batch):
    index
.add_one(batch, encodings['outputs'][batch_index])

index
.build()
print('simpleneighbors index for %s sentences built.' % len(sentences))

Computing embeddings for 10455 sentences
0%|          | 0/104 [00:00<?, ?it/s]
simpleneighbors index for 10455 sentences built.

검색에 문제가 question_encoder을 사용하여 인코딩하고 질문 삽입은 simpleneighbors 인덱스를 쿼리하는 데 사용됩니다.

SQuAD에서 무작위 질문에 대한 가장 가까운 이웃 검색

num_results = 25

query
= random.choice(questions)
display_nearest_neighbors
(query[0], query[1])