![]() | ![]() | ![]() | ![]() |
APIドキュメント: tf.RaggedTensor
tf.ragged
設定
import math
import tensorflow as tf
概要
データにはさまざまな形があります。あなたのテンソルもそうすべきです。不規則テンソルは、ネストされた可変長リストに相当するTensorFlowです。これらにより、次のような不均一な形状のデータを簡単に保存および処理できます。
- 映画の俳優のセットなど、可変長の機能。
- 文やビデオクリップなどの可変長シーケンシャル入力のバッチ。
- セクション、段落、文、および単語に細分されたテキストドキュメントなどの階層入力。
- プロトコルバッファなどの構造化入力の個々のフィールド。
ぼろぼろのテンソルでできること
不規則なテンソルは、数学演算( tf.add
やtf.reduce_mean
など)、配列演算( tf.concat
やtf.tile
など)、文字列操作演算( tf.substr
など)を含む100を超えるTensorFlow演算でサポートされています。 )、制御フロー操作( tf.while_loop
やtf.map_fn
など)、およびその他の多くの操作:
digits = tf.ragged.constant([[3, 1, 4, 1], [], [5, 9, 2], [6], []])
words = tf.ragged.constant([["So", "long"], ["thanks", "for", "all", "the", "fish"]])
print(tf.add(digits, 3))
print(tf.reduce_mean(digits, axis=1))
print(tf.concat([digits, [[5, 3]]], axis=0))
print(tf.tile(digits, [1, 2]))
print(tf.strings.substr(words, 0, 2))
print(tf.map_fn(tf.math.square, digits))
<tf.RaggedTensor [[6, 4, 7, 4], [], [8, 12, 5], [9], []]> tf.Tensor([2.25 nan 5.33333333 6. nan], shape=(5,), dtype=float64) <tf.RaggedTensor [[3, 1, 4, 1], [], [5, 9, 2], [6], [], [5, 3]]> <tf.RaggedTensor [[3, 1, 4, 1, 3, 1, 4, 1], [], [5, 9, 2, 5, 9, 2], [6, 6], []]> <tf.RaggedTensor [[b'So', b'lo'], [b'th', b'fo', b'al', b'th', b'fi']]> <tf.RaggedTensor [[9, 1, 16, 1], [], [25, 81, 4], [36], []]>
ファクトリメソッド、変換メソッド、値マッピング操作など、不規則テンソルに固有のメソッドと操作も多数あります。サポートされている操作のリストについては、 tf.ragged
パッケージのドキュメントを参照してください。
不規則テンソルは、 Keras 、 Datasets 、 tf.function 、 SavedModels 、 tf.Exampleなどの多くのTensorFlowAPIでサポートされています。詳細については、以下のTensorFlowAPIのセクションを確認してください。
通常のテンソルと同様に、Pythonスタイルのインデックスを使用して、不規則なテンソルの特定のスライスにアクセスできます。詳細については、以下のインデックス作成のセクションを参照してください。
print(digits[0]) # First row
tf.Tensor([3 1 4 1], shape=(4,), dtype=int32)
print(digits[:, :2]) # First two values in each row.
<tf.RaggedTensor [[3, 1], [], [5, 9], [6], []]>
print(digits[:, -2:]) # Last two values in each row.
<tf.RaggedTensor [[4, 1], [], [9, 2], [6], []]>
また、通常のテンソルと同様に、Pythonの算術演算子と比較演算子を使用して、要素ごとの演算を実行できます。詳細については、以下のオーバーロードされた演算子のセクションを確認してください。
print(digits + 3)
<tf.RaggedTensor [[6, 4, 7, 4], [], [8, 12, 5], [9], []]>
print(digits + tf.ragged.constant([[1, 2, 3, 4], [], [5, 6, 7], [8], []]))
<tf.RaggedTensor [[4, 3, 7, 5], [], [10, 15, 9], [14], []]>
RaggedTensorの値に対して要素ごとの変換を実行する必要がある場合は、 RaggedTensor
を使用できますtf.ragged.map_flat_values
これは、関数と1つ以上の引数を取り、関数を適用してRaggedTensor
の値を変換します。
times_two_plus_one = lambda x: x * 2 + 1
print(tf.ragged.map_flat_values(times_two_plus_one, digits))
<tf.RaggedTensor [[7, 3, 9, 3], [], [11, 19, 5], [13], []]>
不規則なテンソルは、ネストされたPython list
とNumPy array
に変換できます。
digits.to_list()
[[3, 1, 4, 1], [], [5, 9, 2], [6], []]
digits.numpy()
プレースホルダー18l10n-プレースホルダー/tmpfs/src/tf_docs_env/lib/python3.7/site-packages/tensorflow/python/ops/ragged/ragged_tensor.py:2063: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray return np.array(rows) array([array([3, 1, 4, 1], dtype=int32), array([], dtype=int32), array([5, 9, 2], dtype=int32), array([6], dtype=int32), array([], dtype=int32)], dtype=object)
不規則なテンソルの構築
不規則なテンソルを構築する最も簡単な方法は、 RaggedTensor
を使用することです。これは、指定されたネストされたPython list
またはNumPy array
に対応するtf.ragged.constant
を構築します。
sentences = tf.ragged.constant([
["Let's", "build", "some", "ragged", "tensors", "!"],
["We", "can", "use", "tf.ragged.constant", "."]])
print(sentences)
<tf.RaggedTensor [[b"Let's", b'build', b'some', b'ragged', b'tensors', b'!'], [b'We', b'can', b'use', b'tf.ragged.constant', b'.']]>
paragraphs = tf.ragged.constant([
[['I', 'have', 'a', 'cat'], ['His', 'name', 'is', 'Mat']],
[['Do', 'you', 'want', 'to', 'come', 'visit'], ["I'm", 'free', 'tomorrow']],
])
print(paragraphs)
<tf.RaggedTensor [[[b'I', b'have', b'a', b'cat'], [b'His', b'name', b'is', b'Mat']], [[b'Do', b'you', b'want', b'to', b'come', b'visit'], [b"I'm", b'free', b'tomorrow']]]>
不規則テンソルは、 tf.RaggedTensor.from_value_rowids
、 tf.RaggedTensor.from_row_lengths
、 tf.RaggedTensor.from_row_splits
などのファクトリクラスメソッドを使用して、フラット値テンソルと行分割テンソルをペアにして、それらの値を行に分割する方法を示すことによって構築することもできます。
tf.RaggedTensor.from_value_rowids
各値がどの行に属するかがわかっている場合は、 value_rowids
行分割テンソルを使用してRaggedTensor
を作成できます。
print(tf.RaggedTensor.from_value_rowids(
values=[3, 1, 4, 1, 5, 9, 2],
value_rowids=[0, 0, 0, 0, 2, 2, 3]))
<tf.RaggedTensor [[3, 1, 4, 1], [], [5, 9], [2]]>
tf.RaggedTensor.from_row_lengths
各行の長さがわかっている場合は、 row_lengths
の行分割テンソルを使用できます。
print(tf.RaggedTensor.from_row_lengths(
values=[3, 1, 4, 1, 5, 9, 2],
row_lengths=[4, 0, 2, 1]))
<tf.RaggedTensor [[3, 1, 4, 1], [], [5, 9], [2]]>プレースホルダー27
tf.RaggedTensor.from_row_splits
各行が開始および終了するインデックスがわかっている場合は、 row_splits
行分割テンソルを使用できます。
print(tf.RaggedTensor.from_row_splits(
values=[3, 1, 4, 1, 5, 9, 2],
row_splits=[0, 4, 4, 6, 7]))
<tf.RaggedTensor [[3, 1, 4, 1], [], [5, 9], [2]]>プレースホルダー29
ファクトリメソッドの完全なリストについては、 tf.RaggedTensor
クラスのドキュメントを参照してください。
ぼろぼろのテンソルに保存できるもの
通常のTensor
と同様に、 RaggedTensor
の値はすべて同じタイプである必要があります。そして、値はすべて同じ入れ子の深さ(テンソルのランク)でなければなりません:
print(tf.ragged.constant([["Hi"], ["How", "are", "you"]])) # ok: type=string, rank=2
<tf.RaggedTensor [[b'Hi'], [b'How', b'are', b'you']]>
print(tf.ragged.constant([[[1, 2], [3]], [[4, 5]]])) # ok: type=int32, rank=3
<tf.RaggedTensor [[[1, 2], [3]], [[4, 5]]]>
try:
tf.ragged.constant([["one", "two"], [3, 4]]) # bad: multiple types
except ValueError as exception:
print(exception)
Can't convert Python sequence with mixed types to Tensor.
try:
tf.ragged.constant(["A", ["B", "C"]]) # bad: multiple nesting depths
except ValueError as exception:
print(exception)
all scalar values must have the same nesting depth
ユースケースの例
次の例は、 RaggedTensor
を使用して、各文の最初と最後に特別なマーカーを使用して、可変長クエリのバッチのユニグラムとバイグラムの埋め込みを構築および結合する方法を示しています。この例で使用されている操作の詳細については、 tf.ragged
パッケージのドキュメントを確認してください。
queries = tf.ragged.constant([['Who', 'is', 'Dan', 'Smith'],
['Pause'],
['Will', 'it', 'rain', 'later', 'today']])
# Create an embedding table.
num_buckets = 1024
embedding_size = 4
embedding_table = tf.Variable(
tf.random.truncated_normal([num_buckets, embedding_size],
stddev=1.0 / math.sqrt(embedding_size)))
# Look up the embedding for each word.
word_buckets = tf.strings.to_hash_bucket_fast(queries, num_buckets)
word_embeddings = tf.nn.embedding_lookup(embedding_table, word_buckets) # ①
# Add markers to the beginning and end of each sentence.
marker = tf.fill([queries.nrows(), 1], '#')
padded = tf.concat([marker, queries, marker], axis=1) # ②
# Build word bigrams and look up embeddings.
bigrams = tf.strings.join([padded[:, :-1], padded[:, 1:]], separator='+') # ③
bigram_buckets = tf.strings.to_hash_bucket_fast(bigrams, num_buckets)
bigram_embeddings = tf.nn.embedding_lookup(embedding_table, bigram_buckets) # ④
# Find the average embedding for each sentence
all_embeddings = tf.concat([word_embeddings, bigram_embeddings], axis=1) # ⑤
avg_embedding = tf.reduce_mean(all_embeddings, axis=1) # ⑥
print(avg_embedding)
tf.Tensor( [[-0.14285272 0.02908629 -0.16327512 -0.14529026] [-0.4479212 -0.35615516 0.17110227 0.2522229 ] [-0.1987868 -0.13152348 -0.0325102 0.02125177]], shape=(3, 4), dtype=float32)
不規則で均一な寸法
不規則な次元は、スライスの長さが異なる可能性がある次元です。たとえば、 rt=[[3, 1, 4, 1], [], [5, 9, 2], [6], []]
の内部(列)次元は、列スライス( rt[0, :]
、...、 rt[4, :]
)の長さは異なります。スライスがすべて同じ長さの次元は、均一次元と呼ばれます。
不規則テンソルの最も外側の寸法は、単一のスライスで構成されているため、常に均一です(したがって、スライスの長さが異なる可能性はありません)。残りの寸法は、不規則または均一のいずれかです。たとえば、形状[num_sentences, (num_words), embedding_size]
の不規則なテンソルを使用して、各単語の単語の埋め込みを文のバッチに格納できます。ここで、 (num_words)
の周りの括弧は、ディメンションが不規則であることを示します。
不規則テンソルは、複数の不規則な次元を持つ場合があります。たとえば、形状[num_documents, (num_paragraphs), (num_sentences), (num_words)]
のテンソルを使用して構造化テキストドキュメントのバッチを格納できます(ここでも、かっこは不規則な寸法を示すために使用されます)。
tf.Tensor
と同様に、不規則テンソルのランクは、次元の総数です(不規則次元と均一次元の両方を含む)。潜在的に不規則なテンソルは、 tf.Tensor
またはtf.RaggedTensor
のいずれかの値である可能性があります。
RaggedTensorの形状を説明する場合、不規則な寸法は通常、括弧で囲むことによって示されます。たとえば、上で見たように、文のバッチ内の各単語の単語埋め込みを格納する3D RaggedTensorの形状は、 [num_sentences, (num_words), embedding_size]
と書くことができます。
RaggedTensor.shape
属性は、不規則な次元のサイズがNone
である不規則なテンソルのtf.TensorShape
を返します。
tf.ragged.constant([["Hi"], ["How", "are", "you"]]).shape
TensorShape([2, None])
メソッドtf.RaggedTensor.bounding_shape
を使用して、特定のRaggedTensor
の厳密な境界形状を見つけることができます。
print(tf.ragged.constant([["Hi"], ["How", "are", "you"]]).bounding_shape())
tf.Tensor([2 3], shape=(2,), dtype=int64)
不規則vsスパース
ぼろぼろのテンソルは、スパーステンソルの一種と考えるべきではありません。特に、スパーステンソルは、同じデータをコンパクトな形式でモデル化するtf.Tensor
の効率的なエンコーディングです。しかし、不規則テンソルは、拡張されたクラスのデータをモデル化するtf.Tensor
の拡張です。この違いは、操作を定義するときに重要です。
- スパーステンソルまたはデンソルテンソルにopを適用すると、常に同じ結果が得られます。
- 不規則またはスパーステンソルにopを適用すると、異なる結果が得られる場合があります。
説明に役立つ例として、 concat
、 stack
、 tile
などの配列演算が、不規則テンソルとスパーステンソルに対してどのように定義されているかを考えてみます。不規則なテンソルを連結すると、各行が結合され、結合された長さの単一の行が形成されます。
ragged_x = tf.ragged.constant([["John"], ["a", "big", "dog"], ["my", "cat"]])
ragged_y = tf.ragged.constant([["fell", "asleep"], ["barked"], ["is", "fuzzy"]])
print(tf.concat([ragged_x, ragged_y], axis=1))
<tf.RaggedTensor [[b'John', b'fell', b'asleep'], [b'a', b'big', b'dog', b'barked'], [b'my', b'cat', b'is', b'fuzzy']]>
ただし、次の例に示すように、スパーステンソルを連結することは、対応するデンソルテンソルを連結することと同じです(Øは欠落値を示します)。
sparse_x = ragged_x.to_sparse()
sparse_y = ragged_y.to_sparse()
sparse_result = tf.sparse.concat(sp_inputs=[sparse_x, sparse_y], axis=1)
print(tf.sparse.to_dense(sparse_result, ''))
tf.Tensor( [[b'John' b'' b'' b'fell' b'asleep'] [b'a' b'big' b'dog' b'barked' b''] [b'my' b'cat' b'' b'is' b'fuzzy']], shape=(3, 5), dtype=string)
この区別が重要である理由の別の例として、 tf.reduce_mean
などのopの「各行の平均値」の定義を検討してください。不規則なテンソルの場合、行の平均値は、行の値の合計を行の幅で割ったものです。ただし、スパーステンソルの場合、行の平均値は、行の値の合計をスパーステンソルの全体の幅(最長の行の幅以上)で割ったものです。
TensorFlow API
ケラス
tf.kerasは、ディープラーニングモデルを構築およびトレーニングするためのTensorFlowの高レベルAPIです。不規則なテンソルは、 tf.keras.Input
またはtf.keras.layers.InputLayer
でragged=True
を設定することにより、Kerasモデルへの入力として渡すことができます。不規則なテンソルもKerasレイヤー間を通過し、Kerasモデルによって返される場合があります。次の例は、不規則なテンソルを使用してトレーニングされたおもちゃのLSTMモデルを示しています。
# Task: predict whether each sentence is a question or not.
sentences = tf.constant(
['What makes you think she is a witch?',
'She turned me into a newt.',
'A newt?',
'Well, I got better.'])
is_question = tf.constant([True, False, True, False])
# Preprocess the input strings.
hash_buckets = 1000
words = tf.strings.split(sentences, ' ')
hashed_words = tf.strings.to_hash_bucket_fast(words, hash_buckets)
# Build the Keras model.
keras_model = tf.keras.Sequential([
tf.keras.layers.Input(shape=[None], dtype=tf.int64, ragged=True),
tf.keras.layers.Embedding(hash_buckets, 16),
tf.keras.layers.LSTM(32, use_bias=False),
tf.keras.layers.Dense(32),
tf.keras.layers.Activation(tf.nn.relu),
tf.keras.layers.Dense(1)
])
keras_model.compile(loss='binary_crossentropy', optimizer='rmsprop')
keras_model.fit(hashed_words, is_question, epochs=5)
print(keras_model.predict(hashed_words))
WARNING:tensorflow:Layer lstm will not use cuDNN kernels since it doesn't meet the criteria. It will use a generic GPU kernel as fallback when running on GPU. Epoch 1/5 /tmpfs/src/tf_docs_env/lib/python3.7/site-packages/tensorflow/python/framework/indexed_slices.py:449: UserWarning: Converting sparse IndexedSlices(IndexedSlices(indices=Tensor("gradient_tape/sequential/lstm/RaggedToTensor/boolean_mask_1/GatherV2:0", shape=(None,), dtype=int32), values=Tensor("gradient_tape/sequential/lstm/RaggedToTensor/boolean_mask/GatherV2:0", shape=(None, 16), dtype=float32), dense_shape=Tensor("gradient_tape/sequential/lstm/RaggedToTensor/Shape:0", shape=(2,), dtype=int32))) to a dense Tensor of unknown shape. This may consume a large amount of memory. "shape. This may consume a large amount of memory." % value) 1/1 [==============================] - 2s 2s/step - loss: 3.1269 Epoch 2/5 1/1 [==============================] - 0s 18ms/step - loss: 2.1197 Epoch 3/5 1/1 [==============================] - 0s 19ms/step - loss: 2.0196 Epoch 4/5 1/1 [==============================] - 0s 20ms/step - loss: 1.9371 Epoch 5/5 1/1 [==============================] - 0s 18ms/step - loss: 1.8857 [[0.02800461] [0.00945962] [0.02283431] [0.00252927]]プレースホルダー49
tf。例
tf.Exampleは、TensorFlowデータの標準のprotobufエンコーディングです。 tf.Example
でエンコードされたデータには、多くの場合、可変長の特徴が含まれています。たとえば、次のコードは、4つのtf.Example
のバッチを定義します。機能の長さが異なるメッセージの例:
import google.protobuf.text_format as pbtext
def build_tf_example(s):
return pbtext.Merge(s, tf.train.Example()).SerializeToString()
example_batch = [
build_tf_example(r'''
features {
feature {key: "colors" value {bytes_list {value: ["red", "blue"]} } }
feature {key: "lengths" value {int64_list {value: [7]} } } }'''),
build_tf_example(r'''
features {
feature {key: "colors" value {bytes_list {value: ["orange"]} } }
feature {key: "lengths" value {int64_list {value: []} } } }'''),
build_tf_example(r'''
features {
feature {key: "colors" value {bytes_list {value: ["black", "yellow"]} } }
feature {key: "lengths" value {int64_list {value: [1, 3]} } } }'''),
build_tf_example(r'''
features {
feature {key: "colors" value {bytes_list {value: ["green"]} } }
feature {key: "lengths" value {int64_list {value: [3, 5, 2]} } } }''')]
このエンコードされたデータは、 tf.io.parse_example
を使用して解析できます。これは、シリアル化された文字列のテンソルと機能仕様ディクショナリを取得し、機能名をテンソルにマッピングするディクショナリを返します。可変長の特徴を不規則なテンソルに読み込むには、特徴仕様辞書でtf.io.RaggedFeature
を使用するだけです。
feature_specification = {
'colors': tf.io.RaggedFeature(tf.string),
'lengths': tf.io.RaggedFeature(tf.int64),
}
feature_tensors = tf.io.parse_example(example_batch, feature_specification)
for name, value in feature_tensors.items():
print("{}={}".format(name, value))
colors=<tf.RaggedTensor [[b'red', b'blue'], [b'orange'], [b'black', b'yellow'], [b'green']]> lengths=<tf.RaggedTensor [[7], [], [1, 3], [3, 5, 2]]>
tf.io.RaggedFeature
を使用して、複数の不規則な次元を持つフィーチャを読み取ることもできます。詳細については、 APIドキュメントを参照してください。
データセット
tf.dataは、単純で再利用可能な部分から複雑な入力パイプラインを構築できるようにするAPIです。そのコアデータ構造はtf.data.Dataset
であり、これは要素のシーケンスを表し、各要素は1つ以上のコンポーネントで構成されます。
# Helper function used to print datasets in the examples below.
def print_dictionary_dataset(dataset):
for i, element in enumerate(dataset):
print("Element {}:".format(i))
for (feature_name, feature_value) in element.items():
print('{:>14} = {}'.format(feature_name, feature_value))
不規則なテンソルを使用したデータセットの構築
データセットは、 Dataset.from_tensor_slices
などのtf.Tensor
またはNumPy array
からデータセットを構築するために使用されるのと同じ方法を使用して、不規則なテンソルから構築できます。
dataset = tf.data.Dataset.from_tensor_slices(feature_tensors)
print_dictionary_dataset(dataset)
Element 0: colors = [b'red' b'blue'] lengths = [7] Element 1: colors = [b'orange'] lengths = [] Element 2: colors = [b'black' b'yellow'] lengths = [1 3] Element 3: colors = [b'green'] lengths = [3 5 2]
不規則なテンソルを使用したデータセットのバッチ処理とバッチ解除
不規則なテンソルを持つデータセットは、 Dataset.batch
メソッドを使用してバッチ処理できます( n個の連続する要素を1つの要素に結合します)。
batched_dataset = dataset.batch(2)
print_dictionary_dataset(batched_dataset)
Element 0: colors = <tf.RaggedTensor [[b'red', b'blue'], [b'orange']]> lengths = <tf.RaggedTensor [[7], []]> Element 1: colors = <tf.RaggedTensor [[b'black', b'yellow'], [b'green']]> lengths = <tf.RaggedTensor [[1, 3], [3, 5, 2]]>
逆に、バッチ処理されたデータセットは、 Dataset.unbatch
を使用してフラットなデータセットに変換できます。
unbatched_dataset = batched_dataset.unbatch()
print_dictionary_dataset(unbatched_dataset)
Element 0: colors = [b'red' b'blue'] lengths = [7] Element 1: colors = [b'orange'] lengths = [] Element 2: colors = [b'black' b'yellow'] lengths = [1 3] Element 3: colors = [b'green'] lengths = [3 5 2]
可変長の不規則でないテンソルを使用したデータセットのバッチ処理
不規則でないテンソルを含むデータセットがあり、テンソルの長さが要素間で異なる場合、 dense_to_ragged_batch
変換を適用することにより、不規則でないテンソルを不規則なテンソルにバッチ処理できます。
non_ragged_dataset = tf.data.Dataset.from_tensor_slices([1, 5, 3, 2, 8])
non_ragged_dataset = non_ragged_dataset.map(tf.range)
batched_non_ragged_dataset = non_ragged_dataset.apply(
tf.data.experimental.dense_to_ragged_batch(2))
for element in batched_non_ragged_dataset:
print(element)
<tf.RaggedTensor [[0], [0, 1, 2, 3, 4]]> <tf.RaggedTensor [[0, 1, 2], [0, 1]]> <tf.RaggedTensor [[0, 1, 2, 3, 4, 5, 6, 7]]>
不規則テンソルによるデータセットの変換
Dataset.map
を使用して、データセットで不規則なテンソルを作成または変換することもできます。
def transform_lengths(features):
return {
'mean_length': tf.math.reduce_mean(features['lengths']),
'length_ranges': tf.ragged.range(features['lengths'])}
transformed_dataset = dataset.map(transform_lengths)
print_dictionary_dataset(transformed_dataset)
Element 0: mean_length = 7 length_ranges = <tf.RaggedTensor [[0, 1, 2, 3, 4, 5, 6]]> Element 1: mean_length = 0 length_ranges = <tf.RaggedTensor []> Element 2: mean_length = 2 length_ranges = <tf.RaggedTensor [[0], [0, 1, 2]]> Element 3: mean_length = 3 length_ranges = <tf.RaggedTensor [[0, 1, 2], [0, 1, 2, 3, 4], [0, 1]]>
tf.function
tf.functionは、Python関数のTensorFlowグラフを事前に計算するデコレータであり、TensorFlowコードのパフォーマンスを大幅に向上させることができます。不規則テンソルは、 @tf.function
で装飾された関数で透過的に使用できます。たとえば、次の関数は、不規則テンソルと不規則テンソルの両方で機能します。
@tf.function
def make_palindrome(x, axis):
return tf.concat([x, tf.reverse(x, [axis])], axis)
make_palindrome(tf.constant([[1, 2], [3, 4], [5, 6]]), axis=1)
<tf.Tensor: shape=(3, 4), dtype=int32, numpy= array([[1, 2, 2, 1], [3, 4, 4, 3], [5, 6, 6, 5]], dtype=int32)>
make_palindrome(tf.ragged.constant([[1, 2], [3], [4, 5, 6]]), axis=1)
2021-09-22 20:36:51.018367: W tensorflow/core/grappler/optimizers/loop_optimizer.cc:907] Skipping loop optimization for Merge node with control input: RaggedConcat/assert_equal_1/Assert/AssertGuard/branch_executed/_9 <tf.RaggedTensor [[1, 2, 2, 1], [3, 3], [4, 5, 6, 6, 5, 4]]>
tf.functionのinput_signature
を明示的に指定する場合は、 tf.function
を使用してtf.RaggedTensorSpec
できます。
@tf.function(
input_signature=[tf.RaggedTensorSpec(shape=[None, None], dtype=tf.int32)])
def max_and_min(rt):
return (tf.math.reduce_max(rt, axis=-1), tf.math.reduce_min(rt, axis=-1))
max_and_min(tf.ragged.constant([[1, 2], [3], [4, 5, 6]]))
(<tf.Tensor: shape=(3,), dtype=int32, numpy=array([2, 3, 6], dtype=int32)>, <tf.Tensor: shape=(3,), dtype=int32, numpy=array([1, 3, 4], dtype=int32)>)
具体的な機能
具体的な関数は、 tf.function
によって作成された個々のトレースされたグラフをカプセル化します。不規則テンソルは、具体的な機能で透過的に使用できます。
@tf.function
def increment(x):
return x + 1
rt = tf.ragged.constant([[1, 2], [3], [4, 5, 6]])
cf = increment.get_concrete_function(rt)
print(cf(rt))
<tf.RaggedTensor [[2, 3], [4], [5, 6, 7]]>
SavedModels
SavedModelは、重みと計算の両方を含む、シリアル化されたTensorFlowプログラムです。 Kerasモデルまたはカスタムモデルから構築できます。いずれの場合も、不規則テンソルは、SavedModelで定義された関数とメソッドで透過的に使用できます。
例:Kerasモデルの保存
import tempfile
keras_module_path = tempfile.mkdtemp()
tf.saved_model.save(keras_model, keras_module_path)
imported_model = tf.saved_model.load(keras_module_path)
imported_model(hashed_words)
2021-09-22 20:36:52.069689: W tensorflow/python/util/util.cc:348] Sets are not currently considered sequences, but this may change in the future, so consider avoiding using them. WARNING:absl:Function `_wrapped_model` contains input name(s) args_0 with unsupported characters which will be renamed to args_0_1 in the SavedModel. INFO:tensorflow:Assets written to: /tmp/tmp114axtt7/assets INFO:tensorflow:Assets written to: /tmp/tmp114axtt7/assets <tf.Tensor: shape=(4, 1), dtype=float32, numpy= array([[0.02800461], [0.00945962], [0.02283431], [0.00252927]], dtype=float32)>
例:カスタムモデルの保存
class CustomModule(tf.Module):
def __init__(self, variable_value):
super(CustomModule, self).__init__()
self.v = tf.Variable(variable_value)
@tf.function
def grow(self, x):
return x * self.v
module = CustomModule(100.0)
# Before saving a custom model, you must ensure that concrete functions are
# built for each input signature that you will need.
module.grow.get_concrete_function(tf.RaggedTensorSpec(shape=[None, None],
dtype=tf.float32))
custom_module_path = tempfile.mkdtemp()
tf.saved_model.save(module, custom_module_path)
imported_model = tf.saved_model.load(custom_module_path)
imported_model.grow(tf.ragged.constant([[1.0, 4.0, 3.0], [2.0]]))
INFO:tensorflow:Assets written to: /tmp/tmpnn4u8dy5/assets INFO:tensorflow:Assets written to: /tmp/tmpnn4u8dy5/assets <tf.RaggedTensor [[100.0, 400.0, 300.0], [200.0]]>
オーバーロードされた演算子
RaggedTensor
クラスは、標準のPython算術演算子と比較演算子をオーバーロードし、基本的な要素ごとの数学を簡単に実行できるようにします。
x = tf.ragged.constant([[1, 2], [3], [4, 5, 6]])
y = tf.ragged.constant([[1, 1], [2], [3, 3, 3]])
print(x + y)
<tf.RaggedTensor [[2, 3], [5], [7, 8, 9]]>
オーバーロードされた演算子は要素ごとの計算を実行するため、すべての2項演算への入力は同じ形状であるか、同じ形状にブロードキャスト可能である必要があります。最も単純なブロードキャストの場合、単一のスカラーが不規則テンソルの各値と要素ごとに結合されます。
x = tf.ragged.constant([[1, 2], [3], [4, 5, 6]])
print(x + 3)
<tf.RaggedTensor [[4, 5], [6], [7, 8, 9]]>
より高度なケースの説明については、ブロードキャストのセクションを確認してください。
不規則テンソルは、通常のTensor
と同じ演算子のセットをオーバーロードします。単項演算子-
、 ~
、およびabs()
;および二項演算子+
、 -
、 *
、 /
、 //
、 %
、 **
、 &
、 |
、 ^
、 ==
、 <
、 <=
、 >
、および>=
。
インデックス作成
不規則テンソルは、多次元のインデックス作成やスライスなど、Pythonスタイルのインデックス作成をサポートします。次の例は、2Dおよび3Dの不規則テンソルを使用した不規則テンソルのインデックス付けを示しています。
インデックス作成の例:2D不規則テンソル
queries = tf.ragged.constant(
[['Who', 'is', 'George', 'Washington'],
['What', 'is', 'the', 'weather', 'tomorrow'],
['Goodnight']])
print(queries[1]) # A single query
tf.Tensor([b'What' b'is' b'the' b'weather' b'tomorrow'], shape=(5,), dtype=string)
print(queries[1, 2]) # A single word
tf.Tensor(b'the', shape=(), dtype=string)
print(queries[1:]) # Everything but the first row
<tf.RaggedTensor [[b'What', b'is', b'the', b'weather', b'tomorrow'], [b'Goodnight']]>
print(queries[:, :3]) # The first 3 words of each query
<tf.RaggedTensor [[b'Who', b'is', b'George'], [b'What', b'is', b'the'], [b'Goodnight']]>
print(queries[:, -2:]) # The last 2 words of each query
<tf.RaggedTensor [[b'George', b'Washington'], [b'weather', b'tomorrow'], [b'Goodnight']]>
インデックス作成の例:3D不規則テンソル
rt = tf.ragged.constant([[[1, 2, 3], [4]],
[[5], [], [6]],
[[7]],
[[8, 9], [10]]])
print(rt[1]) # Second row (2D RaggedTensor)
<tf.RaggedTensor [[5], [], [6]]>
print(rt[3, 0]) # First element of fourth row (1D Tensor)
tf.Tensor([8 9], shape=(2,), dtype=int32)
print(rt[:, 1:3]) # Items 1-3 of each row (3D RaggedTensor)
<tf.RaggedTensor [[[4]], [[], [6]], [], [[10]]]>
print(rt[:, -1:]) # Last item of each row (3D RaggedTensor)
<tf.RaggedTensor [[[4]], [[6]], [[7]], [[10]]]>
RaggedTensor
は、多次元のインデックス作成とスライスをサポートしますが、1つの制限があります。不規則な次元へのインデックス作成は許可されていません。示された値が一部の行に存在する可能性があり、他の行には存在しない可能性があるため、この場合は問題があります。このような場合、(1) IndexError
を発生させる必要があるかどうかは明らかではありません。 (2)デフォルト値を使用します。または(3)その値をスキップして、最初よりも少ない行数のテンソルを返します。 Pythonの基本原則(「あいまいさに直面して、推測する誘惑を拒否する」)に従って、この操作は現在許可されていません。
テンソル型変換
RaggedTensor
クラスは、 RaggedTensor
とtf.Tensor
またはtf.SparseTensors
の間で変換するために使用できるメソッドを定義します。
ragged_sentences = tf.ragged.constant([
['Hi'], ['Welcome', 'to', 'the', 'fair'], ['Have', 'fun']])
# RaggedTensor -> Tensor
print(ragged_sentences.to_tensor(default_value='', shape=[None, 10]))
tf.Tensor( [[b'Hi' b'' b'' b'' b'' b'' b'' b'' b'' b''] [b'Welcome' b'to' b'the' b'fair' b'' b'' b'' b'' b'' b''] [b'Have' b'fun' b'' b'' b'' b'' b'' b'' b'' b'']], shape=(3, 10), dtype=string)
# Tensor -> RaggedTensor
x = [[1, 3, -1, -1], [2, -1, -1, -1], [4, 5, 8, 9]]
print(tf.RaggedTensor.from_tensor(x, padding=-1))
<tf.RaggedTensor [[1, 3], [2], [4, 5, 8, 9]]>
#RaggedTensor -> SparseTensor
print(ragged_sentences.to_sparse())
SparseTensor(indices=tf.Tensor( [[0 0] [1 0] [1 1] [1 2] [1 3] [2 0] [2 1]], shape=(7, 2), dtype=int64), values=tf.Tensor([b'Hi' b'Welcome' b'to' b'the' b'fair' b'Have' b'fun'], shape=(7,), dtype=string), dense_shape=tf.Tensor([3 4], shape=(2,), dtype=int64))
# SparseTensor -> RaggedTensor
st = tf.SparseTensor(indices=[[0, 0], [2, 0], [2, 1]],
values=['a', 'b', 'c'],
dense_shape=[3, 3])
print(tf.RaggedTensor.from_sparse(st))
<tf.RaggedTensor [[b'a'], [], [b'b', b'c']]>
不規則テンソルの評価
不規則テンソルの値にアクセスするには、次のことができます。
-
tf.RaggedTensor.to_list
を使用して、不規則なテンソルをネストされたPythonリストに変換します。 -
tf.RaggedTensor.numpy
を使用して、不規則なテンソルを、値がネストされたNumPy配列であるNumPy配列に変換します。 - tf.RaggedTensor.valuesプロパティと
tf.RaggedTensor.row_splits
プロパティ、またはtf.RaggedTensor.values
やtf.RaggedTensor.row_lengths
などの行分割メソッドを使用して、不規則なテンソルをそのコンポーネントに分解しtf.RaggedTensor.value_rowids
。 - Pythonインデックスを使用して、不規則なテンソルから値を選択します。
rt = tf.ragged.constant([[1, 2], [3, 4, 5], [6], [], [7]])
print("Python list:", rt.to_list())
print("NumPy array:", rt.numpy())
print("Values:", rt.values.numpy())
print("Splits:", rt.row_splits.numpy())
print("Indexed value:", rt[1].numpy())
Python list: [[1, 2], [3, 4, 5], [6], [], [7]] NumPy array: [array([1, 2], dtype=int32) array([3, 4, 5], dtype=int32) array([6], dtype=int32) array([], dtype=int32) array([7], dtype=int32)] Values: [1 2 3 4 5 6 7] Splits: [0 2 5 6 6 7] Indexed value: [3 4 5] /tmpfs/src/tf_docs_env/lib/python3.7/site-packages/tensorflow/python/ops/ragged/ragged_tensor.py:2063: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray return np.array(rows)
放送
ブロードキャストとは、さまざまな形状のテンソルを要素ごとの操作に互換性のある形状にするプロセスです。放送の背景については、以下を参照してください。
互換性のある形状を持つために2つの入力x
とy
をブロードキャストするための基本的な手順は次のとおりです。
x
とy
の次元数が同じでない場合は、同じ数になるまで外側の次元(サイズ1)を追加します。x
とy
のサイズが異なる次元ごとに:
-
x
またはy
の次元d
のサイズが1
の場合、他の入力のサイズと一致するように、次元d
全体でその値を繰り返します。 - それ以外の場合は、例外を発生させます(
x
とy
はブロードキャスト互換ではありません)。
均一な次元のテンソルのサイズが単一の数値(その次元全体のスライスのサイズ)である場合。不規則な次元のテンソルのサイズは、スライスの長さのリストです(その次元全体のすべてのスライスについて)。
放送例
# x (2D ragged): 2 x (num_rows)
# y (scalar)
# result (2D ragged): 2 x (num_rows)
x = tf.ragged.constant([[1, 2], [3]])
y = 3
print(x + y)
<tf.RaggedTensor [[4, 5], [6]]>
# x (2d ragged): 3 x (num_rows)
# y (2d tensor): 3 x 1
# Result (2d ragged): 3 x (num_rows)
x = tf.ragged.constant(
[[10, 87, 12],
[19, 53],
[12, 32]])
y = [[1000], [2000], [3000]]
print(x + y)
<tf.RaggedTensor [[1010, 1087, 1012], [2019, 2053], [3012, 3032]]>
# x (3d ragged): 2 x (r1) x 2
# y (2d ragged): 1 x 1
# Result (3d ragged): 2 x (r1) x 2
x = tf.ragged.constant(
[[[1, 2], [3, 4], [5, 6]],
[[7, 8]]],
ragged_rank=1)
y = tf.constant([[10]])
print(x + y)
<tf.RaggedTensor [[[11, 12], [13, 14], [15, 16]], [[17, 18]]]>
# x (3d ragged): 2 x (r1) x (r2) x 1
# y (1d tensor): 3
# Result (3d ragged): 2 x (r1) x (r2) x 3
x = tf.ragged.constant(
[
[
[[1], [2]],
[],
[[3]],
[[4]],
],
[
[[5], [6]],
[[7]]
]
],
ragged_rank=2)
y = tf.constant([10, 20, 30])
print(x + y)
<tf.RaggedTensor [[[[11, 21, 31], [12, 22, 32]], [], [[13, 23, 33]], [[14, 24, 34]]], [[[15, 25, 35], [16, 26, 36]], [[17, 27, 37]]]]>
ブロードキャストされない形状の例を次に示します。
# x (2d ragged): 3 x (r1)
# y (2d tensor): 3 x 4 # trailing dimensions do not match
x = tf.ragged.constant([[1, 2], [3, 4, 5, 6], [7]])
y = tf.constant([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
try:
x + y
except tf.errors.InvalidArgumentError as exception:
print(exception)
Expected 'tf.Tensor(False, shape=(), dtype=bool)' to be true. Summarized data: b'Unable to broadcast: dimension size mismatch in dimension' 1 b'lengths=' 4 b'dim_size=' 2, 4, 1
# x (2d ragged): 3 x (r1)
# y (2d ragged): 3 x (r2) # ragged dimensions do not match.
x = tf.ragged.constant([[1, 2, 3], [4], [5, 6]])
y = tf.ragged.constant([[10, 20], [30, 40], [50]])
try:
x + y
except tf.errors.InvalidArgumentError as exception:
print(exception)
Expected 'tf.Tensor(False, shape=(), dtype=bool)' to be true. Summarized data: b'Unable to broadcast: dimension size mismatch in dimension' 1 b'lengths=' 2, 2, 1 b'dim_size=' 3, 1, 2
# x (3d ragged): 3 x (r1) x 2
# y (3d ragged): 3 x (r1) x 3 # trailing dimensions do not match
x = tf.ragged.constant([[[1, 2], [3, 4], [5, 6]],
[[7, 8], [9, 10]]])
y = tf.ragged.constant([[[1, 2, 0], [3, 4, 0], [5, 6, 0]],
[[7, 8, 0], [9, 10, 0]]])
try:
x + y
except tf.errors.InvalidArgumentError as exception:
print(exception)
Expected 'tf.Tensor(False, shape=(), dtype=bool)' to be true. Summarized data: b'Unable to broadcast: dimension size mismatch in dimension' 2 b'lengths=' 3, 3, 3, 3, 3 b'dim_size=' 2, 2, 2, 2, 2
RaggedTensorエンコーディング
不規則テンソルは、 RaggedTensor
クラスを使用してエンコードされます。内部的には、各RaggedTensor
は次のもので構成されています。
- 可変長行をフラット化されたリストに連結する
values
テンソル。 -
row_partition
は、これらのフラット化された値がどのように行に分割されるかを示します。
row_partition
は、次の4つの異なるエンコーディングを使用して保存できます。
-
row_splits
は、行間の分割点を指定する整数ベクトルです。 -
value_rowids
は、各値の行インデックスを指定する整数ベクトルです。 -
row_lengths
は、各行の長さを指定する整数ベクトルです。 -
uniform_row_length
は、すべての行に単一の長さを指定する整数スカラーです。
整数のスカラーnrows
をrow_partition
エンコーディングに含めて、value_rowidsの空の末尾の行またはvalue_rowids
の空の行を考慮することもできuniform_row_length
。
rt = tf.RaggedTensor.from_row_splits(
values=[3, 1, 4, 1, 5, 9, 2],
row_splits=[0, 4, 4, 6, 7])
print(rt)
<tf.RaggedTensor [[3, 1, 4, 1], [], [5, 9], [2]]>
行パーティションに使用するエンコーディングの選択は、一部のコンテキストで効率を向上させるために、不規則なテンソルによって内部的に管理されます。特に、さまざまな行分割スキームの長所と短所のいくつかは次のとおりです。
- 効率的なインデックス作成:
row_splits
エンコーディングにより、一定時間のインデックス作成と不規則なテンソルへのスライスが可能になります。 - 効率的な連結:2つのテンソルを連結しても行の長さは変わらないため、不規則なテンソルを連結する場合は、
row_lengths
エンコーディングの方が効率的です。 - 小さいエンコーディングサイズ:テンソルのサイズは値の総数にのみ依存するため、
value_rowids
エンコーディングは、空の行が多数ある不規則なテンソルを格納する場合に効率的です。一方、row_splits
およびrow_lengths
エンコーディングは、行ごとに1つのスカラー値しか必要としないため、より長い行を持つ不規則なテンソルを格納する場合に効率的です。 - 互換性:
value_rowids
スキームは、tf.segment_sum
などの操作で使用されるセグメンテーション形式と一致します。row_limits
スキームは、tf.sequence_mask
などのopsで使用される形式と一致します。 - 均一な次元:以下で説明するように、
uniform_row_length
エンコーディングは、不規則なテンソルを均一な次元でエンコードするために使用されます。
複数の不規則な次元
複数の不規則な次元を持つ不規則なテンソルは、 values
テンソルにネストされたRaggedTensor
を使用してエンコードされます。ネストされた各RaggedTensor
は、単一の不規則な次元を追加します。
rt = tf.RaggedTensor.from_row_splits(
values=tf.RaggedTensor.from_row_splits(
values=[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
row_splits=[0, 3, 3, 5, 9, 10]),
row_splits=[0, 1, 1, 5])
print(rt)
print("Shape: {}".format(rt.shape))
print("Number of partitioned dimensions: {}".format(rt.ragged_rank))
<tf.RaggedTensor [[[10, 11, 12]], [], [[], [13, 14], [15, 16, 17, 18], [19]]]> Shape: (3, None, None) Number of partitioned dimensions: 2
ファクトリ関数tf.RaggedTensor.from_nested_row_splits
を使用して、 row_splits
テンソルのリストを提供することにより、複数の不規則な次元を持つRaggedTensorを直接構築できます。
rt = tf.RaggedTensor.from_nested_row_splits(
flat_values=[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
nested_row_splits=([0, 1, 1, 5], [0, 3, 3, 5, 9, 10]))
print(rt)
<tf.RaggedTensor [[[10, 11, 12]], [], [[], [13, 14], [15, 16, 17, 18], [19]]]>
不規則なランクとフラットな値
不規則なテンソルの不規則なランクは、基になるvalues
のテンソルが分割された回数です(つまり、 RaggedTensor
オブジェクトのネストの深さ)。最も内側のvalues
テンソルは、そのflat_valuesとして知られています。次の例では、 conversations
はragged_rank = 3であり、そのflat_values
は24個の文字列を持つ1D Tensor
です。
# shape = [batch, (paragraph), (sentence), (word)]
conversations = tf.ragged.constant(
[[[["I", "like", "ragged", "tensors."]],
[["Oh", "yeah?"], ["What", "can", "you", "use", "them", "for?"]],
[["Processing", "variable", "length", "data!"]]],
[[["I", "like", "cheese."], ["Do", "you?"]],
[["Yes."], ["I", "do."]]]])
conversations.shape
TensorShape([2, None, None, None])
assert conversations.ragged_rank == len(conversations.nested_row_splits)
conversations.ragged_rank # Number of partitioned dimensions.
3
conversations.flat_values.numpy()
array([b'I', b'like', b'ragged', b'tensors.', b'Oh', b'yeah?', b'What', b'can', b'you', b'use', b'them', b'for?', b'Processing', b'variable', b'length', b'data!', b'I', b'like', b'cheese.', b'Do', b'you?', b'Yes.', b'I', b'do.'], dtype=object)
均一な内寸
均一な内部次元を持つ不規則なテンソルは、flat_values(つまり、最も内側のvalues
)に多次元tf.Tensor
を使用してエンコードされます。
rt = tf.RaggedTensor.from_row_splits(
values=[[1, 3], [0, 0], [1, 3], [5, 3], [3, 3], [1, 2]],
row_splits=[0, 3, 4, 6])
print(rt)
print("Shape: {}".format(rt.shape))
print("Number of partitioned dimensions: {}".format(rt.ragged_rank))
print("Flat values shape: {}".format(rt.flat_values.shape))
print("Flat values:\n{}".format(rt.flat_values))
<tf.RaggedTensor [[[1, 3], [0, 0], [1, 3]], [[5, 3]], [[3, 3], [1, 2]]]> Shape: (3, None, 2) Number of partitioned dimensions: 1 Flat values shape: (6, 2) Flat values: [[1 3] [0 0] [1 3] [5 3] [3 3] [1 2]]
均一な非内寸
均一な非内部次元を持つ不規則なテンソルは、行をuniform_row_length
で分割することによってエンコードされます。
rt = tf.RaggedTensor.from_uniform_row_length(
values=tf.RaggedTensor.from_row_splits(
values=[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
row_splits=[0, 3, 5, 9, 10]),
uniform_row_length=2)
print(rt)
print("Shape: {}".format(rt.shape))
print("Number of partitioned dimensions: {}".format(rt.ragged_rank))
<tf.RaggedTensor [[[10, 11, 12], [13, 14]], [[15, 16, 17, 18], [19]]]> Shape: (2, 2, None) Number of partitioned dimensions: 2