Maverick
Maverick

Reputation: 51

KeyError: "Couldn't delete link (Can't delete self)"

I'm trying to delete a dataset in a HDF5 file. To be specific, i'm trying to delete the optimizer layer from a keras deep learning model which i have previously trained and saved.

The code is as follows

f = h5py.File('model.h5', 'r+')
del f['optimizer_weights']
f.close()

And the error is

KeyError: "Couldn't delete link (Can't delete self)

Error message in detail

    del f['optimizer_weights']
  File "h5py\_objects.pyx", line 54, in h5py._objects.with_phil.wrapper (D:\Build\h5py\h5py-2.7.0\h5py\_objects.c:2853)
  File "h5py\_objects.pyx", line 55, in h5py._objects.with_phil.wrapper (D:\Build\h5py\h5py-2.7.0\h5py\_objects.c:2811)
  File "C:\Users\Anaconda3\envs\tensorflow-keras-gpu\lib\site-packages\h5py\_hl\group.py", line 297, in __delitem__
    self.id.unlink(self._e(name))
  File "h5py\_objects.pyx", line 54, in h5py._objects.with_phil.wrapper (D:\Build\h5py\h5py-2.7.0\h5py\_objects.c:2853)
  File "h5py\_objects.pyx", line 55, in h5py._objects.with_phil.wrapper (D:\Build\h5py\h5py-2.7.0\h5py\_objects.c:2811)
  File "h5py\h5g.pyx", line 294, in h5py.h5g.GroupID.unlink (D:\Build\h5py\h5py-2.7.0\h5py\h5g.c:4179)
KeyError: "Couldn't delete link (Can't delete self)"

Any suggestions on how to fix this ??

Thanks!

Upvotes: 1

Views: 1892

Answers (2)

Nitay
Nitay

Reputation: 4720

Quite an old question, but try putting the file in write or append mode

f = h5py.File('model.h5', 'a')

Upvotes: 0

brittohalloran
brittohalloran

Reputation: 3634

Are you sure the dataset actually made it in there? I've gotten this wrong looking error when trying to delete a non-existent dataset.

def printname(name):
    print(name)

f.visit(printname)

# list of datasets, should contain 'dataset_name'

In code you unfortunately need to include a check for existence every time prior to deleting. To 'overwrite' a possibly already existing dataset:

with h5py.File('/path/to/h5', 'a') as f:
    if f.get('dataset_name'):
        del f['dataset_name']
    f['dataset_name'] = 'new value'

Upvotes: 1

Related Questions