【问题标题】:Cython Class, create NumPy with ZerosCython 类,用零创建 NumPy
【发布时间】:2015-05-04 10:41:19
【问题描述】:

我正在尝试创建一个 cython 类,该类创建一个带有零的 NumPy。后来我想在那个 Numpy 中写浮点值...... 我的 python 类如下所示:

class test:
    def __init__(self, b):
       self.b = b
       self.eTest = np.zeros((100, 100))

到目前为止,我的 cython 类看起来像这样:

import numpy as np
cimport numpy as np
FTYPE = np.float
ctypedef np.float_t FTYPE_t
cdef class test:
   def __init__(self, b):
      cdef np.ndarray[FTYPE_t, ndim=2, mode='c'] eTest   <<<works fine without this line
      self.eTest = np.zeros((100,100), dtype=FTYPE)

到目前为止,我的 cython 代码不起作用。我正在努力解决如何在没有任何 Python 的情况下创建零(100、100)的 NumPy 的问题。这甚至可能吗?我对cython不是很熟悉,如果我问一些非常琐碎的问题,我很抱歉!

非常感谢您的帮助和建议!

【问题讨论】:

  • 当你说它“不起作用”时,到底发生了什么?
  • 我得到一个 CompileError,所以我猜我写课程的方式有问题?!
  • 如果您告诉我们您遇到的什么编译器错误,通常会非常有用。
  • CompileError: command 'cc' failed with exit status 1

标签: python performance numpy optimization cython


【解决方案1】:

重新定义你的类::

  cdef class test:
  cdef double[:,:] eTest
  def __init__(self, b):
      cdef np.ndarray[FTYPE_t, ndim=2, mode='c'] tmp
      tmp = np.zeros((100,100), dtype=FTYPE)
      self.eTest = tmp

您的 ndarray(在这种情况下为 tmp)只能是函数(在这种情况下为构造函数)的本地,因此您应该首先将 eTest 声明为支持缓冲区的类型(在我的示例中为 memoryview)和然后将 ndarray 复制到其中。

作为旁注,我会直接将 zeros ndarray 分配给eTest

cdef class test:
      cdef double[:,:] eTest
      def __init__(self, b):
          self.eTest =  np.zeros((100,100), dtype=FTYPE)

但我保留了你的结构以备不时之需。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-23
    • 1970-01-01
    • 2012-03-17
    • 2019-05-19
    • 2014-01-27
    • 1970-01-01
    • 2022-12-18
    • 2011-07-16
    相关资源
    最近更新 更多