1. 安装 TensorFlow
- 官方文档 📚 提供多种安装方式(CPU/GPU版本)
- 使用 pip 安装:
pip install tensorflow
- 验证安装:运行
import tensorflow as tf; print(tf.__version__)
2. 基本概念
- 张量(Tensor):数据的基本载体,如
tf.constant([1,2,3])
- 计算图(Graph):定义运算流程的可视化结构
- 会话(Session):执行计算图的运行环境
3. Hello World 示例
import tensorflow as tf
# 创建常量
hello = tf.constant("Hello, TensorFlow!")
# 启动会话
with tf.Session() as sess:
print(sess.run(hello))
4. 数据处理
- 使用
tf.data.Dataset
构建数据流水线
- 支持从文件、数组、数据库等加载数据
- 可通过
.map()
、.batch()
等方法进行预处理
5. 模型训练
- 选择模型架构:
tf.keras.models.Sequential()
- 添加层:
model.add(tf.keras.layers.Dense(units=64, activation='relu'))
- 编译模型:
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy')
- 训练模型:
model.fit(x_train, y_train, epochs=5)
6. 扩展阅读