TensorFlow.org에서 보기 |
Google Colab에서 실행하기 |
GitHub에서 소스 보기 |
노트북 다운로드하기 |
TF Hub 모델 보기 |
이 colab에서는 문장 임베딩의 품질을 측정하기 위한 라이브러리인 SentEval 툴킷을 사용하여 범용 문장 인코더 CMLM 모델을 시연합니다. SentEval 툴킷에는 임베딩 모델의 일반화 능력을 평가하고 인코딩된 언어 속성을 평가할 수 있는 다양한 다운스트림 작업 세트가 포함되어 있습니다.
처음 두 코드 블록을 실행하여 환경을 설정하고 세 번째 코드 블록에서 SentEval 작업을 선택하여 모델을 평가할 수 있습니다. 이 Colab을 실행하려면 GPU 런타임을 사용하는 것이 좋습니다.
범용 문장 인코더 CMLM 모델에 대한 자세한 내용은 https://openreview.net/forum?id=WDVD4lUCTzU를 참조하십시오.
Install dependencies
pip install --quiet "tensorflow-text==2.8.*"pip install --quiet torch==1.8.1
SentEval 및 작업 데이터 다운로드
이 단계는 github에서 SentEval을 다운로드하고 데이터 스크립트를 실행하여 작업 데이터를 다운로드합니다. 완료하는 데 최대 5분이 소요될 수 있습니다.
Install SentEval and download task data
rm -rf ./SentEvalgit clone https://github.com/facebookresearch/SentEval.gitcd $PWD/SentEval/data/downstream && bash get_transfer_data.bash > /dev/null 2>&1
Cloning into 'SentEval'... remote: Enumerating objects: 691, done. remote: Counting objects: 100% (2/2), done. remote: Compressing objects: 100% (2/2), done. remote: Total 691 (delta 0), reused 2 (delta 0), pack-reused 689 Receiving objects: 100% (691/691), 33.25 MiB | 27.52 MiB/s, done. Resolving deltas: 100% (434/434), done.
SentEval 평가 작업 실행 다음 코드 블록은 SentEval 작업을 실행하고, 결과를 출력하며, 다음 작업 중 하나를 선택하여 USE CMLM 모델을 평가합니다.
MR CR SUBJ MPQA SST TREC MRPC SICK-E
실행할 모델, 매개변수 및 작업을 선택합니다. 더 빠른 결과를 도출하기 위해 신속한 프로토타이핑 매개변수를 계산 시간을 줄이는 데 사용할 수 있습니다.
일반적으로 '빠른 프로토타이핑' 매개변수로 작업을 완료하는 데 5-15분이 소요되고 '더 느리고 최고의 성능' 매개변수로 작업을 완료하는 데 최대 1시간이 걸립니다.
params = {'task_path': PATH_TO_DATA, 'usepytorch': True, 'kfold': 5}
params['classifier'] = {'nhid': 0, 'optim': 'rmsprop', 'batch_size': 128,
'tenacity': 3, 'epoch_size': 2}
더 나은 결과를 얻으려면 더 느린 '더 느리고 최고의 성능' 매개변수를 사용하십시오. 계산에 최대 1시간이 소요될 수 있습니다.
params = {'task_path': PATH_TO_DATA, 'usepytorch': True, 'kfold': 10}
params['classifier'] = {'nhid': 0, 'optim': 'adam', 'batch_size': 16,
'tenacity': 5, 'epoch_size': 6}
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import sys
sys.path.append(f'{os.getcwd()}/SentEval')
import tensorflow as tf
# Prevent TF from claiming all GPU memory so there is some left for pytorch.
gpus = tf.config.list_physical_devices('GPU')
if gpus:
# Memory growth needs to be the same across GPUs.
for gpu in gpus:
tf.config.experimental.set_memory_growth(gpu, True)
import tensorflow_hub as hub
import tensorflow_text
import senteval
import time
PATH_TO_DATA = f'{os.getcwd()}/SentEval/data'
MODEL = 'https://tfhub.dev/google/universal-sentence-encoder-cmlm/en-base/1'
PARAMS = 'rapid prototyping'
TASK = 'CR'
params_prototyping = {'task_path': PATH_TO_DATA, 'usepytorch': True, 'kfold': 5}
params_prototyping['classifier'] = {'nhid': 0, 'optim': 'rmsprop', 'batch_size': 128,
'tenacity': 3, 'epoch_size': 2}
params_best = {'task_path': PATH_TO_DATA, 'usepytorch': True, 'kfold': 10}
params_best['classifier'] = {'nhid': 0, 'optim': 'adam', 'batch_size': 16,
'tenacity': 5, 'epoch_size': 6}
params = params_best if PARAMS == 'slower, best performance' else params_prototyping
preprocessor = hub.KerasLayer(
"https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3")
encoder = hub.KerasLayer(
"https://tfhub.dev/google/universal-sentence-encoder-cmlm/en-base/1")
inputs = tf.keras.Input(shape=tf.shape(''), dtype=tf.string)
outputs = encoder(preprocessor(inputs))
model = tf.keras.Model(inputs=inputs, outputs=outputs)
def prepare(params, samples):
return
def batcher(_, batch):
batch = [' '.join(sent) if sent else '.' for sent in batch]
return model.predict(tf.constant(batch))["default"]
se = senteval.engine.SE(params, batcher, prepare)
print("Evaluating task %s with %s parameters" % (TASK, PARAMS))
start = time.time()
results = se.eval(TASK)
end = time.time()
print('Time took on task %s : %.1f. seconds' % (TASK, end - start))
print(results)
Evaluating task CR with rapid prototyping parameters
Time took on task CR : 52.8. seconds
{'devacc': 90.42, 'acc': 88.98, 'ndev': 3775, 'ntest': 3775}
자세히 알아보기
- TensorFlow Hub에서 더 많은 텍스트 임베딩 모델 찾기
- 다국어 범용 문장 인코더 CMLM 모델 참조
- 다른 범용 문장 인코더 모델 확인
참고
- Ziyi Yang, Yinfei Yang, Daniel Cer, Jax Law, Eric Darve.
조건부 마스크 언어 모델을 사용한 범용 문장 표현 학습. 2020년 11월
TensorFlow.org에서 보기
Google Colab에서 실행하기
GitHub에서 소스 보기
노트북 다운로드하기
TF Hub 모델 보기