このライブラリを使用すると、PythonでTrecordファイルを効率的に読み書きできます。ライブラリは、PytorchのTFrecordファイルのIterableDatasetリーダーも提供しています。現在、圧縮されていない圧縮されていないGZIP TFrecordsがサポートされています。
pip3 install 'tfrecord[torch]'
Trecordファイルごとにインデックスファイルを作成することをお勧めします。複数のワーカーを使用する場合は、インデックスファイルを提供する必要があります。そうしないと、ローダーが重複したレコードを返す場合があります。このユーティリティプログラムを使用して、個々のtfrecordファイルのインデックスファイルを作成できます。
python3 -m tfrecord.tools.tfrecord2idx <tfrecord path> <index path>
ディレクトリの実行に「 .tfidnex」ファイルを作成するには、 " .tfrecord"ファイルを作成します。
tfrecord2idx <data dir>
tfrecorddatasetを使用して、pytorchのtfrecordファイルを読み取ります。
import torch
from tfrecord . torch . dataset import TFRecordDataset
tfrecord_path = "/tmp/data.tfrecord"
index_path = None
description = { "image" : "byte" , "label" : "float" }
dataset = TFRecordDataset ( tfrecord_path , index_path , description )
loader = torch . utils . data . DataLoader ( dataset , batch_size = 32 )
data = next ( iter ( loader ))
print ( data )MultitFrecordDatasetを使用して、複数のTFrecordファイルを読み取ります。このクラスは、指定された確率で与えられたTrecordファイルからサンプルします。
import torch
from tfrecord . torch . dataset import MultiTFRecordDataset
tfrecord_pattern = "/tmp/{}.tfrecord"
index_pattern = "/tmp/{}.index"
splits = {
"dataset1" : 0.8 ,
"dataset2" : 0.2 ,
}
description = { "image" : "byte" , "label" : "int" }
dataset = MultiTFRecordDataset ( tfrecord_pattern , index_pattern , splits , description )
loader = torch . utils . data . DataLoader ( dataset , batch_size = 32 )
data = next ( iter ( loader ))
print ( data )デフォルトでは、 MultiTFRecordDataset無限であるため、データを永久にサンプリングします。適切なフラグを提供することで有限にすることができます
dataset = MultiTFRecordDataset(..., infinite=False)
キューサイズを提供すると、TfrecorddatasetとMultitfrecorddatasetの両方がデータを自動的にシャッフルします。
dataset = TFRecordDataset(..., shuffle_queue_size=1024)
オプションで関数をtransform引数として渡すことができ、返却前に機能の後処理を実行することができます。これは、たとえば、画像をデコードしたり、色を特定の範囲またはパッド変数の長さシーケンスに正規化するために使用できます。
import tfrecord
import cv2
def decode_image ( features ):
# get BGR image from bytes
features [ "image" ] = cv2 . imdecode ( features [ "image" ], - 1 )
return features
description = {
"image" : "bytes" ,
}
dataset = tfrecord . torch . TFRecordDataset ( "/tmp/data.tfrecord" ,
index_path = None ,
description = description ,
transform = decode_image )
data = next ( iter ( dataset ))
print ( data ) import tfrecord
writer = tfrecord . TFRecordWriter ( "/tmp/data.tfrecord" )
writer . write ({
"image" : ( image_bytes , "byte" ),
"label" : ( label , "float" ),
"index" : ( index , "int" )
})
writer . close () import tfrecord
loader = tfrecord . tfrecord_loader ( "/tmp/data.tfrecord" , None , {
"image" : "byte" ,
"label" : "float" ,
"index" : "int"
})
for record in loader :
print ( record [ "label" ])シーケンスエクサムプルは、それぞれの読み取り/書き込み関数がデータをSequenceExampleとして扱うためにsequence_datum上記の同じ方法(読み取りのsequence_description )を使用して読み取りおよび書き込むことができます。
import tfrecord
writer = tfrecord . TFRecordWriter ( "/tmp/data.tfrecord" )
writer . write ({ 'length' : ( 3 , 'int' ), 'label' : ( 1 , 'int' )},
{ 'tokens' : ([[ 0 , 0 , 1 ], [ 0 , 1 , 0 ], [ 1 , 0 , 0 ]], 'int' ), 'seq_labels' : ([ 0 , 1 , 1 ], 'int' )})
writer . write ({ 'length' : ( 3 , 'int' ), 'label' : ( 1 , 'int' )},
{ 'tokens' : ([[ 0 , 0 , 1 ], [ 1 , 0 , 0 ]], 'int' ), 'seq_labels' : ([ 0 , 1 ], 'int' )})
writer . close ()SequenceExampleから読み取り、2つの要素を含むタプルを読みます。
import tfrecord
context_description = { "length" : "int" , "label" : "int" }
sequence_description = { "tokens" : "int" , "seq_labels" : "int" }
loader = tfrecord . tfrecord_loader ( "/tmp/data.tfrecord" , None ,
context_description ,
sequence_description = sequence_description )
for context , sequence_feats in loader :
print ( context [ "label" ])
print ( sequence_feats [ "seq_labels" ])Transforming Inputに関するセクションで説明されているように、機能をtransform引数として渡して、機能の後処理を実行することができます。これは、特にシーケンス機能に使用する必要があります。これらは可変長さのシーケンスであり、バッチする前にパッドアウトする必要があるためです。
import torch
import numpy as np
from tfrecord . torch . dataset import TFRecordDataset
PAD_WIDTH = 5
def pad_sequence_feats ( data ):
context , features = data
for k , v in features . items ():
features [ k ] = np . pad ( v , (( 0 , PAD_WIDTH - len ( v )), ( 0 , 0 )), 'constant' )
return ( context , features )
context_description = { "length" : "int" , "label" : "int" }
sequence_description = { "tokens" : "int " , "seq_labels" : "int" }
dataset = TFRecordDataset ( "/tmp/data.tfrecord" ,
index_path = None ,
description = context_description ,
transform = pad_sequence_feats ,
sequence_description = sequence_description )
loader = torch . utils . data . DataLoader ( dataset , batch_size = 32 )
data = next ( iter ( loader ))
print ( data )または、たとえば動的なパディングを実行するために、バッチを組み立てるために、カスタムcollate_fn実装することを選択できます。
import torch
import numpy as np
from tfrecord . torch . dataset import TFRecordDataset
def collate_fn ( batch ):
from torch . utils . data . _utils import collate
from torch . nn . utils import rnn
context , feats = zip ( * batch )
feats_ = { k : [ torch . Tensor ( d [ k ]) for d in feats ] for k in feats [ 0 ]}
return ( collate . default_collate ( context ),
{ k : rnn . pad_sequence ( f , True ) for ( k , f ) in feats_ . items ()})
context_description = { "length" : "int" , "label" : "int" }
sequence_description = { "tokens" : "int " , "seq_labels" : "int" }
dataset = TFRecordDataset ( "/tmp/data.tfrecord" ,
index_path = None ,
description = context_description ,
transform = pad_sequence_feats ,
sequence_description = sequence_description )
loader = torch . utils . data . DataLoader ( dataset , batch_size = 32 , collate_fn = collate_fn )
data = next ( iter ( loader ))
print ( data )