Tag: numpy

在Python中加速矩阵向量乘法和求幂,可能通过调用C / C ++

我目前正在研究机器学习项目 – 给定数据矩阵Z和向量rho – 我必须计算rho处逻辑损失函数的值和斜率。 计算涉及基本的矩阵向量乘法和log / exp运算,以避免数值溢出(在上一篇文章中描述)。 我目前正在使用NumPy在Python中执行此操作,如下所示(作为参考,此代码运行时间为0.2秒)。 虽然这很好用,但我想加快速度,因为我在代码中多次调用该函数(它代表了我项目中90%以上的计算)。 我正在寻找任何方法来改善没有并行化的代码的运行时间(即只有1个CPU)。 我很高兴使用Python中任何公开的软件包,或者调用C或C ++(因为我听说这可以将运行时间提高一个数量级)。 预处理数据矩阵Z也可以。 为了更好的计算可以利用的一些事情是矢量rho通常是稀疏的(大约50%的条目= 0)并且通常存在比列多得多的行(在大多数情况下n_cols <= 100 ) import time import numpy as np np.__config__.show() #make sure BLAS/LAPACK is being used np.random.seed(seed = 0) #initialize data matrix X and label vector Y n_rows, n_cols = 1e6, 100 X = np.random.random(size=(n_rows, n_cols)) Y = np.random.randint(low=0, […]

c malloc数组指针在cython中返回

如何有效地将cython中的malloc数组指针(或numpy数组指针)返回到python3。 只要我不返回数组指针,cython代码就可以正常工作 我想要: def double complex* randn_zig(int n): … r = malloc(n*n*sizeof(double complex)) … return r c11(gcc 11)等价物是: double complex* randn_zig(int n){ r = malloc(n*n*sizeof(double complex)) return r } 我试过 randn_zig(int n): 和randn_zig( r, int n): 到目前为止,其他排列没有成功。 c和cython代码版本的速度是Numby / pylab randn版本的5倍,如果我能找到一种方法来返回指向大型10 ^ 6到10 ^ 10双复数组的指针。

Numpy C API:链接多个目标文件

我正在使用numpy的C API来编写一些用于矩阵计算的函数。 今天我想将我的函数的某些部分移动到一个单独的.c文件中,并使用标头来声明它们。 现在我有一个与numpy的import_array函数有关的奇怪问题。 我试图尽可能地简化问题。 起初有工作计划: mytest.c #include “mytest.h” PyObject* my_sub_function() { npy_intp dims[2] = {2, 2}; double data[] = {0.1, 0.2, 0.3, 0.4}; PyArrayObject* matrix = (PyArrayObject*)PyArray_SimpleNew(2, dims, NPY_FLOAT64); memcpy(PyArray_DATA(matrix), data, sizeof(double) * dims[0] * dims[1]); return (PyObject*)matrix; } static PyObject* my_test_function(PyObject* self, PyObject* args) { return my_sub_function(); } static PyMethodDef methods[] = { […]

为什么我的python / numpy示例比纯C实现更快?

我在python和C.中有几乎相同的代码.Python示例: import numpy nbr_values = 8192 n_iter = 100000 a = numpy.ones(nbr_values).astype(numpy.float32) for i in range(n_iter): a = numpy.sin(a) C示例: #include #include int main(void) { int i, j; int nbr_values = 8192; int n_iter = 100000; double x; for (j = 0; j < nbr_values; j++){ x = 1; for (i=0; i<n_iter; i++) x = […]

numpy数组C api

