AttributeError: module ‘tensorflow.keras.utils‘ has no attribute image_dataset_from_directory——解决方法

在树莓派中,为python3.7搭建好tensorflow2.4(搭建的简要过程)的环境之后,跑代码时出现如题的问题
首先,利用:

import tensorflow as tf
print(tf.keras.utils.__file__)

来查找tf.keras.utils模块的__init__.py文件的路径:

AttributeError: module ‘tensorflow.keras.utils‘ has no attribute image_dataset_from_directory——解决方法

然后,打开此 tensorflow/keras/utils/__init__.py文件,发现tensorflow.keras.utils中的函数和类都是从tensorflow.python.keras中import过来的,之后与windows下tensorflow 2.7的__init__.py进行对比。

windows的__init__.py文件如下:

AttributeError: module ‘tensorflow.keras.utils‘ has no attribute image_dataset_from_directory——解决方法
在树莓派上按照:
from tensorflow.python.keras.preprocessing.image_dataset import image_dataset_from_directory

的路径找到了image_dataset_from_directory:

AttributeError: module ‘tensorflow.keras.utils‘ has no attribute image_dataset_from_directory——解决方法
说明树莓派的tf是有这个函数的,只是 tensorflow/keras/utils/__init__.py文件没有import这个函数,所以在运行时没有在__init__.py文件中找到此函数而报错。

可以看到, tensorflow/keras/utils/__init__.py文件是自动生成的,不一定完整:

AttributeError: module ‘tensorflow.keras.utils‘ has no attribute image_dataset_from_directory——解决方法
所以在其中添加上对image_dataset_from_directory函数的引用即可

之后在测试代码中添加:

from tensorflow.python.keras.preprocessing.image_dataset import image_dataset_from_directory

或者,直接在 tensorflow/keras/utils/__init__.py文件中添加上:

from tensorflow.python.keras.preprocessing.image_dataset import image_dataset_from_directory

之后,就可以在代码中正常使用 tf.keras.utils.image_dataset_from_directory

注意:以这种方式查看源代码可能会解决类似的问题。

[En]

Note: similar problems may be solved by looking at the source code in this way.

比如,相同版本的tensorflow的tf.lite的下一级有funcA这个函数,但是在新环境中出现了AttributeError,那可以先:

import tensorflow as tf
print(tf.lite.__file__)

看一下tf.lite的__init__.py文件的路径:

AttributeError: module ‘tensorflow.keras.utils‘ has no attribute image_dataset_from_directory——解决方法
然后类似上述方法,与能正常引用funcA函数的tensorflow的__init__.py进行对比,在新环境的__init__.py文件中添加上funcA函数相关的引用就可以了

Original: https://blog.csdn.net/weixin_43698781/article/details/123518877
Author: alphanoblaker
Title: AttributeError: module ‘tensorflow.keras.utils‘ has no attribute image_dataset_from_directory——解决方法

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/496478/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球