python - 优化 Numba 和 Numpy 功能
问题描述
我试图让这段代码运行得更快,但我找不到任何可以加快速度的技巧。
我得到了大约 3 微秒的运行时间,问题是我调用了这个函数几百万次,而这个过程最终需要很长时间。我在 Java 中有相同的实现(只有基本的 for 循环),基本上,即使是大型训练数据,计算也是即时的(这是用于 ANN)
有没有办法加快这个速度?
我在 Windows 10 上运行 Python 2.7、numba 0.43.1 和 numpy 1.16.3
x = True
expected = 0.5
eligibility = np.array([0.1,0.1,0.1])
positive_weight = np.array([0.2,0.2,0.2])
total_sq_grad_positive = np.array([0.1,0.1,0.1])
learning_rate = 1
@nb.njit(fastmath= True, cache = True)
def update_weight_from_post_post_jit(x, expected,eligibility,positive_weight,total_sq_grad_positive,learning_rate):
if x:
g = np.multiply(eligibility,(1-expected))
else:
g = np.negative(np.multiply(eligibility,expected))
gg = np.multiply(g,g)
total_sq_grad_positive = np.add(total_sq_grad_positive,gg)
#total_sq_grad_positive = np.where(divide_by_zero,total_sq_grad_positive, tsgp_temp)
temp = np.multiply(learning_rate, g)
temp2 = np.sqrt(total_sq_grad_positive)
#temp2 = np.where(temp2 == 0,1,temp2 )
temp2[temp2 == 0] = 1
temp = np.divide(temp,temp2)
positive_weight = np.add(positive_weight, temp)
return [positive_weight, total_sq_grad_positive]
解决方案
编辑:看来@max9111 是对的。不必要的临时数组是开销的来源。
对于您的函数的当前语义,似乎有两个无法避免的临时数组——返回值[positive_weight, total_sq_grad_positive]
。但是,令我震惊的是,您可能正计划使用此函数来更新这两个输入数组。如果是这样,通过就地执行所有操作,我们可以获得最大的加速。像这样:
import numba as nb
import numpy as np
x = True
expected = 0.5
eligibility = np.array([0.1,0.1,0.1])
positive_weight = np.array([0.2,0.2,0.2])
total_sq_grad_positive = np.array([0.1,0.1,0.1])
learning_rate = 1
@nb.njit(fastmath= True, cache = True)
def update_weight_from_post_post_jit(x, expected,eligibility,positive_weight,total_sq_grad_positive,learning_rate):
for i in range(eligibility.shape[0]):
if x:
g = eligibility[i] * (1-expected)
else:
g = -(eligibility[i] * expected)
gg = g * g
total_sq_grad_positive[i] = total_sq_grad_positive[i] + gg
temp = learning_rate * g
temp2 = np.sqrt(total_sq_grad_positive[i])
if temp2 == 0: temp2 = 1
temp = temp / temp2
positive_weight[i] = positive_weight[i] + temp
@nb.jit
def test(n, *args):
for i in range(n): update_weight_from_post_post_jit(*args)
如果更新输入数组不是您想要的,您可以使用该函数开始
positive_weight = positive_weight.copy()
total_sq_grad_positive = total_sq_grad_positive.copy()
并按照您的原始代码返回它们。这几乎没有那么快,但仍然更快。
我不确定它是否可以优化为“即时”;Java 可以做到这一点让我有点惊讶,因为这对我来说看起来是一个非常复杂的函数,并且需要一些耗时的操作,例如sqrt
.
但是,您是否nb.jit
在调用此函数的函数上使用过?像这样:
@nb.jit
def test(n):
for i in range(n): update_weight_from_post_post_jit(x, expected,eligibility,positive_weight,total_sq_grad_positive,learning_rate)
在我的计算机上,这将运行时间减少了一半,这是有道理的,因为 Python 函数调用的开销非常高。
推荐阅读
- python - 在 Python 中按值对矩阵进行排序
- android-studio - 如何删除或最小化android studio资产文件夹中的Audience_Network.dex文件?
- java - Do a HTTP POST instead of a GET
- r - 使用 purrr 和 select 创建二分变量
- android - UriMatcher matching wilcard? (Crash in Android mail app)
- c++ - 当分子和分母都有一个有限的范围时,找到一个实数的有理逼近
- powershell - 从 .url 和 .lnk 文件中大量提取图标图像
- typescript - 即使我将返回语句设置为数组,函数也会返回 void?
- java-11 - 带有 Graal VM 的 Apache Ant
- sql - 如何对具有相同日期的表行进行重复数据删除并保留具有最新日期戳的行?