当尝试保存tensorflow模型时,出现“module 'h5py' has no attribute 'File'”错误。

5

我刚刚使用MNIST数字数据库制作了一个小型神经网络,并尝试将其保存。以下是完整的代码:

# Importing Libs
import h5py
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from tensorflow import keras

# ---------- PART I: Importing and cleaning Data ----------
# Importing Data
train_data = np.genfromtxt('mnist_train.csv', delimiter=',')[1:]
test_data  = np.genfromtxt('mnist_test.csv', delimiter=',')[1:]

train_images = train_data[:, 1:]
train_labels = train_data[:, 0]

test_images  = test_data[:, 1:]
test_labels  = test_data[:, 0]

class_names = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

train_images = train_images/255
test_images = test_images/255

train_images = train_images.reshape(60000, 28, 28)
test_images = test_images.reshape(10000, 28, 28)

# ---------- PART II: Making the model ----------
layers = [keras.layers.Flatten(input_shape=(28, 28)), 
          keras.layers.Dense(128, activation='relu'), 
          keras.layers.Dense(10, activation='softmax')]

model = keras.Sequential(layers)
model.compile(optimizer='adam', 
              loss='sparse_categorical_crossentropy', 
              metrics=['accuracy'])


model.fit(train_images, train_labels, epochs=1
model.save("network.h5")

以下是错误回溯信息:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-36-0e5ebf05c427> in <module>
      1 print('Saving Model...')
----> 2 model.save("network.h5")

~\Downloads\Anaconda\lib\site-packages\tensorflow_core\python\keras\engine\network.py in save(self, filepath, overwrite, include_optimizer, save_format, signatures, options)
   1006     """
   1007     save.save_model(self, filepath, overwrite, include_optimizer, save_format,
-> 1008                     signatures, options)
   1009 
   1010   def save_weights(self, filepath, overwrite=True, save_format=None):

~\Downloads\Anaconda\lib\site-packages\tensorflow_core\python\keras\saving\save.py in save_model(model, filepath, overwrite, include_optimizer, save_format, signatures, options)
     97 
     98   if (save_format == 'h5' or
---> 99       (h5py is not None and isinstance(filepath, h5py.File)) or
    100       os.path.splitext(filepath)[1] in _HDF5_EXTENSIONS):
    101     # TODO(b/130258301): add utility method for detecting model type.

AttributeError: module 'h5py' has no attribute 'File'

我的版本:

  1. tensorflow: 2.1.0
  2. keras: 2.2.4-tf
  3. h5py: 2.10.0
  4. Anaconda: 2019.10

非常感谢您的帮助。


你找到解决方案了吗?我不明白目前被接受的解决方案与你尝试过的有何不同。 - user3731622
4个回答

1

我通过卸载现有的h5py,然后使用conda重新安装来解决了这个问题。

$ conda install h5py

希望这对你也有用。 :D


1
实际上,这是不同库版本的问题。在使用TensorFlow时,我也遇到了同样的问题。从anaconda提示符中,您可以检查哪个版本的h5py与TensorFlow兼容。我尝试过多次卸载和重新安装,但最后,安装了一个兼容的h5py版本,问题得到了解决。可以在此处检查Conda提示符截图here

1
你可以看到问题已经从被接受的答案中解决了,但由于你正在尝试提供一个答案,它应该是通用的,而截图版本与问题中给出的版本不同。 - Amit Gupta

1
请尝试这个。它工作得很好。
from tensorflow.keras.models import load_model
model.save("model.h5")
print("Saved model to disk")
 
# load model
model = load_model('model.h5')

这似乎解决了问题,但我实际上不知道为什么。load_model函数和model.save函数有什么关系? - Lukas
1
这种方法被用来使用Keras保存和加载模型。如果你想使用另一种方法,也可以。更多细节请参考:https://machinelearningmastery.com/save-load-keras-deep-learning-models/ - muthu kumar

0

我在我的环境中通过将 h5py 模块降级到 3.1.0 版本解决了这个问题,这个版本兼容 TensorFlow 2.6。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接