当前位置: 代码网 > it编程>前端脚本>Python > AttributeError: module ‘tensorflow‘ has no attribute ‘placeholder‘解决办法

AttributeError: module ‘tensorflow‘ has no attribute ‘placeholder‘解决办法

2024年08月01日 Python 我要评论
TensorFlow 2.x 相较于 1.x 版本有着显著的变化,其中最重要的是引入了即时执行(Eager Execution)和函数式编程模型,这使得 TensorFlow 的使用变得更加直观和Pythonic。在 TensorFlow 2.x 中,许多 TensorFlow 1.x 的概念(比如图计算、会话等)都被简化或重新设计了。注意,在 TensorFlow 2.x 中使用兼容模式可能会限制你使用 TensorFlow 2.x 的新特性。已经被弃用,取而代之的是使用。

在这里插入图片描述

1.报错代码

self.inputs_base_structure_left = tf.placeholder(dtype=tf.float32, shape=[none, 2048, 2], name="inputs_left")  # initial a inputs to siamese_network

2. 报错原因

attributeerror: module 'tensorflow' has no attribute 'placeholder' 这个错误发生的原因是因为在较新版本的 tensorflow 中,tf.placeholder 已经被弃用,取而代之的是使用 tf.compat.v1.placeholder 或者直接使用 tensorflow 2.x 中的新特性,比如 tf.functiontf.tensor 来定义输入。

tensorflow 2.x 相较于 1.x 版本有着显著的变化,其中最重要的是引入了即时执行(eager execution)和函数式编程模型,这使得 tensorflow 的使用变得更加直观和pythonic。在 tensorflow 2.x 中,许多 tensorflow 1.x 的概念(比如图计算、会话等)都被简化或重新设计了。

3. 解决办法

  1. 使用 tensorflow 1.x 兼容模式
    在 tensorflow 2.x 中,你可以通过启用 tensorflow 1.x 兼容模式来使用 tf.placeholder。在代码的开始处添加以下行:

    import tensorflow as tf
    tf.compat.v1.disable_eager_execution()
    

    然后,你可以使用 tf.compat.v1.placeholder 来创建占位符:

    x = tf.compat.v1.placeholder(tf.float32, shape=[none, 784])
    y = tf.compat.v1.placeholder(tf.float32, shape=[none, 10])
    

    注意,在 tensorflow 2.x 中使用兼容模式可能会限制你使用 tensorflow 2.x 的新特性。

  2. 使用 tensorflow 1.x 版本:(我的方法
    如果你不打算将代码迁移到 tensorflow 2.x,你可以考虑安装并使用 tensorflow 1.x 版本。但请注意,tensorflow 1.x 不再得到官方的积极支持,且存在安全隐患。

我开始使用tf.compat.v1.placeholder后来又出现了其他问题,我直接弃用了这种方法,然后安装了tensorflow1.15版本,直接完美运行代码

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com