Tensorflow入门之 Hello World

Tensorflow入门之 Hello World

简介

Tensorflow 是 Google 开源的深度学习框架,来自于 Google Brain 研究项目,在 Google 第一代分布式机器学习框架 DistBelief 的基础上发展起来。

Tensorflow 的官方网址 http://www.tensorflow.org

Tensorflow 的 GitHub 网址 https://github.com/tensorflow/tensorflow

Hello World

启动 main 方法,若成功输出b'Hello, Tensorflow!',则表明Tensorflow安装成功。

python 复制代码
import tensorflow as tf


def demo():

    hello = tf.constant('Hello, Tensorflow!')
    sess = tf.Session()
    print(sess.run(hello))
    sess.close()


if __name__ == '__main__':
    demo()

报错信息

jsx 复制代码
Traceback (most recent call last):
  File "D:/Greenarrow/Workspace/FaceLogin/api/demo.py", line 13, in <module>
    demo()
  File "D:/Greenarrow/Workspace/FaceLogin/api/demo.py", line 7, in demo
    sess = tf.Session()
AttributeError: module 'tensorflow' has no attribute 'Session'

解决方案

  • Tensorflow 版本导致
  • 禁用TF2.x中的eager,否则会报错
  • tf.Session() 改为 tf.compat.v1.Session()

完整代码

python 复制代码
import tensorflow as tf


def demo():

    # 禁用TF2.x中的eager
    tf.compat.v1.disable_eager_execution()
    hello = tf.constant('Hello, Tensorflow!')
    sess = tf.compat.v1.Session()
    print(sess.run(hello))
    sess.close()


if __name__ == '__main__':
    demo()

执行结果

相关推荐
HIT_Weston1 小时前
45、【Agent】【OpenCode】本地代理分析(请求&接收回调)
人工智能·agent·opencode
知行合一。。。1 小时前
Python--04--数据容器(总结)
开发语言·python
架构师老Y1 小时前
008、容器化部署:Docker与Python应用打包
python·容器·架构
逻辑君1 小时前
认知神经科学研究报告【20260010】
人工智能·深度学习·神经网络·机器学习
星河耀银海1 小时前
远控体验分享:安全与实用性参考
人工智能·安全·微服务
lifewange1 小时前
pytest-类中测试方法、多文件批量执行
开发语言·python·pytest
企业架构师老王2 小时前
2026企业架构演进:科普Agent(龙虾)如何从“极客玩具”走向实在Agent规模化落地?
人工智能·ai·架构
GreenTea2 小时前
一文搞懂Harness Engineering与Meta-Harness
前端·人工智能·后端
pluvium272 小时前
记对 xonsh shell 的使用, 脚本编写, 迁移及调优
linux·python·shell·xonsh
鬼先生_sir2 小时前
Spring AI Alibaba 1.1.2.2 完整知识点库
人工智能·ai·agent·源码解析·springai