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()

执行结果

相关推荐
阿里云大数据AI技术2 分钟前
阿里云 EMR AI 助手正式发布:从问答工具到全栈智能运维助手
运维·人工智能
Larcher1 小时前
从零搭建 MCP 服务——让 AI 拥有无限扩展能力
人工智能·程序员
zzzzzz3101 小时前
你的 AI 写的 React 烂透了?这个 8000+ Star 的开源工具能揪出 90% 的「Agent 屎山」
人工智能
小星AI1 小时前
MCP协议超详细教程,从入门到实战
人工智能
小星AI1 小时前
Kimi Code CLI 超详细教程,附源码
人工智能·agent
牧艺2 小时前
Cursor Rules / Skills 分层设计:让 Agent 像「团队新同事」
前端·人工智能·cursor
shepherd1112 小时前
一文带你掌握 LLM、Token、Context、Prompt、RAG、MCP、Skill、Agent 等 AI 核心概念
人工智能·后端·ai编程
小林ixn2 小时前
MCP 保姆级入门指南:AI 的“万能充电口”到底怎么玩?
人工智能
转转技术团队4 小时前
没有测试的核心代码,怎么交给 AI 重构
人工智能