尧图网络 高端网站定制 · 原创设计
免费咨询热线
400-888-6620
免费获取方案
石头剪刀布数据集迁移学习:MobileNetV2 微调实现 99% 验证准确率
基于MobileNetV2的石头剪刀布图像分类迁移学习实现99%验证准确率在计算机视觉任务中从头训练一个卷积神经网络往往需要大量数据和计算资源。本文将展示如何利用迁移学习技术通过微调预训练的MobileNetV2模型在石头剪刀布Rock-Paper-Scissors小数据集上实现99%以上的验证准确率。1. 环境准备与数据加载首先确保已安装必要的Python库!pip install tensorflow tensorflow-datasets matplotlib石头剪刀布数据集包含2520张训练图像和372张测试图像每类石头、剪刀、布样本数量均衡。我们可以直接从Google存储桶下载import tensorflow as tf import tensorflow_datasets as tfds import matplotlib.pyplot as plt # 加载数据集 (ds_train, ds_test), ds_info tfds.load( rock_paper_scissors, split[train, test], shuffle_filesTrue, as_supervisedTrue, with_infoTrue ) # 查看数据集信息 print(f训练集样本数: {ds_info.splits[train].num_examples}) print(f测试集样本数: {ds_info.splits[test].num_examples}) print(f类别数: {ds_info.features[label].num_classes})数据增强是防止小数据集过拟合的关键技术。我们定义以下增强管道def preprocess(image, label): # 统一图像尺寸为224x224MobileNetV2的默认输入尺寸 image tf.image.resize(image, [224, 224]) # 归一化到[-1,1]范围 image (image / 127.5) - 1 return image, label def augment(image, label): # 随机水平翻转 image tf.image.random_flip_left_right(image) # 随机旋转-15°到15° image tf.image.rot90(image, ktf.random.uniform(shape[], minval0, maxval4, dtypetf.int32)) # 随机亮度调整 image tf.image.random_brightness(image, max_delta0.2) return preprocess(image, label) # 应用数据增强到训练集 ds_train ds_train.map(augment, num_parallel_callstf.data.AUTOTUNE) ds_train ds_train.shuffle(1024).batch(32).prefetch(tf.data.AUTOTUNE) # 测试集只做预处理不做增强 ds_test ds_test.map(preprocess, num_parallel_callstf.data.AUTOTUNE) ds_test ds_test.batch(32).prefetch(tf.data.AUTOTUNE)2. MobileNetV2基础模型加载MobileNetV2是一个轻量级的深度卷积网络特别适合移动端和嵌入式设备。我们加载在ImageNet上预训练的权重base_model tf.keras.applications.MobileNetV2( input_shape(224, 224, 3), include_topFalse, weightsimagenet, poolingavg # 使用全局平均池化替代Flatten ) # 冻结基础模型的所有层 base_model.trainable False # 添加自定义分类头 model tf.keras.Sequential([ base_model, tf.keras.layers.Dropout(0.5), # 添加Dropout防止过拟合 tf.keras.layers.Dense(3, activationsoftmax) ]) model.compile( optimizertf.keras.optimizers.Adam(learning_rate0.001), losssparse_categorical_crossentropy, metrics[accuracy] ) model.summary()模型结构关键点输入尺寸224x224x3基础模型参数量1.4M全部冻结可训练参数量6K仅分类头3. 初始训练阶段我们先训练模型的顶层分类头同时保持基础模型冻结initial_epochs 10 history model.fit( ds_train, validation_datads_test, epochsinitial_epochs ) # 绘制训练曲线 def plot_learning_curves(history): plt.figure(figsize(12, 4)) plt.subplot(1, 2, 1) plt.plot(history.history[accuracy], labelTraining Accuracy) plt.plot(history.history[val_accuracy], labelValidation Accuracy) plt.title(Accuracy over Time) plt.legend() plt.subplot(1, 2, 2) plt.plot(history.history[loss], labelTraining Loss) plt.plot(history.history[val_loss], labelValidation Loss) plt.title(Loss over Time) plt.legend() plt.show() plot_learning_curves(history)典型结果训练准确率~98%验证准确率~95%4. 微调阶段解冻部分层为了进一步提升性能我们解冻基础模型的部分顶层并进行微调# 解冻基础模型的后20层 base_model.trainable True fine_tune_at len(base_model.layers) - 20 for layer in base_model.layers[:fine_tune_at]: layer.trainable False # 使用更小的学习率 model.compile( optimizertf.keras.optimizers.Adam(learning_rate0.0001), losssparse_categorical_crossentropy, metrics[accuracy] ) # 继续训练 fine_tune_epochs 10 total_epochs initial_epochs fine_tune_epochs history_fine model.fit( ds_train, initial_epochhistory.epoch[-1], epochstotal_epochs, validation_datads_test ) # 合并训练历史并绘制 acc history.history[accuracy] history_fine.history[accuracy] val_acc history.history[val_accuracy] history_fine.history[val_accuracy] loss history.history[loss] history_fine.history[loss] val_loss history.history[val_loss] history_fine.history[val_loss] plt.figure(figsize(12, 4)) plt.subplot(1, 2, 1) plt.plot(acc, labelTraining Accuracy) plt.plot(val_acc, labelValidation Accuracy) plt.axvline(len(history.history[accuracy]), linestyle--, colorgray) plt.title(Accuracy over Time) plt.legend() plt.subplot(1, 2, 2) plt.plot(loss, labelTraining Loss) plt.plot(val_loss, labelValidation Loss) plt.axvline(len(history.history[loss]), linestyle--, colorgray) plt.title(Loss over Time) plt.legend() plt.show()微调后典型结果训练准确率~99.5%验证准确率~99%5. 模型评估与部署最后评估模型性能并保存# 在测试集上评估 test_loss, test_acc model.evaluate(ds_test) print(f\n测试准确率: {test_acc:.2%}) # 保存模型 model.save(rps_mobilenetv2.h5) # 转换为TensorFlow Lite格式用于移动设备 converter tf.lite.TFLiteConverter.from_keras_model(model) tflite_model converter.convert() with open(rps_mobilenetv2.tflite, wb) as f: f.write(tflite_model)混淆矩阵分析可以帮助我们了解模型在不同类别上的表现import numpy as np from sklearn.metrics import confusion_matrix import seaborn as sns # 收集测试集所有预测 y_true [] y_pred [] for images, labels in ds_test.unbatch(): y_true.append(labels.numpy()) y_pred.append(np.argmax(model.predict(tf.expand_dims(images, axis0)))) # 计算混淆矩阵 cm confusion_matrix(y_true, y_pred) class_names [石头, 布, 剪刀] plt.figure(figsize(6, 6)) sns.heatmap(cm, annotTrue, fmtd, cmapBlues, xticklabelsclass_names, yticklabelsclass_names) plt.xlabel(预测标签) plt.ylabel(真实标签) plt.title(混淆矩阵) plt.show()常见优化技巧尝试不同的解冻层数通常解冻最后10-30层使用学习率衰减策略增加数据增强的多样性尝试不同的优化器如RMSprop在实际部署中可以使用以下代码进行单张图像预测def predict_image(image_path): img tf.keras.preprocessing.image.load_img(image_path, target_size(224, 224)) img_array tf.keras.preprocessing.image.img_to_array(img) img_array (img_array / 127.5) - 1 # 与训练相同的归一化 img_array tf.expand_dims(img_array, 0) # 添加批次维度 predictions model.predict(img_array) score tf.nn.softmax(predictions[0]) class_names [石头, 布, 剪刀] print( 这张图像最可能是 {}置信度 {:.2f}% .format(class_names[np.argmax(score)], 100 * np.max(score)) )
RELATED

