Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug fix: model save when file already exists #11289

Merged
merged 4 commits into from
Oct 3, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions keras/utils/io_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,11 +183,13 @@ def __init__(self, path, mode='a'):
self.data = path
self._is_file = False
elif isinstance(path, str):
self.data = h5py.File(path,)
self.data = h5py.File(path, mode=mode)
self._is_file = True
elif isinstance(path, dict):
self.data = path
self._is_file = False
if mode == 'w':
self.data.clear()
# Flag to check if a dict is user defined data or a sub group:
self.data['_is_group'] = True
else:
Expand All @@ -209,7 +211,7 @@ def __setitem__(self, attr, val):
else:
self.data[attr] = val
return
if attr in self:
if isinstance(self.data, h5py.Group) and attr in self.data:
raise KeyError('Cannot set attribute. '
'Group with name "{}" exists.'.format(attr))
if is_np:
Expand Down
23 changes: 23 additions & 0 deletions tests/test_model_saving.py
Original file line number Diff line number Diff line change
Expand Up @@ -632,6 +632,29 @@ def test_saving_recurrent_layer_without_bias():
os.remove(fname)


def test_loop_model_saving():
model = Sequential()
model.add(Dense(2, input_shape=(3,)))
model.compile(loss=losses.MSE,
optimizer=optimizers.RMSprop(lr=0.0001),
metrics=[metrics.categorical_accuracy])

x = np.random.random((1, 3))
y = np.random.random((1, 2))
_, fname = tempfile.mkstemp('.h5')

for _ in range(3):
model.train_on_batch(x, y)
save_model(model, fname, overwrite=True)
out = model.predict(x)

new_model = load_model(fname)
os.remove(fname)

out2 = new_model.predict(x)
assert_allclose(out, out2, atol=1e-05)


def test_saving_constant_initializer_with_numpy():
"""Test saving and loading model of constant initializer with numpy inputs.
"""
Expand Down