Skip to content

Fix ValueError when refitting after load(fitted_as_initial=True)#333

Open
gaoflow wants to merge 1 commit into
ECSHackWeek:mainfrom
gaoflow:fix-310-refit-after-load-fitted-initial
Open

Fix ValueError when refitting after load(fitted_as_initial=True)#333
gaoflow wants to merge 1 commit into
ECSHackWeek:mainfrom
gaoflow:fix-310-refit-after-load-fitted-initial

Conversation

@gaoflow
Copy link
Copy Markdown

@gaoflow gaoflow commented Jun 1, 2026

Summary

Loading a previously-fitted model with fitted_as_initial=True and then refitting it on a new spectrum raises a ValueError, as reported in #310:

ValueError: operands could not be broadcast together with shapes (n,) (0,)

Root cause

BaseCircuit.load(..., fitted_as_initial=True) stores the fitted parameters as a numpy array:

self.initial_guess = np.array(json_data['Parameters'])

The subsequent fit() then checks emptiness with if self.initial_guess != []:. For a numpy array this is an element-wise comparison, which NumPy tries to broadcast against the empty list [] (shape (0,)) and raises the broadcasting error. (This matches the workaround noted in the issue thread — manually casting initial_guess back to a list.)

Fix

Test for emptiness with len(self.initial_guess) != 0 instead. This is robust whether initial_guess is a list (the construction-time type) or a numpy array (the post-load type), and preserves the existing behaviour for the empty case.

Reproduction

import numpy as np
from impedance.models.circuits import CustomCircuit

c = CustomCircuit('R0-p(R1,C1)', initial_guess=[90, 180, 2e-5])
c.fit(freqs, Z)
c.save('m.json')

c2 = CustomCircuit()
c2.load('m.json', fitted_as_initial=True)   # initial_guess is now an ndarray
c2.fit(freqs, Z)                            # -> ValueError before this fix

Verification

Added a regression test test_refit_after_load_fitted_as_initial in impedance/tests/test_model_io.py that fits a model, saves it, reloads it with fitted_as_initial=True, and refits. It fails on the current code with the reported (n,) (0,) broadcasting error and passes with this fix. The existing test_model_io suite continues to pass.

Fixes #310.

CustomCircuit.load(..., fitted_as_initial=True) stores the fitted
parameters as a numpy array in self.initial_guess. A subsequent call to
fit() then evaluated self.initial_guess != [], which NumPy
broadcasts element-wise, raising:

    ValueError: operands could not be broadcast together with
    shapes (n,) (0,)

Check emptiness with len() instead so the guard works for both lists
and numpy arrays. Fixes ECSHackWeek#310.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ValueError while loading the saved model and using its fitted parameters as initial guess for the new EIS

1 participant