我有一个C ++函数返回一个std :: vector,我想在python中使用它,所以我使用的是C numpy api: static PyObject * py_integrate(PyObject *self, PyObject *args){ … std::vector integral; cpp_function(integral); // This changes integral npy_intp size = {integral.size()}; PyObject *out = PyArray_SimpleNewFromData(1, &size, NPY_DOUBLE, &(integral[0])); return out; } 这是我从python中调用它的方式: import matplotlib.pyplot as plt a = py_integrate(parameters) print a fig = plt.figure() ax = fig.add_subplot(111) ax.plot(a) print a 会发生什么:第一次打印没问题,值是正确的。 […]

C与Python / numpy的数学表现不佳

近似重复/​​相关: BLAS如何获得如此极端的性能? (如果你想在C语言中快速使用matmul,那么除非你想亲自调整自己的asm版本,否则请认真使用一个好的BLAS库。)但这并不意味着看到编译欠优化矩阵代码时会发生什么并不重要。 如何优化矩阵乘法(matmul)代码,以便在单个处理器内核上快速运行 矩阵乘法与块 出于兴趣,我决定比较(不熟练的)手写C与Python / numpy的性能,执行两个大的方形矩阵的简单矩阵乘法,填充从0到1的随机数。 我发现python / numpy超过我的C代码超过10,000x这显然是不对的,所以我的C代码导致它执行得如此糟糕? (甚至用-O3或-Ofast编译) python: import time import numpy as np t0 = time.time() m1 = np.random.rand(2000, 2000) m2 = np.random.rand(2000, 2000) t1 = time.time() m3 = m1 @ m2 t2 = time.time() print(‘creation time: ‘, t1 – t0, ‘ \n multiplication time: ‘, t2 – t1) […]

如何在Cython中动态声明2D c数组

我需要使用各种大小的2D numpy数组执行大量工作,我想将这些计算卸载到cython上。 我的想法是我的2D numpy数组将从python传递到cython,在那里它将被转换为c-array或内存视图,并用于其他c级函数的级联中进行计算。 经过一些分析后,由于一些严重的python开销,我排除了在cython中使用numpy数组。 使用内存视图更快,更容易使用,但我怀疑我可以使用c-arrays进一步加速。 这是我的问题 – 如何在没有使用设定值预定义其尺寸的情况下在cython中声明2D c数组? 例如,我可以通过这种方式从numpy创建一个c-array: narr = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]], dtype=np.dtype(“i”)) cdef int c_arr[3][4]: for i in range(3): for j in range(4): c_arr[i][j] = narr[i][j] 然后将其传递给函数: cdef void somefunction(int c_Arr[3][4]): … 但这意味着我有一个固定的数组sizde,在我的情况下将是无用的。 所以我尝试过这样的事情: narr = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]], dtype=np.dtype(“i”)) cdef int a = np.shape(narr)[0] cdef int b = np.shape(narr)[1] cdef int c_arr[a][b]: # […]

Numpy C-Api示例给出了SegFault

我试图理解Python C-Api是如何工作的,我想在Python和C扩展之间交换numpy数组。 所以,我开始了这个教程: http : //dsnra.jpl.nasa.gov/software/Python/numpydoc/numpy-13.html 试图在那里做第一个例子,计算2d numpy数组的跟踪的C模块对我来说非常整洁,因为我也想在2d数组中进行基本操作。 #include #include “Numeric/arrayobject.h” #include int main(){ Py_Initialize(); import_array(); } static char doc[] = “This is the C extension for xor_masking routine”; static PyObject * trace(PyObject *self, PyObject *args) { PyObject *input; PyArrayObject *array; double sum; int i, n; if (!PyArg_ParseTuple(args, “O”, &input)) return NULL; array = (PyArrayObject […]

在C / C ++中使用Python代码

我在嵌入式Linux环境中工作,我有一些我想使用的Python代码。 我的Python代码只是在做一些数学运算,而不是使用Numpy以外的任何库和常用的库。 有没有办法建立一个我可以用C或C ++代码调用的库?

使用ctypes将2d numpy数组传递给c

使用ctypes将numpy 2d – 数组传递给ac函数的正确方法是什么? 到目前为止我的当前方法(导致段错误): c代码: void test(double **in_array, int N){ int i,j; for(i = 0; i<N; i++){ for(j = 0; j<N; j++){ printf("%e \t", in_array[i][j]); } printf("\n"); } } python代码: from ctypes import * import numpy.ctypeslib as npct array_2d_double = npct.ndpointer(dtype=np.double,ndim=2, flags=’CONTIGUOUS’) liblr = npct.load_library(‘libtest.so’, ‘./src’) liblr.test.restype = None liblr.test.argtypes = [array_2d_double, c_int] x […]