通过预测方法作为函数参数

时间:2019-01-02 23:34:18

标签: python scikit-learn arguments predict

我想通过函数参数指定要使用的预测方法。像这样:

frame = cv2.resize(frame, None, fx=0.5, fy=0.5)    

通过折衷from sklearn.linear_model import LinearRegression def Process(data_y_train, data_x_train, data_x_test, model=LinearRegression, predict_method=predict): model_fit = model().fit(data_x_train, data_y_train) predicted_values = model_fit.predict_method(data_x_test) return predicted_values 传递模型函数(例如,LinearRegression,LogisticRegression)效果很好,但是我很难通过参数model传递预测方法(例如,predict,predict_proba)。 / p>

当我指定predict_method时,出现错误“名称'predict'未定义”。如果我指定predict_method=predict,则会收到一条错误消息,提示“ LinearRegression”对象没有属性“ predict_function”。

this discussion,我也尝试过

predict_method=LinearRegression.predict

但是在这里我得到一个错误:没有名为LinearRegression的模块。

谢谢您的帮助!

1 个答案:

答案 0 :(得分:1)

我注意到在您的代码中,您没有使用在代码中任何地方传递的predict_method参数,因此我认为您编写的内容并不是您要尝试做的事情。 / p>

当前,在您的代码中,您正在将函数model().fit(data_x_train, data_y_train)的输出存储在变量model_fit中,然后调用该变量的predict_method属性。如果上述方法仍然无效,则必须是错误的出处。

我怀疑您想要要做的事情如下:

def Process(data_y_train, data_x_train, data_x_test,
            model=LinearRegression, predict_method=LinearRegression.predict):
    model_instance = model() # create an instance of the class stored in the variable 'model'
    model_instance.fit(data_x_train, data_y_train) # run the function 'fit' belonging to that instance
    predicted_values = predict_method(model_instance,data_x_test) # run the method stored in the variable 'predict_method' - you have to pass the instance the method belongs to in the first parameter
    return predicted_values

更多信息:

  • LinearRegression是一个。它定义了一堆方法,等等。
  • 要创建该类的实例,您必须执行类似inst = LinearRegression()的操作。变量inst现在是类LinearRegression
  • 的实例
  • LinearRegression.predict instance方法的示例。这意味着它需要一个实例来运行(在这种情况下,可以将其视为“进行操作”)
  • 因此,我可以直接致电inst.predict(x,y,z),但不能直接致电LinearRegression.predict(x,y,z)
  • 如果要调用LinearRegression.predict,则必须在第一个参数中传递实例:LinearRegression.predict(inst,x,y,z)

关于您随后尝试的操作:在这种情况下,从包含函数名称的字符串中调用函数不是必需的,只会增加开销,因此这可能不是正确的方法:)

希望这会有所帮助。