NumpyでTensorflowまたはPyTorchの分散および収集操作を実装したいと考えています。私はしばらく頭を掻いてきました。すべてのポインタは大いに感謝しています!散布してnumpyで操作を収集する方法は?
答えて
の方法は、私が予想していた以上に多くの作業であることが判明しました。私はそれのためにNumPyの準備が整った機能を見つけませんでした。私はNumPyで実装する必要があるかもしれない人のためにここで共有しています。 (PS self
は、法の宛先または出力されます。)
def scatter_numpy(self, dim, index, src):
"""
Writes all values from the Tensor src into self at the indices specified in the index Tensor.
:param dim: The axis along which to index
:param index: The indices of elements to scatter
:param src: The source element(s) to scatter
:return: self
"""
if index.dtype != np.dtype('int_'):
raise TypeError("The values of index must be integers")
if self.ndim != index.ndim:
raise ValueError("Index should have the same number of dimensions as output")
if dim >= self.ndim or dim < -self.ndim:
raise IndexError("dim is out of range")
if dim < 0:
# Not sure why scatter should accept dim < 0, but that is the behavior in PyTorch's scatter
dim = self.ndim + dim
idx_xsection_shape = index.shape[:dim] + index.shape[dim + 1:]
self_xsection_shape = self.shape[:dim] + self.shape[dim + 1:]
if idx_xsection_shape != self_xsection_shape:
raise ValueError("Except for dimension " + str(dim) +
", all dimensions of index and output should be the same size")
if (index >= self.shape[dim]).any() or (index < 0).any():
raise IndexError("The values of index must be between 0 and (self.shape[dim] -1)")
def make_slice(arr, dim, i):
slc = [slice(None)] * arr.ndim
slc[dim] = i
return slc
# We use index and dim parameters to create idx
# idx is in a form that can be used as a NumPy advanced index for scattering of src param. in self
idx = [[*np.indices(idx_xsection_shape).reshape(index.ndim - 1, -1),
index[make_slice(index, dim, i)].reshape(1, -1)[0]] for i in range(index.shape[dim])]
idx = list(np.concatenate(idx, axis=1))
idx.insert(dim, idx.pop())
if not np.isscalar(src):
if index.shape[dim] > src.shape[dim]:
raise IndexError("Dimension " + str(dim) + "of index can not be bigger than that of src ")
src_xsection_shape = src.shape[:dim] + src.shape[dim + 1:]
if idx_xsection_shape != src_xsection_shape:
raise ValueError("Except for dimension " +
str(dim) + ", all dimensions of index and src should be the same size")
# src_idx is a NumPy advanced index for indexing of elements in the src
src_idx = list(idx)
src_idx.pop(dim)
src_idx.insert(dim, np.repeat(np.arange(index.shape[dim]), np.prod(idx_xsection_shape)))
self[idx] = src[src_idx]
else:
self[idx] = src
return self
ありgather
のためのシンプルな解決策になるが、これは私が上で定住するものである可能性があり:
(ここself
値が収集されているということですndarray )
def gather_numpy(self, dim, index):
"""
Gathers values along an axis specified by dim.
For a 3-D tensor the output is specified by:
out[i][j][k] = input[index[i][j][k]][j][k] # if dim == 0
out[i][j][k] = input[i][index[i][j][k]][k] # if dim == 1
out[i][j][k] = input[i][j][index[i][j][k]] # if dim == 2
:param dim: The axis along which to index
:param index: A tensor of indices of elements to gather
:return: tensor of gathered values
"""
idx_xsection_shape = index.shape[:dim] + index.shape[dim + 1:]
self_xsection_shape = self.shape[:dim] + self.shape[dim + 1:]
if idx_xsection_shape != self_xsection_shape:
raise ValueError("Except for dimension " + str(dim) +
", all dimensions of index and self should be the same size")
if index.dtype != np.dtype('int_'):
raise TypeError("The values of index must be integers")
data_swaped = np.swapaxes(self, 0, dim)
index_swaped = np.swapaxes(index, 0, dim)
gathered = np.choose(index_swaped, data_swaped)
return np.swapaxes(gathered, 0, dim)
フォアref
とindices
numpyの配列である:
散布更新:
は収集:
ref[indices] # tf.gather(ref, indices)
ref[:, indices] # tf.gather(ref, indices, axis=1)
ref[..., indices, :] # tf.gather(ref, indices, axis=-2)
ref[..., indices] # tf.gather(ref, indices, axis=-1)
は、より多くのためにnumpy docs on indexingを参照してください。
あなたのソリューションでは、srcを散布したい次元をどのように定義するのですか? –
更新された回答。 – DomJack
@DomJackで提案されているように、スライスの割り当てを使用するのではなく、散乱の場合は、np.add.at;これはスライスの割り当てとは異なり、重複したインデックスの存在下では明確な動作をしているためです。
明確に定義されているとはどういう意味ですか?私の理解はPyTorchとTensorflowにあり、インデックスが重複すると値が上書きされます。 TFの場合、更新の順序は確定的ではないことを特に警告します。私はnp.add.atを見て、それは "scatter_add"操作(いいえ)には良いと思われますが、それは私が望む動作ではありません。 –
- 1. WCFおよびC#(またはF#)を使用した散布的な操作の収集
- 2. comm.Scattervを使用してnumpy配列をpythonで散布する方法
- 3. 散布は、Muleの例外を収集します。getPayloadAsString()、getPayloadAsString(DataType.STRING_DATA_TYPE)を使用
- 4. 3D散布図の作成方法は?
- 5. Pythonでコレクションに対して操作を実行し、結果を収集する方法は?
- 6. テンソルボードを使って散布図を作る方法 - テンソルフロー
- 7. データを収集して渡す方法
- 8. データをインポートし、Rで散布図を作成する方法は?
- 9. ディンプル散布図に集計を作成しない
- 10. 独自のコードを配布するためにバイナリカーネルを収集する方法
- 11. Pythonを使用して散布図をアニメーション化する方法
- 12. カラーバーを使って散布をベースマップする方法は?
- 13. PCAで散布図を作成する方法と結果を読む方法
- 14. フォームを作成し、配布し、情報を収集するためのオプション
- 15. Excelでの散布図の散布図の直線的散布
- 16. nullを取得する収集後にスパークマップ操作のグラフフィールド
- 17. Nokogiriでliタグをトラバースして値を収集する方法
- 18. Cypher発散と収束経路集約
- 19. numpyで列を集計する方法
- 20. grepを収集してaws configsetで使用する方法
- 21. 散布図の凡例を編集するには?
- 22. numpyでこのテンソルの収縮を計算する方法は?
- 23. numpyで二項分布を実装する方法は?
- 24. は、私が<code>ChartFactory.createScatterPlot</code>で作成した散布図を持って散布図
- 25. AngularJSで編集ボタンを操作する方法は?
- 26. 動的値を収集するソースを作成する方法
- 27. Eximで失敗したアドレスを収集する方法は?
- 28. 散布は
- 29. ヒープダンプ(IBM JDK)を収集する方法
- 30. Observableを収集する方法
私は、これらのメソッドは、PythonフロントはC++メソッドに終了しているよう –
が見える...問題のコードはオープンソースであることを疑います。 'numpy'エキスパートの助けが必要な場合は、彼らが何をしているのかを説明する必要があります。言い換えれば、あなたがやりたいことを 'numpy'の言葉で(例で)述べてください。 'pytorch'の経験がなければ、私はその文書を簡単に理解できませんでした。 – hpaulj
@MadPhysicistはいコードはオープンソースです。ここで確認できます。非常にクールなプロジェクトです:http://openmined.org/ –