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

标签 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

训练后的权重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() 方法中轻松使用。

我该怎么做?有没有 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/

相关文章:

java - 为什么在java中输出这个

php - 如何使用标签缓存MySQL数据以在需要时删除缓存?

javascript - 使用 Javascript 加载和缓存图像并了解 HTTP 状态代码

python - 如何使用 OpenCV 和 Python 提取最大连通分量?

Python 3 与 Bs4 的抓取

python - Dask: Groupby 和 'First'/'Last' in agg

java - Java 中的递归 Set 方法 - Perl 中的默认变量?

python - Python 中带有管道的 Shell 命令

php - 在函数php中访问类内的公共(public)静态变量

caching - Redis集群-网络延迟