handling_sparse_features.ipynb
Run, share, and edit Python notebooks
colab.research.google.com
TF-Ranking library tutorial
context가 주어지면, examples의 최적의 list를 제공한다. 예를 들어서 검색 엔진의 경우, query가 주어지면 최적의 document list가 주어진다. 보통 user relevance feedback을 기존으로 학습되는데 human ratings( explicit ), clicks( implicit )가 될 수 있다.
그래서 우리는 지금부터 textual data를 통해서 ranking estimator을 만들고자 한다. 데이터는 사용자에 의해서 relevance가 정해진다.
search: 쿼리와 문서 타이틀이 주어진다.
question answering: 질문과 대답이 주어진다.
recommendation: title과 description이 주어진다.
이 튜토리얼에서는 2번째인 question answering task를 해결해보고자 한다.
1) 데이터셋
ANTIQUE: 2,626개의 다양한 종류의 질문으로 구성되어 있는 데이터셋이다. 34,011개의 relevance annotation으로 1-5 scale로 구성되어 있다. 각 answer list는 size가 다양해서 trucate, padd with dummies를 사용하여 고정된 50개로 사용하고자 한다.
https://paperswithcode.com/dataset/antique
train은 2206개, test는 200개로 구성되어있다.
>>다운로드 코드
wget은 웹서버로부터 콘텐츠를 가져오는 코드다. 아래 링크를 통하여 데이터를 받을 수 있다.
https://ciir.cs.umass.edu/download
Downloads | Center for Intelligent Information Retrieval | UMass Amherst
Downloads The following material is available for download from the CIIR. It is provided without warranty and without support. If there are problems accessing or using any of this material, we would appreciate being told (info at ciir.cs.umass.edu), in cas
ciir.cs.umass.edu
!wget -O "/tmp/vocab.txt" "http://ciir.cs.umass.edu/downloads/Antique/tf-ranking/vocab.txt"
!wget -O "/tmp/train.tfrecords" "http://ciir.cs.umass.edu/downloads/Antique/tf-ranking/ELWC/train.tfrecords"
!wget -O "/tmp/test.tfrecords" "http://ciir.cs.umass.edu/downloads/Antique/tf-ranking//ELWC/test.tfrecords"
2) 목적
query가 주어지면, ranking metric을 극대화하는 최적의 answer list를 반환한다.
3) data formats
폴더에는 TFRecords로 인코딩되고 ELWC 형태의 train, test files가 있다.
protobuffer은 직렬화 데이터 구조로 데이터를 저장하는 구조를 의미한다. protobuffer message는 직렬화 데이터 구조의 설명으로 어떻게 구조가 되어있는 지를 말해준다.
1) protocol buffer = 데이터를 직렬화했을때 표현되는 Format
= ELWC( ExampleListWithContext ) -> format 중 하나의 종류임
2) protocol buffer message = message = protobuf = 위 format에 대한 description = proto file
= tf.Example -> Proto 중 하나의 종류임
여기서는 ranking의 context와 example feature를 tf.Example message로 변환하고 이를 ELWC라는 protocol buffer(=serialized format)을 사용하여 data를 저장하였다. 그리고 이것을 TFRecord로 쉽게 바꿀 수 있다.
이렇게 바뀐다면 데이터 로딩 속도를 향상시킬 수 있다.
>> import 코드
!pip install -q tensorflow_ranking tensorflow-serving-api
여기서 tensorflow serving이란, 모델의 학습이 끝나고 이를 실제 production 환경에 응용하기 위해서 inference할 수 있는 시스템을 구축해야하는데 tensorflow serving이 이 과정을 최적화된 형태로 지원한다. docker와 함께 이 api를 활용하여 머신러닝 모델을 활용할 수있도록 도와준다.
from tensorflow_serving.apis import input_pb2: protocol buffer를 불러오는 라이브러리인 것 같음 모르겠당...
-> https://pypi.org/project/tensorflow-serving-api/#description
tensorflow-serving-api
TensorFlow Serving Python API.
pypi.org
>> 코드
from google.protobuf import text_format: text representaion of protocol message를 text_format.Parse를 통해서 다시 message로 복귀 시킬 수 있다.
>>코드
proto 문법을 모르는데 아무튼 아래의 text representation of message를 text_format.parse에 넣어주면 tf.train.Example message가 나오게 된다. 이를 통해 context feature에 맞는 message(=data structure description)를 만들어냈다.
from google.protobuf import text_format
CONTEXT = text_format.Parse(
"""
features {
feature {
key: "query_tokens"
value { bytes_list { value: ["this", "is", "a", "relevant", "question"] } }
}
}""", tf.train.Example())
>>코드
ELWC = input_pb2.ExampleListWithContext(): ELWC formatter 객체를 만들어준다.
ELWC.context.CopyFrom(CONTEXT) : ELWC format에 맞게 context feature를 넣어준다.
for example in EXAMPLES:
example_features = ELWC.examples.add()
example_features.CopyFrom(example): 위와 마찬가지로 example feature도 넣어준다.
이렇게하면 protocol buffer인 ELWC format에 맞는 data가 만들어진다. 이것을 쉽게 TFRecord file로 바꿀 수 있다.
TF-Ranking transform data to ELWC - ExampleListWithContext form
I have read all the guides, videos, and everything, but I have no idea how to convert my feature set to an ELWC datasheet format for TF-Rank ListWise problem. There is no description of this struct...
stackoverflow.com
**TFRecord & tf.Example
TFRecord file로 데이터를 바꿔주면 데이터를 로딩하는 속도가 훨씬 빨라진다. 이때 protocol buffer masseges는 data를 TFRecord files로 바꾸는 쉬운 방법이다.
protocol buffer에는 data structure에 대한 description이 protocol buffer message로 작성되어 있다. 그리고 이것은 .proto file로 저장된다. 이렇게 작성된 protocol buffer message는 protocol buffer compiler에게 data를 저장하는 방법, encoding, parsing을 알려준다.
텐서플로우에서는 사용되는 protocol buffer messages는 아래와 같다.1) data types: tf.train.BytesList: string-bytetf.train.FloatList: float-doubletf.train.Int64List: bool-enum-int32-uint32-int64-uint64
2) tf.train.feature: 위의 셋 중 하나의 type을 선택한다.
3) tf.train.features: {"string": tf.train.feature}
data를 최종적으로 tf.train.Example message로 바꿔야 TFRecord file로 바꿀 수 있는데 이 과정을 살펴보자.
data -> dataset -> dataset의 각 feature -> tf.train.Feature -> tf.train.Feature로 구성된 이름이 feature인 dictionary -> tf.train.Features( feature = feature ) -> tf.train.Example( 방금 만든 tf.train.Features ) -> TFRecord file (byte-string으로 바꾸면 된다.)
https://towardsdatascience.com/working-with-tfrecords-and-tf-train-example-36d111b3ff4d
Working with TFRecords and tf.train.Example
Creating tf.train.Example messages from data and writing and reading TFRecords
towardsdatascience.com
What are the advantages of using tf.train.SequenceExample over tf.train.Example for variable length features?
Recently I read this guide on undocumented featuers in TensorFlow, as I needed to pass variable length sequences as input. However, I found the protocol for tf.train.SequenceExample relatively conf...
stackoverflow.com
https://www.machinelearningmindset.com/tfrecords-for-tensorflow/
**eager execution
그래프를 만들지 않고 즉시, 계산하는 방법
**out of the box
아무런 추가 설치 없이 기본으로 사용할 수 있는 기능
**data point = single row in my data
어쨋든 데이터의 구성을 바꿔서 ranking model에서 사용할 수 있도록 변환하였다.
4) train & test path along with model hyperparameters
train, test, vocab path를 정해준다. 각 데이터셋이 위의 과정을 거쳐서 TFRecord file형태로 저장되어 있고 덕분에 빠른 속도로 모델에 로딩이 가능하다.
list_size, padding_label, learning rate, batch size,
hidden layer dims, drop out ratio, group size, model dir, train steps
5) components of a ranking estimator
- input reader
- transform fucn
- scoring func
- ranking losses, metrics
- head
- model builder
6) feature columns
csv에서 읽은 데이터를 모델 훈련에 필요한 feature로 매핑할때 feature column을 사용한다.
contest features, example features를 필요한 feature columns를 만들어보자.
예를 들어서, 문자열은 모델에 바로 주입할 수 없는데 feature_column.categorical_column_with_vocabulary_list 를 사용하여 문자열을 원-핫 벡터로 표현할 수 있습니다.
또 다르게 embedding column의 경우에는 sparse vector을 dense vector로 바꿔줍니다.
어쨋든 raw data를 가공해주는 역할을 합니다.
>>코드
_EMBEDDING_DIMENSION = 20
def context_feature_columns():
"""Returns context feature names to column definitions."""
sparse_column = tf.feature_column.categorical_column_with_vocabulary_file(
key="query_tokens",
vocabulary_file=_VOCAB_PATH)
query_embedding_column = tf.feature_column.embedding_column(
sparse_column, _EMBEDDING_DIMENSION)
return {"query_tokens": query_embedding_column}
def example_feature_columns():
"""Returns the example feature columns."""
sparse_column = tf.feature_column.categorical_column_with_vocabulary_file(
key="document_tokens",
vocabulary_file=_VOCAB_PATH)
document_embedding_column = tf.feature_column.embedding_column(
sparse_column, _EMBEDDING_DIMENSION)
return {"document_tokens": document_embedding_column}
raw data를 estimator가 사용할 수 있도록 중재자 역할을 하는 feature column으로 바꿔줍니다. 예를 들어서 string type의 경우, 모델이 바로 사용할 수 없습니다. 그래서 vocab을 기반으로 one-hot-vector(sparse)로 바꿔주고 embedding으로 dense vector로 바꿔줄 수 있습니다.
7) input reader
tf.data.TFRecordDataset: TFRecord파일은 바이너리 데이터 포맷으로 구글의 protocol buffer 포맷으로 데이터를 파일에 serialize하여 저장한다.
tf.feature_column.make_parse_example_spec: input feature_columns로부터 pasing spec dictionary를 만든다.
tf.compat.v1.data.make_one_shot_iterator: dataset의 원소를 위한 iterator을 만들어낸다.
context_feature_spec, label_column, example_feature_spec을 만들어서 dataset만들고 거기서 label과 feature을 추출한다.
8) feature transformation
sparse feature to dense feature. as nn layers usually take dense features as inputs.
tensorflow_ranking.feature.encode_listwise_features:
9) scoring function
query-doc pair을 model에 넣어주면 relevance score을 구해준다.
tf.comapt.v1.name_scope("input_layer"): class name_scope는 prefix로 모든 operation 앞에 해당 이름을 추가해준다.
with tf.name_scope("MyOp") as scope: 라고 하면 이 안의 모든 op앞에 myop가 추가된다.
tf.compat.v1.layers.flatten(context_features[name]):tf.layers namespace의 모든 api 중 flatten은 input tensor을 flatten시킨다.
**tf.compat.v1은 텐서플로우의 모든 인터페이스를 이 모듈로 읽어드린다.
10) loss, metric, head
tf.compat.v1.GraphKeys: graph collections를 사용하기 위한 이름
tf.compat.v1.get_collection: name과 함께 list of values in collection이 주어진다.
tf.compat.v1.train.get_global_step(): return global step variable
11) model builder
tf.estimator.RunConfig: configurations를 정해준다.
model dir, random_seed, ...
tf.estimator.Estimator: train & evaluate위한 tensorflow models.
tf.estimator.TrainSpec
tf.estimator.EvalSpec
throttle_secs
12) tensorboard
ranking metric을 그래프와 함께 확인할 수 있다.
%load_ext tensorboard
%tensorboard --logdir="/tmp/ranking_model_dir" --port 12345
13) generating predictions
학습과 검증을 위한 input_fn과 마찬가지로 predict_input_fn도 데이터를 ELWC 형태로 읽고, TFRecords로 저장하여 feature을 생성한다.
context, example features를 통해서 label을 추측한다.
ranker.predict는 generator을 반환한다.
'이제는 사용하지 않는 공부방 > Artificial intelligence' 카테고리의 다른 글
[밑바닥부터 시작하는 딥러닝2] word2vec (0) | 2021.06.05 |
---|---|
[tensorflow] 텐서플로우 여러가지 기능 (0) | 2021.06.02 |
[추천시스템] (2) LearningToRank 논문정리 (0) | 2021.05.29 |
[밑바닥부터 시작하는 딥러닝2] 자연어와 단어의 분산표현 (0) | 2021.05.29 |
[밑바닥부터 시작하는 딥러닝] 8강 더 깊게 딥러닝 (0) | 2021.05.21 |