【问题标题】:How to load previously saved model and expand the model with new training data using scikit-learn如何使用 scikit-learn 加载先前保存的模型并使用新的训练数据扩展模型
【发布时间】:2014-12-30 02:34:59
【问题描述】:

我正在使用 scikit-learn,其中我保存了一个逻辑回归模型,其中包含 unigrams 作为训练集 1 的特征。是否可以加载此模型,然后使用来自第二个训练集的新数据实例(训练设置 2)?如果是,如何做到这一点?这样做的原因是因为我对每个训练集使用了两种不同的方法(第一种方法涉及特征损坏/正则化,第二种方法涉及自我训练)。

为了清楚起见,我添加了一些简单的示例代码:

from sklearn.linear_model import LogisticRegression as log
from sklearn.feature_extraction.text import CountVectorizer as cv
import pickle

trainText1 # Training set 1 text instances    
trainLabel1 # Training set 1 labels 
trainText2 # Training set 2 text instances    
trainLabel2 # Training set 2 labels 

clf = log()
# Count vectorizer used by the logistic regression classifier 
vec = cv() 

# Fit count vectorizer with training text data from training set 1
vec.fit(trainText1) 

# Transforms text into vectors for training set1
train1Text1 = vec.transform(trainText1) 

# Fitting training set1 to the linear logistic regression classifier 
clf.fit(trainText1,trainLabel1)

# Saving logistic regression model from training set 1
modelFileSave = open('modelFromTrainingSet1', 'wb')
pickle.dump(clf, modelFileSave)
modelFileSave.close()  

# Loading logistic regression model from training set 1    
modelFileLoad = open('modelFromTrainingSet1', 'rb')
clf = pickle.load(modelFileLoad)

# I'm unsure how to continue from here....

【问题讨论】:

    标签: python machine-learning scikit-learn


    【解决方案1】:

    LogisticRegression 在内部使用不支持增量拟合的 liblinear 求解器。相反,您可以使用SGDClassifier(loss='log') 作为partial_fit 方法,尽管在实践中也可以使用它。其他超参数不同。注意仔细网格搜索它们的最佳值。请阅读 SGDClassifier 文档了解这些超参数的含义。

    CountVectorizer 不支持增量拟合。您将不得不重用安装在火车组 #1 上的矢量化器来转换 #2。这意味着集合 #2 中尚未出现在 #1 中的任何标记都将被完全忽略。这可能不是您所期望的。

    为了缓解这种情况,您可以使用HashingVectorizer,它是无状态的,但代价是不知道这些功能的含义。阅读the documentation了解更多详情。

    【讨论】:

      猜你喜欢
      • 2014-10-13
      • 1970-01-01
      • 2019-09-09
      • 2015-10-14
      • 2019-09-30
      • 1970-01-01
      • 1970-01-01
      • 2021-03-30
      相关资源
      最近更新 更多