【问题标题】:Can numpy strides stride only within subarrays?numpy strides 只能在子数组内跨步吗?
【发布时间】:2017-09-08 10:52:04
【问题描述】:

我有一个非常大的 numpy 数组(145000 行 * 550 列)。我想在子数组中创建滚动切片。我试图用一个函数来实现它。 lagged_vals 函数的行为符合预期,但 np.lib.stride_tricks 的行为与我希望的不同 -

def lagged_vals(series,l):
# Garbage implementation but still right
    return np.concatenate([[x[i:i+l] for i in range(x.shape[0]) if i+l <= x.shape[0]] for x in series]
                          ,axis = 0)

# Sample 2D numpy array
something = np.array([[1,2,2,3],[2,2,3,3]])
lagged_vals(something,2) # Works as expected

# array([[1, 2],
#     [2, 2],
#     [2, 3],
#     [2, 2],
#     [2, 3],
#     [3, 3]])


np.lib.stride_tricks.as_strided(something,
                               (something.shape[0]*something.shape[1],2),
                               (8,8))

# array([[1, 2],
#        [2, 2],
#        [2, 3],
#        [3, 2], <--- across subarray stride, which I do not want
#        [2, 2],
#        [2, 3],
#        [3, 3])

如何在np.lib.stride_tricks 实现中删除该特定行?以及如何为大型 numpy 数组扩展这种跨数组步幅删除?

【问题讨论】:

  • 那么,您可以接受这些步幅的 3D 输出,还是必须有 2D 输出?

标签: python arrays python-3.x numpy stride


【解决方案1】:

当然,np.lib.stride_tricks.as_strided 可以做到这一点。这是一种方法-

from numpy.lib.stride_tricks import as_strided

L = 2 # window length
shp = a.shape
strd = a.strides

out_shp = shp[0],shp[1]-L+1,L
out_strd = strd + (strd[1],)

out = as_strided(a, out_shp, out_strd).reshape(-1,L)

样本输入、输出-

In [177]: a
Out[177]: 
array([[0, 1, 2, 3],
       [4, 5, 6, 7]])

In [178]: out
Out[178]: 
array([[0, 1],
       [1, 2],
       [2, 3],
       [4, 5],
       [5, 6],
       [6, 7]])

请注意,重塑的最后一步会强制它在那里进行复制。但如果我们需要最终输出为2D,这是无法避免的。如果我们对3D 输出没问题,请跳过该重塑,从而实现view,如示例案例所示 -

In [181]: np.shares_memory(a, out)
Out[181]: False

In [182]: as_strided(a, out_shp, out_strd)
Out[182]: 
array([[[0, 1],
        [1, 2],
        [2, 3]],

       [[4, 5],
        [5, 6],
        [6, 7]]])

In [183]: np.shares_memory(a, as_strided(a, out_shp, out_strd) )
Out[183]: True

【讨论】:

  • 谢谢!经过测试和投票!干杯!!我更喜欢它是 2D 的。
猜你喜欢
  • 1970-01-01
  • 2022-01-18
  • 1970-01-01
  • 1970-01-01
  • 2022-01-18
  • 1970-01-01
  • 2019-11-29
  • 1970-01-01
  • 2019-04-05
相关资源
最近更新 更多