Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何存储/缓存类中方法的值,以便以后在同一类的其他方法中使用?_Python_Oop_Caching_Machine Learning - Fatal编程技术网

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