我正在编写一个线性回归类,它可以将模型拟合到某些数据,类似于 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
但是,我不想从 fit()
返回 w
;我想在 fit()
中计算出 w
后以某种方式存储它,以便用户不必关心权重,而且还可以使权重可以在 predict()
方法中轻松使用。
我该怎么做?有没有 pythonic 或标准的 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
关于python - 如何存储/缓存类中方法的值以便稍后在同一类的其他方法中使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53706580/