【问题标题】:Whenever I try to use @jit on my class method, I get IndentationError: unexpected indent每当我尝试在我的类方法上使用 @jit 时,我都会收到 IndentationError: unexpected indent
【发布时间】:2014-09-07 15:11:05
【问题描述】:

我几天来一直在努力让@jit 工作以加快我的代码速度。 最后我遇到了这个,描述了在对象方法中添加@jithttp://williamjshipman.wordpress.com/2013/12/24/learning-python-eight-ways-to-filter-an-image

我有一个名为GentleBoostC 的类,我想加快其中名为train 的方法。 train 接受三个参数(一个二维数组、一个一维数组和一个整数),并且不返回任何内容。

这是我在代码中的内容:

import numba
from numba import jit, autojit, int_, void, float_, object_


class GentleBoostC(object):
    # lots of functions

    # and now the function I want to speed up
    @jit (void(object_,float_[:,:],int_[:],int_)) 
    def train(self, X, y, H):
        # do stuff

但我不断收到缩进错误,指向定义 train 函数的行。我的缩进没有任何问题。我重新缩进了我的整个代码。如果我用@jit 注释掉这一行,那么就没有问题了。

这是确切的错误:

   @jit (void(object_,float_[:,:],int_[:],int_))
  File "C:\Users\app\Anaconda\lib\site-packages\numba\decorators.py", line 224, in _jit_decorator
    nopython=nopython, func_ast=func_ast, **kwargs)
  File "C:\Users\app\Anaconda\lib\site-packages\numba\decorators.py", line 133, in compile_function
    func_env = pipeline.compile2(env, func, restype, argtypes, func_ast=func_ast, **kwds)
  File "C:\Users\app\Anaconda\lib\site-packages\numba\pipeline.py", line 133, in compile2
    func_ast = functions._get_ast(func)
  File "C:\Users\app\Anaconda\lib\site-packages\numba\functions.py", line 89, in _get_ast
    ast.PyCF_ONLY_AST | flags, True)
  File "C:\Users\app\Documents\Python Scripts\gentleboost_c_class_jit_v5_nolimit.py", line 1
    def train(self, X, y, H):
    ^
IndentationError: unexpected indent

【问题讨论】:

  • 使用python -tt 运行您的脚本。您可能确实有缩进问题。 cat -eT filename.py 显示了什么?查看@jit 行和周围的上下文。
  • 那么当我注释掉@jit 行时,为什么它完全没有问题?无论如何,我该如何使用 python -tt?我正在使用 Anaconda 的 Spyder 运行 python - 我将如何从那里做呢?
  • 两个选项:@jit 行混合制表符和空格与其他行不一致,或者您正在使用尚不支持装饰器的古老 Python 版本。
  • 我使用的是 Python 2.7
  • 我的@jit 行正确吗?

标签: python jit numba


【解决方案1】:

根据我从文档中看到的,您不能将装饰器应用于方法;您看到的错误来自 JIT 解析器在不在 class 语句的上下文中时未处理源代码缩进。

如果您希望编译该方法的主体,则需要将其分解为一个单独的函数,并从该方法中调用该函数:

@jit(void(object_, float_[:,:], int_[:], int_)) 
def train_function(instance, X, y, H):
    # do stuff

class GentleBoostC(object):
    def train(self, X, y, H):
        train_function(self, X, y, H)    

【讨论】:

  • 但是 train 方法访问了许多类数据成员,它会影响现有成员......所以这是否意味着我需要将它们全部作为参数传递,然后也返回受影响的东西?跨度>
  • @user961627:这就是train_function 函数接受instance 第一个参数的原因。它与self 是同一个对象,我只是选择了一个不同的名称以区别于方法第一个参数的通用约定。
  • 现在有一个后续问题:stackoverflow.com/questions/25685916/…... 确实与对对象的有限支持有关吗?
  • 为了将函数保留在类体内,可以将其设为类的静态方法,如stackoverflow.com/a/52722636所示
猜你喜欢
  • 2020-04-07
  • 1970-01-01
  • 2021-10-18
  • 1970-01-01
  • 2022-09-28
  • 1970-01-01
  • 1970-01-01
  • 2023-02-08
  • 2014-08-13
相关资源
最近更新 更多