Python 如何存储/缓存类中方法的值,以便以后在同一类的其他方法中使用?
我正在写一个线性回归类,它将模型与一些数据相匹配,类似于 模型拟合后,我希望能够调用Python 如何存储/缓存类中方法的值,以便以后在同一类的其他方法中使用?,python,oop,caching,machine-learning,Python,Oop,Caching,Machine Learning,我正在写一个线性回归类,它将模型与一些数据相匹配,类似于 模型拟合后,我希望能够调用predict()方法,而不必将经过训练的模型权重作为参数传递给该方法。到目前为止,我所掌握的情况如下 class LinReg: """ Fit a linear model to data""" def __init__(self): .... def fit(self, x, y): """Fit a model to data x with tar
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()
方法中使用权重
lm = LinReg()
w = lm.fit(x,y)
y_pred = lm.predict(x_new, w) # don't want to pass w here
我该怎么做?是否有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