1. 安装与环境配置
- 使用
pip install tensorflow
安装最新版本
- 推荐使用 Colab 在线环境实践
- 确保已安装 Python 3.7+ 和 GPU 支持(如需加速训练)
2. 核心概念
- 张量(Tensor):数据的基本载体,如
tf.constant([1,2,3])
- 计算图(Graph):操作(Operation)和张量组成的有向图
- 会话(Session):执行计算图的运行环境
3. 代码示例
import tensorflow as tf
# 创建张量
a = tf.constant(2)
b = tf.constant(3)
# 定义计算
c = tf.add(a, b)
# 运行会话
with tf.Session() as sess:
result = sess.run(c)
print("结果:", result) # 输出: 结果: 5
4. 扩展学习
5. 常见问题
- 如何在 CPU 上运行?
设置 tf.config.set_visible_devices([], 'GPU')
后重启会话
- 为什么出现内存不足错误?
可尝试使用 tf.keras.utils.get_custom_objects()
优化内存使用