Search code examples
pythonmachine-learningscikit-learnlogistic-regression

Fitting multiple instances of the same scikit-learn model


I am trying to run multiple multinomial logistic regressions on my dataset. Once I run one, I am trying to append the model I just ran to a list, so I can access the specific model later. Code looks something like this

models = []
for i in range(0, 10):
  model = sklearn.linear_model.LogisticRegression()
  model.fit(x,y)
  models.append(model)

Where x and y are different in each for iteration. The issue is that the coefficients/model that i get in each element of the final array "models", is the same as the final iteration of that for loop. I am assuming this is because I am just updating the reference each iteration and not creating a new Logistic Regression model each time. Can someone point me to a better way to do this?


Solution

  • You might be interested in the clone function.

    sklearn.base.clone(estimator, *, safe=True)[source]

    Constructs a new unfitted estimator with the same parameters. Clone does a deep copy of the model in an estimator without actually copying attached data. It yields a new estimator with the same parameters that has not been fitted on any data.

    from sklearn.base import clone
    
    model = LogisticRegression()
    new_model = clone(model)