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



我正在编写一个线性回归类,它将模型与一些数据相匹配,类似于scikit-learn实现。

一旦模型适合,我希望能够调用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

训练后的权重wfit()返回,因此用户可以将这些权重存储为变量以稍后传递给predict()方法。

lm = LinReg()
w = lm.fit(x,y)
y_pred = lm.predict(x_new, w) # don't want to pass w here

但是,我不想从fit()返回w;一旦在fit()中计算出w,我想以某种方式存储它,这样用户就不必关心权重,而且也可以在predict()方法中轻松使用权重。

我该怎么做?有没有一种Python或标准OO方法可以做到这一点?

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

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

最新更新