01. TensorFlow 简介
TensorFlow 是 Google 开发的开源机器学习框架,广泛应用于深度学习。
TensorFlow 的特点:
- 张量(Tensor)计算
- 自动微分(GradientTape)
- GPU/TPU 加速
- 生产部署工具(TensorFlow Serving、Lite)
- 丰富的预训练模型
python
import tensorflow as tf
# 张量基础
tensor = tf.constant([[1, 2], [3, 4]])
print("形状:", tensor.shape) # (2, 2)
print("数据类型:", tensor.dtype) # int32
# 张量运算
a = tf.constant([1, 2, 3])
b = tf.constant([4, 5, 6])
c = a + b # [5, 7, 9]
d = tf.multiply(a, b) # [4, 10, 18]
# 自动微分
x = tf.Variable(3.0)
with tf.GradientTape() as tape:
y = x ** 2 + 2 * x + 1
dy_dx = tape.gradient(y, x)
print("dy/dx =", dy_dx.numpy()) # 8.002. Keras 模型构建
Keras 是 TensorFlow 的高级 API,提供简洁的模型构建方式。
两种模型构建方式:
- Sequential:层栈式模型
- Functional API:支持多输入输出、共享层
- Model Subclassing:完全自定义
python
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
# Sequential 模型
model = keras.Sequential([
layers.Dense(64, activation='relu', input_shape=(784,)),
layers.Dropout(0.2),
layers.Dense(32, activation='relu'),
layers.Dense(10, activation='softmax')
])
model.summary()
# Functional API
inputs = keras.Input(shape=(784,))
x = layers.Dense(64, activation='relu')(inputs)
x = layers.Dropout(0.2)(x)
x = layers.Dense(32, activation='relu')(x)
outputs = layers.Dense(10, activation='softmax')(x)
model = keras.Model(inputs=inputs, outputs=outputs)
# 编译模型
model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)03. 图像分类实战
使用 TensorFlow 构建图像分类模型。
工作流程:
- 数据加载和预处理
- 模型构建
- 训练和验证
- 预测和评估
python
import tensorflow as tf
from tensorflow.keras import datasets, layers, models
# 加载 CIFAR-10 数据集
(train_images, train_labels), (test_images, test_labels) = \
datasets.cifar10.load_data()
# 归一化
train_images, test_images = train_images / 255.0, test_images / 255.0
# 构建 CNN 模型
model = models.Sequential([
layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64, (3, 3), activation='relu'),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64, (3, 3), activation='relu'),
layers.Flatten(),
layers.Dense(64, activation='relu'),
layers.Dense(10, activation='softmax')
])
# 编译
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# 训练
history = model.fit(train_images, train_labels, epochs=10,
validation_data=(test_images, test_labels))
# 评估
test_loss, test_acc = model.evaluate(test_images, test_labels)
print("测试准确率:", round(test_acc, 4))知识测验
第 1/5 题正确 0
TensorFlow 中 GradientTape 的作用是什么?
下一节
下一节 PyTorch 入门