ValueError:cython中的ndarray不是C连续的 [英] ValueError: ndarray is not C-contiguous in cython

查看:143
本文介绍了ValueError:cython中的ndarray不是C连续的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在cython中编写了以下函数来估计对数可能性

I have written the following function in cython to estimate the log-likelihood

@cython.boundscheck(False)
@cython.wraparound(False)
def likelihood(double m,
               double c,
               np.ndarray[np.double_t, ndim=1, mode='c'] r_mpc not None,
               np.ndarray[np.double_t, ndim=1, mode='c'] gtan not None,
               np.ndarray[np.double_t, ndim=1, mode='c'] gcrs not None,
               np.ndarray[np.double_t, ndim=1, mode='c'] shear_err not None,
               np.ndarray[np.double_t, ndim=1, mode='c'] beta not None,
               double rho_c,
               np.ndarray[np.double_t, ndim=1, mode='c'] rho_c_sigma not None):
    cdef double rscale = rscaleConstM(m, c,rho_c, 200)

    cdef Py_ssize_t ngals = r_mpc.shape[0]

    cdef np.ndarray[DTYPE_T, ndim=1, mode='c'] gamma_inf = Sh(r_mpc, c, rscale, rho_c_sigma)
    cdef np.ndarray[DTYPE_T, ndim=1, mode='c'] kappa_inf = Kap(r_mpc, c, rscale, rho_c_sigma)


    cdef double delta = 0.
    cdef double modelg = 0.
    cdef double modsig = 0.

    cdef Py_ssize_t i
    cdef DTYPE_T logProb = 0.


    #calculate logprob
    for i from ngals > i >= 0:

        modelg = (beta[i]*gamma_inf[i] / (1 - beta[i]*kappa_inf[i]))

        delta = gtan[i] - modelg

        modsig = shear_err[i]

        logProb = logProb -.5*(delta/modsig)**2  - logsqrt2pi - log(modsig)


    return logProb

但是当我运行此函数的编译版本时,出现以下错误消息:

but when I run the compiled version of this function, I get the following error message:

  File "Tools.pyx", line 3, in Tools.likelihood 
    def likelihood(double m,
ValueError: ndarray is not C-contiguous

我不太明白为什么会出现此问题?我将不胜感激获得任何有用的提示.

I could not quite understand why this problem occurs??!!! I will appreciate to get any useful tips.

推荐答案

在收到错误之前,请尝试打印要传递给likelihood的numpy数组的flags属性.您可能会看到类似的内容:

Just before you get the error, try printing the flags attribute of the numpy array(s) you're passing to likelihood. You'll probably see something like:

In [2]: foo.flags
Out[2]: 
  C_CONTIGUOUS : False
  F_CONTIGUOUS : True
  OWNDATA : True
  WRITEABLE : True
  ALIGNED : True
  UPDATEIFCOPY : False

请注意在其上显示C_CONTIGUOUS : False的位置,因为这就是问题所在.要解决此问题,只需将其转换为C顺序即可:

Note where it says C_CONTIGUOUS : False, because that's the issue. To fix it, simply convert it to C-order:

In [6]: foo = foo.copy(order='C')

In [7]: foo.flags
Out[7]: 
  C_CONTIGUOUS : True
  F_CONTIGUOUS : False
  OWNDATA : True
  WRITEABLE : True
  ALIGNED : True
  UPDATEIFCOPY : False

这篇关于ValueError:cython中的ndarray不是C连续的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