TensorFlow 2 深度学习:图像分类与序列模型
FreeGuideOnline
最新
2026-06-12
1. 环境准备与项目概览
在开始实战之前,我们需要搭建好 TensorFlow 2 的编程环境。本教程使用 Python 3.8+ 和 TensorFlow 2.x,所有代码均在 Jupyter Notebook 或普通 Python 脚本中可运行。
1.1 安装依赖
pip install tensorflow matplotlib numpy pandas scikit-learn
验证安装版本:
import tensorflow as tf
print(tf.__version__)
确保输出 2.x 版本号。
1.2 项目结构说明
本教程将带领你完成两个核心深度学习任务:
- 任务一:图像分类 – 使用 CNN 对 CIFAR-10 数据集进行图片识别。
- 任务二:序列建模 – 利用 LSTM 对 IMDB 电影评论进行情感分析。
每个任务都遵循统一的机器学习流程:数据准备 → 模型构建 → 训练 → 评估 → 预测。
2. 图像分类实战:CIFAR-10 识别
CIFAR-10 包含 10 类 32×32 彩色图片,共 60,000 张,是入门图像分类的经典数据集。
2.1 数据加载与预处理
import tensorflow as tf
from tensorflow.keras import datasets, layers, models
# 加载数据
(x_train, y_train), (x_test, y_test) = datasets.cifar10.load_data()
# 归一化到 [0,1]
x_train = x_train.astype('float32') / 255.0
x_test = x_test.astype('float32') / 255.0
# 标签转为 one-hot 编码
y_train = tf.keras.utils.to_categorical(y_train, 10)
y_test = tf.keras.utils.to_categorical(y_test, 10)
print(f'训练集形状: {x_train.shape}')
print(f'测试集形状: {x_test.shape}')
2.2 构建 CNN 模型
一个典型的卷积神经网络包含卷积层、池化层和全连接层。我们设计一个轻量但有效的模型:
model = models.Sequential([
layers.Conv2D(32, (3,3), activation='relu', padding='same', input_shape=(32,32,3)),
layers.Conv2D(32, (3,3), activation='relu', padding='same'),
layers.MaxPooling2D((2,2)),
layers.Dropout(0.25),
layers.Conv2D(64, (3,3), activation='relu', padding='same'),
layers.Conv2D(64, (3,3), activation='relu', padding='same'),
layers.MaxPooling2D((2,2)),
layers.Dropout(0.25),
layers.Flatten(),
layers.Dense(256, activation='relu'),
layers.Dropout(0.5),
layers.Dense(10, activation='softmax')
])
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
model.summary()
2.3 训练与可视化
使用 EarlyStopping 防止过拟合,并记录训练历史以便画图。
from tensorflow.keras.callbacks import EarlyStopping
import matplotlib.pyplot as plt
early_stop = EarlyStopping(monitor='val_loss', patience=5, restore_best_weights=True)
history = model.fit(
x_train, y_train,
batch_size=64,
epochs=30,
validation_split=0.2,
callbacks=[early_stop]
)
# 绘制准确率与损失曲线
def plot_history(history):
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs = range(1, len(acc)+1)
plt.figure(figsize=(12,4))
plt.subplot(1,2,1)
plt.plot(epochs, acc, 'bo-', label='Training acc')
plt.plot(epochs, val_acc, 'r*-', label='Validation acc')
plt.title('Training and Validation Accuracy')
plt.legend()
plt.subplot(1,2,2)
plt.plot(epochs, loss, 'bo-', label='Training loss')
plt.plot(epochs, val_loss, 'r*-', label='Validation loss')
plt.title('Training and Validation Loss')
plt.legend()
plt.show()
plot_history(history)
2.4 模型评估
在测试集上查看最终性能:
test_loss, test_acc = model.evaluate(x_test, y_test, verbose=2)
print(f'Test accuracy: {test_acc:.4f}')
你应该能获得大约 80% 以上的准确率(增加 epochs 或使用数据增强可进一步提升)。
3. 序列模型实战:IMDB 情感分析
IMDB 电影评论数据集包含 25,000 条训练评论和 25,000 条测试评论,标签为正面(1)和负面(0)。我们将使用词嵌入 + LSTM 构建分类器。
3.1 数据加载与预处理
from tensorflow.keras.datasets import imdb
from tensorflow.keras.preprocessing.sequence import pad_sequences
max_features = 10000 # 词汇表大小
maxlen = 200 # 每条评论截断或填充到的长度
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=max_features)
# 填充序列,使得长度一致
x_train = pad_sequences(x_train, maxlen=maxlen)
x_test = pad_sequences(x_test, maxlen=maxlen)
print(f'训练集形状: {x_train.shape}')
print(f'测试集形状: {x_test.shape}')
3.2 构建 LSTM 模型
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Embedding, LSTM, Dense, Dropout
model = Sequential([
Embedding(max_features, 128, input_length=maxlen),
LSTM(64, dropout=0.2, recurrent_dropout=0.2),
Dense(1, activation='sigmoid')
])
model.compile(optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy'])
model.summary()
3.3 训练与验证
同样使用早停法和验证集监控训练过程。
early_stop = EarlyStopping(monitor='val_loss', patience=3, restore_best_weights=True)
history = model.fit(
x_train, y_train,
batch_size=128,
epochs=10,
validation_split=0.2,
callbacks=[early_stop]
)
plot_history(history) # 复用上节的绘图函数
3.4 模型评估
test_loss, test_acc = model.evaluate(x_test, y_test, verbose=2)
print(f'Test accuracy: {test_acc:.4f}')
在 IMDB 数据集上,该模型通常能达到 87% 左右的准确率。
3.5 使用模型进行预测
你可以用训练好的模型预测新的文本:
word_index = imdb.get_word_index()
reverse_word_index = dict([(value, key) for (key, value) in word_index.items()])
def decode_review(text_sequence):
return ' '.join([reverse_word_index.get(i-3, '?') for i in text_sequence])
# 示例:预测测试集第一条评论
sample_review = x_test[0].reshape(1, maxlen)
pred = model.predict(sample_review)[0][0]
label = 'Positive' if pred > 0.5 else 'Negative'
print(f'Prediction: {label} (confidence {pred:.4f})')
print('Original review (decoded):', decode_review(x_test[0][:50]), '...')
4. 总结与下一步
恭喜你完成了图像分类和序列建模两个核心实战项目!通过本教程你掌握了:
- 使用 Conv2D 和 MaxPooling 构建 CNN 处理图像
- 利用 Embedding + LSTM 处理变长文本序列
- 训练过程中的早停、dropout 等正则化技巧
- 可视化训练曲线,评估模型性能
想要进一步提升模型表现,可以尝试以下方向:
- 图像任务:加入数据增强(
ImageDataGenerator)、迁移学习(VGG16 等预训练模型) - 序列任务:尝试双向 LSTM、GRU、Transformer 或使用预训练词向量(GloVe)
- 部署模型:使用 TensorFlow Serving 或转换为 TensorFlow Lite 部署到移动端
深度学习的世界广阔而有趣,持续动手实践是进步的最佳方式。现在,去调整参数、尝试自己的数据集,开始你的下一个项目吧!