相关推荐

Transformer 与 CNN 参数初始化对比:4个关键差异与 Xavier/He 选择指南

Transformer 与 CNN 参数初始化对比:4个关键差异与 Xavier/He 选择指南

Transformer 与 CNN 参数初始化对比:4个关键差异与 Xavier/He 选择指南在深度学习的模型设计中,参数初始化看似是一个微小的技术细节,实则对模型的收敛速度和最终性能有着决定性影响。Transformer 和 CNN 作为当前两大主流架构,其…

📅 2026/7/29 5:21:45
PANNs Wavegram-Logmel-CNN 解析:双输入特征如何将mAP提升至0.439

PANNs Wavegram-Logmel-CNN 解析:双输入特征如何将mAP提升至0.439

Wavegram-Logmel-CNN架构解析:双输入特征如何突破音频分类性能瓶颈音频模式识别领域近年来迎来爆发式增长,从智能家居的声控交互到工业设备的异常检测,高质量的声音分类技术正成为AI落地的关键支柱。传统基于单一特征输入的神经网络模型在复杂…

📅 2026/9/8 17:16:28
分布式日志关联查询:同一请求在多服务间别靠时间戳猜

分布式日志关联查询:同一请求在多服务间别靠时间戳猜

分布式日志关联查询:同一请求在多服务间别靠时间戳猜 一、你找到了 A 服务的错误日志,但 B 服务那里有 500 条日志 排查跨服务问题时的典型场景。用户在订单页面报错,你查到订单服务有异常日志。顺着时间戳去下游支付服务查日志。同一秒有 …

📅 2026/9/10 19:11:29
MORE NEWS

更多资讯

📰

CPython 自由线程构建 QSBR 槽位泄漏修复解析:从 gh-issue-155363 看线程状态创建失败路径的回收机制

CPython 自由线程构建 QSBR 槽位泄漏修复解析:从 gh-issue-155363 看线程状态创建失败路径的回收机制 【免费下载链接】cpython The Python programming language 项目地址: https://gitcode.com/GitHub_Trending/cp/cpython 导读 本文围绕 CPython 仓库中一…

📰

六款AI编程助手全栈实测:最终留下Claude Code和Cursor

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

📰

OMP 中的 OpenAI Harmony 方言:gpt-oss 函数调用线格式与流式解析实战

OMP 中的 OpenAI Harmony 方言:gpt-oss 函数调用线格式与流式解析实战 【免费下载链接】oh-my-pi ⌥ Coding agent with the IDE wired in 项目地址: https://gitcode.com/GitHub_Trending/oh/oh-my-pi Harmony 是 OpenAI 为其开源权重模型 gpt-oss 系列&…

📰

MCU如何通过I²C控制光模块并实现亚微秒时间戳

1. 光模块从来不是MCU的“舒适区”,但这次真被盯上了“MCU盯上光模块了!”——看到这个标题,我第一反应是笑出声。不是因为荒谬,而是太熟悉这种“跨界突袭”的节奏。干了十多年嵌入式开发,从8051到ARM Cortex-M7&#…

📰

Harbor 项目创建权限管控:从配置文件到 API 校验的完整实践

Harbor 项目创建权限管控:从配置文件到 API 校验的完整实践 【免费下载链接】harbor An open source trusted cloud native registry project that stores, signs, and scans content. 项目地址: https://gitcode.com/GitHub_Trending/ha/harbor 导读 Harbo…

📰

标定板分辨率全解析:高精度视觉系统的核心选型与验证

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

TODAY

今日更新

THIS WEEK

本周精选

THIS MONTH

本月热门

读完文章,想聊聊您的网站?

告诉我们您的行业与需求,资深顾问一对一梳理方案与报价,全程免费。

📞 💬