V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
going2think
V2EX  ›  Python

numpy 如何取消循环操作

  •  
  •   going2think · 2019-06-06 17:46:26 +08:00 · 2115 次点击
    这是一个创建于 1778 天前的主题,其中的信息可能已经有所发展或是发生改变。

    有如下代码,请问该如何去掉两重 for 循环,使用 numpy 的数组操作来实现呢?谢谢各位了

    import numpy as np
    
    a = np.zeros((100, 100))
    b = np.zeros((100, 100))
    ds = []
    for i in range(5, 95):
        for j in range(5, 95):
            pa = a[i-5:i+5, j-5:j+5]
            pb = b[i-5:i+5, j-5:j+5]
            d = pa - pb
            ds.append(d)
    
    return ds
    
    5 条回复    2019-06-07 20:35:48 +08:00
    necomancer
        1
    necomancer  
       2019-06-06 22:25:24 +08:00   ❤️ 1
    from skimage.util.shape import view_as_windows

    a = np.random.random((100,100))
    b = np.random.random((100,100))

    ret = view_as_windows(a-b, (10,10))

    In [1]: np.allclose(ret[:-1,:-1,:], ds.reshape(90,90,10,10))
    Out[1]: True

    顺带一提,view_as_windows 有 step 函数,你这个情况 step=1,是默认参数。
    necomancer
        2
    necomancer  
       2019-06-06 22:26:11 +08:00   ❤️ 1
    step=10 在你的例子里应该相当于刚好无重叠,可以用 view_as_blocks 函数。
    necomancer
        3
    necomancer  
       2019-06-06 22:49:41 +08:00   ❤️ 1
    这个函数基本上是在用 np.lib.stride_tricks.as_strided,所以如果你没有 skimage,去 skimage 找到那个函数拷过来就行。麻烦的地方只在怎么根据 window_size 和 step 算 stride
    going2think
        4
    going2think  
    OP
       2019-06-06 23:33:17 +08:00
    @necomancer 感谢帮助,我去试试~
    xgdgsc
        5
    xgdgsc  
       2019-06-07 20:35:48 +08:00
    这种直接改 numba
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5467 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 06:05 · PVG 14:05 · LAX 23:05 · JFK 02:05
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.