大编辑:
================
为了清楚起见,我要删除旧的结果,代之以最近的结果。问题仍然是一样的:我是否正确地使用了Cython和Numba,以及可以对代码进行哪些改进?(我有一个更新的、更简单的临时IPython笔记本,上面有所有的代码和结果这里)
1)
我想我明白了为什么Cython,Numba和CPython之间最初没有什么区别:这是因为我喂养了它们
numpy数组作为输入:
x = np.asarray([x_i*np.random.randint(8,12)/10 for x_i in range(n)])而不是清单:
x = [x_i*random.randint(8,12)/10 for x_i in range(n)]使用Numpy数组作为数据输入的基准测试

使用Python列表作为输入的基准测试

2)
我用显式循环替换了zip()函数,但是,它并没有产生太大的影响。守则将是:
CPython
def py_lstsqr(x, y):
""" Computes the least-squares solution to a linear matrix equation. """
len_x = len(x)
x_avg = sum(x)/len_x
y_avg = sum(y)/len(y)
var_x = 0
cov_xy = 0
for i in range(len_x):
temp = (x[i] - x_avg)
var_x += temp**2
cov_xy += temp*(y[i] - y_avg)
slope = cov_xy / var_x
y_interc = y_avg - slope*x_avg
return (slope, y_interc) Cython
%load_ext cythonmagic
%%cython
def cy_lstsqr(x, y):
""" Computes the least-squares solution to a linear matrix equation. """
cdef double x_avg, y_avg, var_x, cov_xy,\
slope, y_interc, x_i, y_i
cdef int len_x
len_x = len(x)
x_avg = sum(x)/len_x
y_avg = sum(y)/len(y)
var_x = 0
cov_xy = 0
for i in range(len_x):
temp = (x[i] - x_avg)
var_x += temp**2
cov_xy += temp*(y[i] - y_avg)
slope = cov_xy / var_x
y_interc = y_avg - slope*x_avg
return (slope, y_interc)南巴
from numba import jit
@jit
def numba_lstsqr(x, y):
""" Computes the least-squares solution to a linear matrix equation. """
len_x = len(x)
x_avg = sum(x)/len_x
y_avg = sum(y)/len(y)
var_x = 0
cov_xy = 0
for i in range(len_x):
temp = (x[i] - x_avg)
var_x += temp**2
cov_xy += temp*(y[i] - y_avg)
slope = cov_xy / var_x
y_interc = y_avg - slope*x_avg
return (slope, y_interc)发布于 2014-05-09 14:12:34
我认为Numba正在发生的事情是:
Numba工作在Numpy数组上。没别的了。其他一切都与Numba无关。
zip返回一个任意项的迭代器,Numba无法对其进行查看。因此,Numba不能做太多的编译。
使用for i in range(...)循环索引可能会产生更好的结果,并允许更强的类型推断。
发布于 2015-04-18 11:13:30
使用内置sum()可能会导致问题。
下面是在Numba中运行更快的线性回归代码:
@numba.jit
def ols(x, y):
"""Simple OLS for two data sets."""
M = x.size
x_sum = 0.
y_sum = 0.
x_sq_sum = 0.
x_y_sum = 0.
for i in range(M):
x_sum += x[i]
y_sum += y[i]
x_sq_sum += x[i] ** 2
x_y_sum += x[i] * y[i]
slope = (M * x_y_sum - x_sum * y_sum) / (M * x_sq_sum - x_sum**2)
intercept = (y_sum - slope * x_sum) / M
return slope, intercepthttps://stackoverflow.com/questions/23550483
复制相似问题