Scikit 学习:忘记之前的训练数据

Sem*_*aki 5 python scikit-learn

在 scikit learn 我有一个模型(在我的例子中是一个线性模型)

clf = linear_model.LinearRegression()
Run Code Online (Sandbox Code Playgroud)

我可以用一些数据训练这个模型

clf.fit(x1,y1)
Run Code Online (Sandbox Code Playgroud)

但是如果我再次调用fit它会继续训练模型。

clf.fit(x2,y2)
Run Code Online (Sandbox Code Playgroud)

现在 clf 是一个用 (x1,y1) 和 (x2,y2) 训练的模型

如果我想从 0 开始训练,我可以通过重新定义重新创建模型 clf

clf = linear_model.LinearRegression()
clf.fit(x1,y1)
# save the model
# ...
clf = linear_model.LinearRegression()
clf.fit(x2,y2)
Run Code Online (Sandbox Code Playgroud)

但是我不想再次定义 clf:

基本上之前选择了回归量的类型,例如:

if params.linear_algorithm == 'least_squares':
    clf = linear_model.LinearRegression()
elif params.linear_algorithm == 'ridge':
    clf = linear_model.Ridge()
elif params.linear_algorithm == 'lasso':
    clf = linear_model.Lasso()
Run Code Online (Sandbox Code Playgroud)

所以我不想在我的 train 函数内部clf用所有条件块重新定义,相反我只想clf从以前的训练中清除它并重新使用它来训练另一组数据。

clf 是否有一种方法可以清除迄今为止所学的内容,因此当我调用 clf.fit(x2,y2) 时仅针对此数据进行训练?

编辑:你们是对的,每次都覆盖训练。

我的问题是我将模型保存在字典中,它只是引用了 clf,所以每次重新训练 clf 时,所有以前的保存都会更改。

每次重新定义 clf 都会创建一个新对象,因此每个保存点现在都是不同的模型

例子

for i in range(3):
   # get the x and y
   # ...
   clf.fit(x,y)
   model[i] = clf
Run Code Online (Sandbox Code Playgroud)

知道如何每次保存不同的模型而不是将所有模型 [i] 指向同一个 clf 吗?

Mic*_*tti 9

你的假设是错误的。根据Scikit-Learn 文档

多次调用 fit() 将覆盖之前任何 fit() 学到的知识。

因此,您可以安全地使用您的代码,它将实现您的需求。