如何存储/缓存类中的方法的值以供以后在同一类的其他方法中使用?

时间:2018-12-10 13:21:43

标签: python oop caching machine-learning

我正在编写一个线性回归类,该模型使模型适合某些数据,类似于scikit-learn implementation

模型适合后,我希望能够调用,而不必将训练后的模型权重作为参数传递给该方法。到目前为止,我的情况在下面

predict()

训练后的权重class LinReg: """ Fit a linear model to data""" def __init__(self): .... def fit(self, x, y): """Fit a model to data x with targets y""" ... # model weights w are calculated here return w def predict(self, x, w): """Predict the target variable of the data x using trained weights w""" ... # predicted y values, y_pred, are calulated here return y_pred w返回,因此用户可以将它们存储为变量,以便以后传递给fit()方法。

predict()

但是,我不想从lm = LinReg() w = lm.fit(x,y) y_pred = lm.predict(x_new, w) # don't want to pass w here 返回w;我想以某种方式存储fit(),一旦它在w中计算出来,以便用户不必担心权重,还可以使权重易于在{{1}中使用}方法。

我该怎么做?有pythonic或标准的OO方法可以做到这一点吗?

1 个答案:

答案 0 :(得分:1)

我将其存储为实例级属性:

def __init__(self):
    self.w = None  # define the prop here...
    ....

def fit(self, x, y):
    """Fit a model to data x with targets y"""
    ...
    # model weights w are calculated here
    self.w = your_computed_value

def predict(self, x):
    """Predict the target variable of the data x using trained weights w"""
    ...
    # predicted y values, y_pred, are calulated here
    do_something_here(self.w)
    return y_pred