要素ごとの操作のブロードキャスト規則#
このセクションの目的は、ブロードキャストを使用する運用に適用される一連の共通ルールを提供することです。
説明
ブロードキャストを使用すると、任意の次元数の入力に対して要素ごとの演算を実行できます。次の 2 種類のブロードキャストがサポートされます: Numpy と PDPD。
規則#
ブロードキャストなし:
- 入力テンソルの次元は一致する必要があります。
- 暗黙的なブロードキャスト規則は適用されません。
Numpy ブロードキャスト:
- 2 つのテンソルの右揃えの次元が要素ごとに比較されます。
- 小さいテンソルは、大きいテンソルと同じ形状にするために、サイズ 1 の次元が付加されます。
- アライメント後、両方のテンソルが等しいか、次元の 1 つが 1 の場合、2 つのテンソルは互換性があります。
- サイズ 1 の次元のテンソルは、2 番目のテンソルのサイズと一致するように暗黙的にブロードキャストされます。
- 両方の入力がランク = 0 の場合、結果はスカラーになります。
PDPD ブロードキャスト:
- 最初の入力テンソル A は任意のランクであり、2 番目の入力 B は最初の入力以下のランクを持ちます。
- 入力テンソル B は、入力 A の連続サブシーケンスです。
- A の形状と一致するようにブロードキャスト B を適用します。指定された軸は、B を A にブロードキャストする開始次元インデックスです。
- 軸がデフォルト (-1) に設定されている場合、新しい値を計算します。
axis = rank(A) - rank(B)。デフォルト値の (-1) を除き、軸には負の値は許可されません。 - 入力 B のサイズ 1 の末尾の次元は、
shape(B) = (3, 1) => (3)などのサブシーケンスでは無視されます。
Numpy の例#
A: Shape(,) -> scalarB: Shape(,) -> scalarResult: Shape(,) -> scalarA: Shape(2, 3)B: Shape( 1)Result: Shape(2, 3)A: Shape( 3)B: Shape(2, 3)Result: Shape(2, 3)A: Shape(2, 3, 5)B: Shape(,) -> scalarResult: Shape(2, 3, 5)A: Shape(2, 1, 5)B: Shape(1, 4, 5)Result: Shape(2, 4, 5)A: Shape( 6, 5)B: Shape(2, 1, 5)Result: Shape(2, 6, 5)A: Shape(2, 1, 5)B: Shape( 4, 1)Result: Shape(2, 4, 5)A: Shape(3, 2, 1, 4)B: Shape( 5, 4)Result: Shape(3, 2, 5, 4)A: Shape( 1, 5, 3)B: Shape(5, 2, 1, 3)Result: Shape(5, 2, 5, 3)A: Shape(3)B: Shape(2)Result: broadcast won't happen due to dimensions mismatchA: Shape(3, 1, 5)B: Shape(4, 4, 5)Result: broadcast won't happen due to dimensions mismatch on the leftmost axis
PDPD の例#
A: Shape(2, 3, 4, 5)B: Shape( 3, 4 ) with axis = 1Result: Shape(2, 3, 4, 5)A: Shape(2, 3, 4, 5)B: Shape( 3, 1 ) with axis = 1Result: Shape(2, 3, 4, 5)A: Shape(2, 3, 4, 5)B: Shape( 4, 5) with axis=-1(default) or axis=2Result: Shape(2, 3, 4, 5)A: Shape(2, 3, 4, 5)B: Shape(1, 3 ) with axis = 0Result: Shape(2, 3, 4, 5)A: Shape(2, 3, 4, 5)B: Shape(,)Result: Shape(2, 3, 4, 5)A: Shape(2, 3, 4, 5)B: Shape( 5) with axis=-1(default) or axis = 3Result: Shape(2, 3, 4, 5)A: Shape(8, 1, 6, 1)B: Shape( 7, 1, 5) with axis = 1Result: broadcast won't happen due to dimensions mismatch, only B to A broadcast is supported for PDPD
双方向ブロードキャスト規則#
説明
双方向ブロードキャストは、要素ごとの操作を目的としたものではありません。目的は、配列を指定された形状にブロードキャストすることです。
規則#
双方向ブロードキャスト:
入力テンソルの次元は右揃えです。
次のブロードキャスト規則が適用されます:
numpy.array(input) * numpy.ones(target_shape)。2 つの対応する次元が同じ値を持つか、そのうちの 1 つが 1 に等しい必要があります。
次の場合、出力形状は
target_shapeと等しくない可能性があります:
target_shapeにはサイズ 1 の次元が含まれます。target_shapeランクは入力テンソルのランクより小さくなります。
双方向の例#
A: Shape(5)B: Shape(1)Result: Shape(5)A: Shape(2, 3)B: Shape( 3)Result: Shape(2, 3)A: Shape(3, 1)B: Shape(3, 4)Result: Shape(3, 4)A: Shape(3, 4)B: Shape(,) -> scalarResult: Shape(3, 4)A: Shape( 3, 1)B: Shape(2, 1, 6)Result: Shape(2, 3, 6)