Whenever I try to use @jit on my class method, I get IndentationError: unexpected indent

旧时模样 提交于 2019-11-30 16:08:12

问题


I've been trying for several days to get @jit working to speed up my code. Finally I came across this, describing adding @jit to object methods: http://williamjshipman.wordpress.com/2013/12/24/learning-python-eight-ways-to-filter-an-image

I have a class called GentleBoostC and I want to speed up the method within it that's called train. train accepts three arguments (a 2D array, a 1D array, and an integer), and returns nothing.

This is what I have in code:

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

But I keep getting an indentation error, pointing to the line that defines the train function. There is nothing wrong with my indents. I have re-indented my entire code. And if I comment out the line with @jit, then there are no problems.

Here's the exact error:

   @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

回答1:


From what I can see from the documentation, you cannot apply the decorator to a method; the error you see is from the JIT parser not handling the source code indentation when not in the context of a class statement.

If you want the body of that method to be compiled, you'll need to factor it out to a separate function, and call that function from the method:

@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)    


来源:https://stackoverflow.com/questions/25683592/whenever-i-try-to-use-jit-on-my-class-method-i-get-indentationerror-unexpecte

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!