剪切numpy数组
我想对一个numpy数组进行“剪切”。我不太确定我用“剪切”这个词是否正确;我指的剪切是这样的:
把第一列不动
把第二列移动1个位置
把第三列移动2个位置
依此类推...
所以这个数组:
array([[11, 12, 13],
[17, 18, 19],
[35, 36, 37]])
会变成这样的数组:
array([[11, 36, 19],
[17, 12, 37],
[35, 18, 13]])
或者像这样的数组:
array([[11, 0, 0],
[17, 12, 0],
[35, 18, 13]])
这取决于我们如何处理边缘部分。我对边缘的处理方式没有太多要求。
这是我尝试写的一个函数来实现这个功能:
import numpy
def shear(a, strength=1, shift_axis=0, increase_axis=1, edges='clip'):
strength = int(strength)
shift_axis = int(shift_axis)
increase_axis = int(increase_axis)
if shift_axis == increase_axis:
raise UserWarning("Shear can't shift in the direction it increases")
temp = numpy.zeros(a.shape, dtype=int)
indices = []
for d, num in enumerate(a.shape):
coords = numpy.arange(num)
shape = [1] * len(a.shape)
shape[d] = num
coords = coords.reshape(shape) + temp
indices.append(coords)
indices[shift_axis] -= strength * indices[increase_axis]
if edges == 'clip':
indices[shift_axis][indices[shift_axis] < 0] = -1
indices[shift_axis][indices[shift_axis] >= a.shape[shift_axis]] = -1
res = a[indices]
res[indices[shift_axis] == -1] = 0
elif edges == 'roll':
indices[shift_axis] %= a.shape[shift_axis]
res = a[indices]
return res
if __name__ == '__main__':
a = numpy.random.random((3,4))
print a
print shear(a)
看起来是有效的。如果不行,请告诉我!
不过我觉得这个方法有点笨拙,不太优雅。我是不是忽略了numpy或scipy里已经有的现成函数?有没有更简单、更好、更高效的方法来在numpy中做到这一点?我是不是在重复造轮子?
编辑:
如果这个方法能在N维数组上也能用,而不仅仅是2D的,那就更好了。
这个函数将在我数据处理的循环中反复使用,所以我觉得优化它是很有必要的。
第二次编辑:
我终于做了一些性能测试。看起来numpy.roll是个不错的选择,尽管有循环。谢谢,tom10和Sven Marnach!
性能测试代码:(在Windows上运行,不要在Linux上使用time.clock,我觉得)
import time, numpy
def shear_1(a, strength=1, shift_axis=0, increase_axis=1, edges='roll'):
strength = int(strength)
shift_axis = int(shift_axis)
increase_axis = int(increase_axis)
if shift_axis == increase_axis:
raise UserWarning("Shear can't shift in the direction it increases")
temp = numpy.zeros(a.shape, dtype=int)
indices = []
for d, num in enumerate(a.shape):
coords = numpy.arange(num)
shape = [1] * len(a.shape)
shape[d] = num
coords = coords.reshape(shape) + temp
indices.append(coords)
indices[shift_axis] -= strength * indices[increase_axis]
if edges == 'clip':
indices[shift_axis][indices[shift_axis] < 0] = -1
indices[shift_axis][indices[shift_axis] >= a.shape[shift_axis]] = -1
res = a[indices]
res[indices[shift_axis] == -1] = 0
elif edges == 'roll':
indices[shift_axis] %= a.shape[shift_axis]
res = a[indices]
return res
def shear_2(a, strength=1, shift_axis=0, increase_axis=1, edges='roll'):
indices = numpy.indices(a.shape)
indices[shift_axis] -= strength * indices[increase_axis]
indices[shift_axis] %= a.shape[shift_axis]
res = a[tuple(indices)]
if edges == 'clip':
res[indices[shift_axis] < 0] = 0
res[indices[shift_axis] >= a.shape[shift_axis]] = 0
return res
def shear_3(a, strength=1, shift_axis=0, increase_axis=1):
if shift_axis > increase_axis:
shift_axis -= 1
res = numpy.empty_like(a)
index = numpy.index_exp[:] * increase_axis
roll = numpy.roll
for i in range(0, a.shape[increase_axis]):
index_i = index + (i,)
res[index_i] = roll(a[index_i], i * strength, shift_axis)
return res
numpy.random.seed(0)
for a in (
numpy.random.random((3, 3, 3, 3)),
numpy.random.random((50, 50, 50, 50)),
numpy.random.random((300, 300, 10, 10)),
):
print 'Array dimensions:', a.shape
for sa, ia in ((0, 1), (1, 0), (2, 3), (0, 3)):
print 'Shift axis:', sa
print 'Increase axis:', ia
ref = shear_1(a, shift_axis=sa, increase_axis=ia)
for shear, label in ((shear_1, '1'), (shear_2, '2'), (shear_3, '3')):
start = time.clock()
b = shear(a, shift_axis=sa, increase_axis=ia)
end = time.clock()
print label + ': %0.6f seconds'%(end-start)
if (b - ref).max() > 1e-9:
print "Something's wrong."
print
5 个回答
8
numpy的 roll 函数可以做到这一点。比如说,如果你原来的数组是x,那么
for i in range(x.shape[1]):
x[:,i] = np.roll(x[:,i], i)
就会产生
[[11 36 19]
[17 12 37]
[35 18 13]]
8
这可以通过一个技巧来实现,具体内容可以参考Joe Kington的这个回答:
from numpy.lib.stride_tricks import as_strided
a = numpy.array([[11, 12, 13],
[17, 18, 19],
[35, 36, 37]])
shift_axis = 0
increase_axis = 1
b = numpy.vstack((a, a))
strides = list(b.strides)
strides[increase_axis] -= strides[shift_axis]
strides = (b.strides[0], b.strides[1] - b.strides[0])
as_strided(b, shape=b.shape, strides=strides)[a.shape[0]:]
# array([[11, 36, 19],
# [17, 12, 37],
# [35, 18, 13]])
如果想要得到“clip”而不是“roll”,可以使用
b = numpy.vstack((numpy.zeros(a.shape, int), a))
这可能是最有效的方法,因为它完全不使用任何Python循环。
8
tom10的回答中的方法可以扩展到任意维度:
def shear3(a, strength=1, shift_axis=0, increase_axis=1):
if shift_axis > increase_axis:
shift_axis -= 1
res = numpy.empty_like(a)
index = numpy.index_exp[:] * increase_axis
roll = numpy.roll
for i in range(0, a.shape[increase_axis]):
index_i = index + (i,)
res[index_i] = roll(a[index_i], -i * strength, shift_axis)
return res