这个问题对于矩阵Roll rows of a matrix independently非常类似
但我没能适应三维张量
给我一个张量
0 0 0
1 1 1
0 0 0
0 0 0
1 1 1
0 0 0
还有一个向量,它指定了我要将矩阵按列移动多少
1 2
我想要一个新的张量,其中每个矩阵按列移动,如下所示
0 0 0
0 0 0
1 1 1
1 1 1
0 0 0
0 0 0
到目前为止,我已经能够得到一个潜在的映射索引
import numpy as np
# Input
A = np.array([[0, 0, 0],
[1, 1, 1],
[0, 0, 0],
[0, 0, 0]])
B = np.array([[0, 0, 0],
[1, 1, 1],
[0, 0, 0],
[0, 0, 0]])
AB = np.array([A, B])
# Shifting amount
r = np.array([-1, 1])
d1, d2, d3 = np.ogrid[:AB.shape[0], :AB.shape[1], :AB.shape[2]]
r[r < 0] += AB.shape[1]
r = np.array([r, ]*AB.shape[1]).transpose()
r = r[:, np.newaxis]
# New column indices?
d2 = d2 - r
d2[d2 < 0] += AB.shape[1]
result = AB[d2]
print(result)
但我得到了这个错误:
~/Work/ethz/iml/task2 $ python test.py
Traceback (most recent call last):
File "test.py", line 27, in <module>
result = AB[d2]
IndexError: index 2 is out of bounds for axis 0 with size 2
这就是d2
的样子:
[[[1 1 1 1]
[2 2 2 2]
[3 3 3 3]
[0 0 0 0]]
[[3 3 3 3]
[0 0 0 0]
[1 1 1 1]
[2 2 2 2]]]
方法#1
从同一链接Q&;A就表演而言—
样本运行-
方法#2
继续你的尝试,似乎你已经足够接近了。我们只需少量修改/修正即可获得最终输出-
由于滚动无论如何都需要将数据移动到一个新数组中,所以您可以创建一个索引列表,每个行都将映射到该列表。我们可以沿着您选择为“行”轴的轴排列
A
的元素,保持所有其他轴在适当的位置这将适用于
A
的任何输入形状raxis
是要排列的“行”轴,caxis
是作为一个单元移动的矩阵列。通过在重塑r
之前将所有轴都设置为1,可以轻松地将其扩展到多个轴,这也必须将它们从其形状中排除。所有其他轴保持原样。这基本上是Divakar's answer的广义版本样本运行:
以下是一种使用
take_along_axis
的索引方法:相关问题 更多 >
编程相关推荐