python – 用Numba优化整数元组的字典?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 用Numba优化整数元组的字典?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2546字,纯文字阅读大概需要4分钟。
内容图文
我正在学习如何使用Numba(虽然我已经非常熟悉Cython).我该怎么做才能加快这段代码的速度?请注意,该函数返回一组两元组的dict.我正在使用IPython笔记本.我更喜欢Numba而不是Cython.
@autojit
def generateadj(width,height):
adj = {}
for y in range(height):
for x in range(width):
s = set()
if x>0:
s.add((x-1,y))
if x<width-1:
s.add((x+1,y))
if y>0:
s.add((x,y-1))
if y<height-1:
s.add((x,y+1))
adj[x,y] = s
return adj
我设法在Cython中写这个,但我不得不放弃数据结构的方式.我不喜欢这个.我在Numba文档中的某处读到它可以处理列表,元组等基本内容.
%%cython
import numpy as np
def generateadj(int width, int height):
cdef int[:,:,:,:] adj = np.zeros((width,height,4,2), np.int32)
cdef int count
for y in range(height):
for x in range(width):
count = 0
if x>0:
adj[x,y,count,0] = x-1
adj[x,y,count,1] = y
count += 1
if x<width-1:
adj[x,y,count,0] = x+1
adj[x,y,count,1] = y
count += 1
if y>0:
adj[x,y,count,0] = x
adj[x,y,count,1] = y-1
count += 1
if y<height-1:
adj[x,y,count,0] = x
adj[x,y,count,1] = y+1
count += 1
for i in range(count,4):
adj[x,y,i] = adj[x,y,0]
return adj
解决方法:
虽然numba支持像dicts和sets这样的Python数据结构,但它在对象模式下也是如此.从numba词汇表中,对象模式定义为:
A Numba compilation mode that generates code that handles all values
as Python objects and uses the Python C API to perform all operations
on those objects. Code compiled in object mode will often run no
faster than Python interpreted code, unless the Numba compiler can
take advantage of loop-jitting.
因此,在编写numba代码时,您需要坚持使用内置数据类型,例如数组.这里有一些代码可以做到这一点:
@jit
def gen_adj_loop(width, height, adj):
i = 0
for x in range(width):
for y in range(height):
if x > 0:
adj[i,0] = x
adj[i,1] = y
adj[i,2] = x - 1
adj[i,3] = y
i += 1
if x < width - 1:
adj[i,0] = x
adj[i,1] = y
adj[i,2] = x + 1
adj[i,3] = y
i += 1
if y > 0:
adj[i,0] = x
adj[i,1] = y
adj[i,2] = x
adj[i,3] = y - 1
i += 1
if y < height - 1:
adj[i,0] = x
adj[i,1] = y
adj[i,2] = x
adj[i,3] = y + 1
i += 1
return
这需要一个数组adj.每行的格式为x y adj_x adj_y.所以对于(3,4)处的像素,我们有四行:
3 4 2 4
3 4 4 4
3 4 3 3
3 4 3 5
我们可以将上面的函数包装在另一个中:
@jit
def gen_adj(width, height):
# each pixel has four neighbors, but some of these neighbors are
# off the grid -- 2*width + 2*height of them to be exact
n_entries = width*height*4 - 2*width - 2*height
adj = np.zeros((n_entries, 4), dtype=int)
gen_adj_loop(width, height, adj)
此功能非常快,但不完整.我们必须将adj转换为您问题中表单的字典.问题是这是一个非常缓慢的过程.我们必须迭代adj数组并将每个条目添加到Python字典中.这不能被numba jitted.
所以底线是这样的:结果是元组字典的要求确实限制了你可以优化这些代码的程度.
内容总结
以上是互联网集市为您收集整理的python – 用Numba优化整数元组的字典?全部内容,希望文章能够帮你解决python – 用Numba优化整数元组的字典?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。