当前位置: 首页 > news >正文

基于tensorflow使用VGG16实现猫狗识别

import tensorflow as tf
import numpy as np
from tensorflow.keras import layers, models, optimizers
from tensorflow.keras.preprocessing.image import ImageDataGenerator# 定义 VGG16 模型
class VGG16(tf.keras.Model):def __init__(self, num_classes=2):super(VGG16, self).__init__()self.features = models.Sequential([layers.Conv2D(64, (3, 3), padding='same', activation='relu', input_shape=(224, 224, 3)),layers.MaxPooling2D((2, 2), strides=(2, 2)),layers.Conv2D(128, (3, 3), padding='same', activation='relu'),layers.MaxPooling2D((2, 2), strides=(2, 2)),layers.Conv2D(256, (3, 3), padding='same', activation='relu'),layers.Conv2D(256, (3, 3), padding='same', activation='relu'),layers.MaxPooling2D((2, 2), strides=(2, 2)),layers.Conv2D(512, (3, 3), padding='same', activation='relu'),layers.Conv2D(512, (3, 3), padding='same', activation='relu'),layers.MaxPooling2D((2, 2), strides=(2, 2)),layers.Conv2D(512, (3, 3), padding='same', activation='relu'),layers.Conv2D(512, (3, 3), padding='same', activation='relu'),layers.MaxPooling2D((2, 2), strides=(2, 2)),])self.classifier = models.Sequential([layers.Flatten(),layers.Dense(4096, activation='relu'),layers.Dropout(0.5),layers.Dense(4096, activation='relu'),layers.Dropout(0.5),layers.Dense(num_classes, activation='softmax'),])def call(self, x):x = self.features(x)x = self.classifier(x)return x# 使用 ImageDataGenerator 加载并预处理数据集
data_dir = 'data'
input_shape = (224, 224)
batch_size = 4train_datagen = ImageDataGenerator(rescale=1.0/255,shear_range=0.2,zoom_range=0.2,horizontal_flip=True
)
val_datagen = ImageDataGenerator(rescale=1.0/255)train_gen = train_datagen.flow_from_directory(directory=f'{data_dir}/train',target_size=input_shape,batch_size=batch_size,class_mode='binary'
)val_gen = val_datagen.flow_from_directory(directory=f'{data_dir}/validation',target_size=input_shape,batch_size=batch_size,class_mode='binary'
)# 初始化模型、优化器和损失函数
model = VGG16(num_classes=2)
# 构建模型结构(明确指定输入形状)
model.build(input_shape=(None, 224, 224, 3))  # None 表示动态批次大小# 查看模型结构
model.summary()
model.compile(optimizer=optimizers.Adam(learning_rate=0.0001),loss='sparse_categorical_crossentropy',metrics=['accuracy'])# 训练循环
epochs = 20
steps_per_epoch = train_gen.samples // batch_size
validation_steps = val_gen.samples // batch_sizefor epoch in range(epochs):print(f"=========== Epoch {epoch + 1} ==============")history = model.fit(train_gen,steps_per_epoch=steps_per_epoch,validation_data=val_gen,validation_steps=validation_steps,epochs=1)train_loss = history.history['loss'][0]val_loss = history.history['val_loss'][0]val_accuracy = history.history['val_accuracy'][0]print(f"训练集上的损失:{train_loss}")print(f"验证集上的损失:{val_loss}")print(f"验证集上的精度:{val_accuracy:.1%}")# 保存模型model.save_weights(f"Adogandcat_epoch_{epoch + 1}.h5")print("模型权重已保存。")#预测部分
# 定义和加载 VGG16 模型
vgg16 = VGG16(num_classes=2)
vgg16.build(input_shape=(None, 224, 224, 3))
vgg16.load_weights('Adogandcat_epoch_20.h5')  # 替换为训练好的 VGG16 权重路径# 加载和预处理图像
def load_and_preprocess_image(image_path, target_size=(224, 224)):img = load_img(image_path, target_size=target_size)  # 加载图像并调整大小img_array = img_to_array(img)  # 转换为 NumPy 数组img_array = np.expand_dims(img_array, axis=0)  # 添加批次维度img_array = preprocess_input(img_array)  # VGG16 所需的标准化return img, img_array# 预测和显示图像
def predict_and_display(image_path, model, model_name):# 加载图像original_img, processed_img = load_and_preprocess_image(image_path)# 预测类别predictions = model(processed_img, training=False)predicted_class = np.argmax(predictions, axis=1)[0]confidence = predictions[0][predicted_class]# 显示结果plt.figure(figsize=(6, 6))plt.imshow(original_img)plt.axis('off')plt.title(f"Model: {model_name}\nPredicted Class: {predicted_class}\nConfidence: {confidence:.2f}")plt.show()# 测试图像路径
image_path = 'data/test/1.jpg'  # 替换为实际图像路径# 使用 CustomCNN 预测
predict_and_display(image_path, custom_cnn, "Custom CNN")# 使用 VGG16 预测
predict_and_display(image_path, vgg16, "VGG16")

训练结果:

运行时间:46 mins.

Found 18750 images belonging to 2 classes.

Found 6250 images belonging to 2 classes.

2024-11-22 00:51:58.211251: I tensorflow/core/platform/cpu_feature_guard.cc:142] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations:  AVX2 FMA

To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.

2024-11-22 00:51:58.612873: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1510] Created device /job:localhost/replica:0/task:0/device:GPU:0 with 38404 MB memory:  -> device: 0, name: NVIDIA A100-SXM4-40GB, pci bus id: 0000:4b:00.0, compute capability: 8.0

=========== Epoch 1 ==============

4687/4687 [==============================] - 140s 29ms/step - loss: 0.6943 - accuracy: 0.5031 - val_loss: 0.6932 - val_accuracy: 0.5010

训练集上的损失:0.6943416595458984

验证集上的损失:0.6932020783424377

验证集上的精度:50.1%

模型已保存。

=========== Epoch 2 ==============

4687/4687 [==============================] - 138s 29ms/step - loss: 0.6843 - accuracy: 0.5500 - val_loss: 0.6604 - val_accuracy: 0.6079

训练集上的损失:0.6842659711837769

验证集上的损失:0.660356879234314

验证集上的精度:60.8%

模型已保存。

=========== Epoch 3 ==============

4687/4687 [==============================] - 138s 29ms/step - loss: 0.6018 - accuracy: 0.6783 - val_loss: 0.4973 - val_accuracy: 0.7553

训练集上的损失:0.6018291711807251

验证集上的损失:0.4972682297229767

验证集上的精度:75.5%

模型已保存。

=========== Epoch 4 ==============

4687/4687 [==============================] - 139s 30ms/step - loss: 0.4743 - accuracy: 0.7762 - val_loss: 0.4171 - val_accuracy: 0.8156

训练集上的损失:0.4742658734321594

验证集上的损失:0.4170766770839691

验证集上的精度:81.6%

模型已保存。

=========== Epoch 5 ==============

4687/4687 [==============================] - 138s 29ms/step - loss: 0.3851 - accuracy: 0.8273 - val_loss: 0.3572 - val_accuracy: 0.8489

训练集上的损失:0.3850820064544678

验证集上的损失:0.3571555018424988

验证集上的精度:84.9%

模型已保存。

=========== Epoch 6 ==============

4687/4687 [==============================] - 138s 29ms/step - loss: 0.3096 - accuracy: 0.8676 - val_loss: 0.2901 - val_accuracy: 0.8841

训练集上的损失:0.30961713194847107

验证集上的损失:0.29008445143699646

验证集上的精度:88.4%

模型已保存。

=========== Epoch 7 ==============

4687/4687 [==============================] - 139s 30ms/step - loss: 0.2486 - accuracy: 0.8966 - val_loss: 0.2143 - val_accuracy: 0.9088

训练集上的损失:0.2486010491847992

验证集上的损失:0.2143394649028778

验证集上的精度:90.9%

模型已保存。

=========== Epoch 8 ==============

4687/4687 [==============================] - 139s 30ms/step - loss: 0.2155 - accuracy: 0.9101 - val_loss: 0.1907 - val_accuracy: 0.9205

训练集上的损失:0.2155471295118332

验证集上的损失:0.1906772404909134

验证集上的精度:92.0%

模型已保存。

=========== Epoch 9 ==============

4687/4687 [==============================] - 139s 30ms/step - loss: 0.1929 - accuracy: 0.9192 - val_loss: 0.1902 - val_accuracy: 0.9214

训练集上的损失:0.19291609525680542

验证集上的损失:0.19024263322353363

验证集上的精度:92.1%

模型已保存。

=========== Epoch 10 ==============

4687/4687 [==============================] - 143s 30ms/step - loss: 0.1751 - accuracy: 0.9284 - val_loss: 0.1607 - val_accuracy: 0.9337

训练集上的损失:0.17511127889156342

验证集上的损失:0.1606709510087967

验证集上的精度:93.4%

模型已保存。

=========== Epoch 11 ==============

4687/4687 [==============================] - 138s 29ms/step - loss: 0.1559 - accuracy: 0.9391 - val_loss: 0.1388 - val_accuracy: 0.9416

训练集上的损失:0.155866801738739

验证集上的损失:0.13884252309799194

验证集上的精度:94.2%

模型已保存。

=========== Epoch 12 ==============

4687/4687 [==============================] - 137s 29ms/step - loss: 0.1457 - accuracy: 0.9401 - val_loss: 0.1550 - val_accuracy: 0.9470

训练集上的损失:0.14570224285125732

验证集上的损失:0.15503031015396118

验证集上的精度:94.7%

模型已保存。

=========== Epoch 13 ==============

4687/4687 [==============================] - 138s 30ms/step - loss: 0.1359 - accuracy: 0.9451 - val_loss: 0.1201 - val_accuracy: 0.9520

训练集上的损失:0.1359049379825592

验证集上的损失:0.12010601162910461

验证集上的精度:95.2%

模型已保存。

=========== Epoch 14 ==============

4687/4687 [==============================] - 138s 30ms/step - loss: 0.1293 - accuracy: 0.9489 - val_loss: 0.1366 - val_accuracy: 0.9486

训练集上的损失:0.12929560244083405

验证集上的损失:0.13661223649978638

验证集上的精度:94.9%

模型已保存。

=========== Epoch 15 ==============

4687/4687 [==============================] - 139s 30ms/step - loss: 0.1206 - accuracy: 0.9516 - val_loss: 0.1472 - val_accuracy: 0.9478

训练集上的损失:0.12062755972146988

验证集上的损失:0.1471676379442215

验证集上的精度:94.8%

模型已保存。

=========== Epoch 16 ==============

4687/4687 [==============================] - 137s 29ms/step - loss: 0.1174 - accuracy: 0.9544 - val_loss: 0.1282 - val_accuracy: 0.9475

训练集上的损失:0.11741997301578522

验证集上的损失:0.1282137632369995

验证集上的精度:94.8%

模型已保存。

=========== Epoch 17 ==============

4687/4687 [==============================] - 138s 29ms/step - loss: 0.1139 - accuracy: 0.9552 - val_loss: 0.1264 - val_accuracy: 0.9563

训练集上的损失:0.11387941241264343

验证集上的损失:0.12638334929943085

验证集上的精度:95.6%

模型已保存。

=========== Epoch 18 ==============

4687/4687 [==============================] - 138s 29ms/step - loss: 0.1123 - accuracy: 0.9557 - val_loss: 0.1192 - val_accuracy: 0.9585

训练集上的损失:0.11233851313591003

验证集上的损失:0.11923010647296906

验证集上的精度:95.9%

模型已保存。

=========== Epoch 19 ==============

4687/4687 [==============================] - 138s 29ms/step - loss: 0.1124 - accuracy: 0.9579 - val_loss: 0.1174 - val_accuracy: 0.9534

训练集上的损失:0.11243574321269989

验证集上的损失:0.11737789213657379

验证集上的精度:95.3%

模型已保存。

=========== Epoch 20 ==============

4687/4687 [==============================] - 150s 32ms/step - loss: 0.0986 - accuracy: 0.9616 - val_loss: 0.1180 - val_accuracy: 0.9539

训练集上的损失:0.09860984236001968

验证集上的损失:0.11801616102457047

验证集上的精度:95.4%

模型已保存。

原文使用的是pytorch:

VGG网络详解(实现猫猫和狗狗识别)_vgg卷积神经网络猫狗实验-CSDN博客

相关文章:

基于tensorflow使用VGG16实现猫狗识别

import tensorflow as tf import numpy as np from tensorflow.keras import layers, models, optimizers from tensorflow.keras.preprocessing.image import ImageDataGenerator# 定义 VGG16 模型 class VGG16(tf.keras.Model):def __init__(self, num_classes2):super(VGG16…...

第18章 EXISTS 与 NOT EXISTS 关键字

一、EXISTS 关键字介绍 关键字介绍EXISTS 关联子查询通常也会和 EXISTS操作符一起来使用,用来检查在子查询中是否存在满足条件的行。 如果在子查询中当前的行不满足条件:返回 FALSE,继续在子查询中查找 如果在子查询中当前的行满足条件&…...

Windows多JDK版本管理工具JVMs

Windows多JDK版本管理工具JVMs 官网安装使用手动下载jdk 官网 https://github.com/ystyle/jvms 下载 https://github.com/ystyle/jvms/releases 当前下载版本为v2.1.6 安装 下载后,解压到某个目录。 比如:D:\soft\JVMs\jvms_v2.1.6_amd64 把这个目录…...

【C++】初始化列表、类型转换

目录: 一、const成员函数 二、初始化列表 三、类型转换 正文 一、const成员函数 (1)将const修饰的成员函数称之为const成员函数,const修饰成员函数放到成员函数参数列表的后⾯。至于为什么这么放是语法规定。 (2&a…...

创新设计,精准仿真|SOLIDWORKS Simulation 2025新功能

SOLIDWORKS Simulation 2025 带来了多项新功能,不仅提高了工作效率,还增强了仿真的精确度。以下是五大新功能的详细介绍,帮助您更好地利用这些新特性提升设计仿真能力。 1. 从分析中排除实体 在复杂的装配体仿真中,有时需要排除某…...

vue3封装Element Plus table表格组件

支持绝大部分Element Plus原有设置属性&#xff0c;支持分页&#xff0c;支持动态适配高度 效果展示 组件代码&#xff1a; <template><div class"table-wrap" ref"tableWrap"><el-tableclass"w100 h100":data"tableInfo.…...

Qt之QWidget相关

Qt概述 Qt 是一个跨平台的 C 开发框架。 跨平台支持&#xff1a;可以用于开发 Windows、macOS、Linux、Android、iOS 等多种操作系统下的应用程序。这意味着开发者使用 Qt 编写的代码&#xff0c;在经过适当的编译和配置后&#xff0c;能够在不同平台上运行&#xff0c;减少了…...

用web前端写出一个高校官网

所实现的效果如链接&#xff1a; http://127.0.0.1:5500/school.html <!DOCTYPE html> <html> <head> <meta charset"utf-8"> <title>xigongshang</title> <style> * {margin: 0;padding: 0;} a{ text-decoration: none…...

【笔记】Android Gradle Plugin配置文件相关说明-libs.versions.toml

版本号 文件路径&#xff1a;Project\gradle\libs.versions.toml 直接搜索versions.agp是找不到的&#xff0c;这是变量引用的写法&#xff0c;查询 agp版本可以直接查版本号。 [versions] agp "8.5.0-alpha08" junit "4.13.2" junitVersion "1.…...

如何修复WordPress卡在维护模式

当你管理WordPress网站时&#xff0c;没有什么比看到它卡在维护模式更令人沮丧的了。特别是在你进行重要更新或期望大量流量的时候&#xff0c;这种情况会更加令人不安。 维护模式可能由许多因素引起&#xff0c;从简单的文件损坏到更复杂的插件冲突或存在的.maintenance文件。…...

glob三个函数的效果

glob 允许你给一个从dirname到basename pattern的整字符串路径&#xff0c;然后匹配一切符合要求的路径。 glob0 dirname和basename分开传&#xff0c;只返回basename。可见不支持pattern匹配。 glob1 dirname和basename pattern分开传&#xff0c;只返回basename。支持pa…...

FreeRTOS:事件标志组与任务通知

目录 一、事件标志组&#xff08;Event Groups&#xff09; 1、事件标志组的特点 2、事件标志组与队列、信号量的区别 3、关键API函数 4、示例代码 5、优缺点 6、总结 二、任务通知&#xff08;Task Notifications&#xff09; 1、任务通知的特点 2、关键API函数 3、…...

c++11的动态类型

c17引入了any 和 variant&#xff0c;可以将任意数据类型统一用any或variant类型表示&#xff0c;在开发中还是能够带来很多便利的。在c11版本中&#xff0c;可以用下面这个例子&#xff0c;仿照实现一个Any类型。 #include <iostream> #include <stdexcept> #inc…...

付费会员渗透难,腾讯音乐的触顶挑战

腾讯音乐付费用户增长背后&#xff0c;月活跃用户数下滑3%&#xff0c;超级会员渗透率仅1.8%。 转载|原创新熵 作者丨晓伊 编辑丨蕨影 腾讯音乐此次营收同比正增长的到来&#xff0c;殊为不易。要知道&#xff0c;此前已连续四个季度出现营收同比下滑的态势。 11月12日&#x…...

内网安全隧道搭建-ngrok-frp-nps-sapp

1.ngrok 建立内网主机与公网跳板机的连接&#xff1a; 内网主机为客户机&#xff1a; 下载客户端执行 2.frp &#xff08;1&#xff09;以下为内网穿透端口转发 frp服务端配置&#xff1a; bindPort 为frp运行端口 服务端运行 ./frps -c frps.ini frp客户端配置&#xf…...

Load-Balanced-Online-OJ(负载均衡式在线OJ)

负载均衡式在线OJ 1. 项目介绍2. 项目说明4. 项目代码5. 项目演示 1. 项目介绍 2. 项目说明 4. 项目代码 5. 项目演示...

Postman之变量操作

系列文章目录 1.Postman之安装及汉化基本使用介绍 2.Postman之变量操作 3.Postman之数据提取 4.Postman之pm.test断言操作 5.Postman之newman Postman之变量操作 1.pm.globals全局变量2.pm.environment环境变量3.pm.collectionVariables集合变量4.pm.variables5.提取数据-设置变…...

查找字符串中某个字符返回字符位置

当然有正则表达式就非常简单,没有的话也不用担心,我们自己写算法完成这个功能. 早期的vs版本不支持vs,当然也可以下载boost来实现,关键还是不想下载,那么就自己写吧. 1.要求,查找字符串中同一个字符,并找出字符的位置. 2.根据字符位置,计算出对应的x,y坐标. 算法第一步,查找字…...

《数学物理学报》

作者指南 一、目的与范围 《数学物理学报》以刊登数学与物理科学的边缘学科中具有创造性的代表学科水平的科研成果为主的综合性学术刊物。其目的旨在向专业读者&#xff08;研究生水平以上&#xff09;提供数理学科领域的重要的、独创的成果。 二、投稿 要求文章内容具有创新…...

39页PDF | 毕马威_数据资产运营白皮书(限免下载)

一、前言 《毕马威数据资产运营白皮书》探讨了数据作为新型生产要素在企业数智化转型中的重要性&#xff0c;提出了数据资产运营的“三要素”&#xff08;组织与意识、流程与规范、平台与工具&#xff09;和“四重奏”&#xff08;数据资产盘点、评估、治理、共享&#xff09;…...

在Ubuntu中设置开机自动运行(sudo)指令的指南

在Ubuntu系统中&#xff0c;有时需要在系统启动时自动执行某些命令&#xff0c;特别是需要 sudo权限的指令。为了实现这一功能&#xff0c;可以使用多种方法&#xff0c;包括编写Systemd服务、配置 rc.local文件或使用 cron任务计划。本文将详细介绍这些方法&#xff0c;并提供…...

从零开始打造 OpenSTLinux 6.6 Yocto 系统(基于STM32CubeMX)(九)

设备树移植 和uboot设备树修改的内容同步到kernel将设备树stm32mp157d-stm32mp157daa1-mx.dts复制到内核源码目录下 源码修改及编译 修改arch/arm/boot/dts/st/Makefile&#xff0c;新增设备树编译 stm32mp157f-ev1-m4-examples.dtb \stm32mp157d-stm32mp157daa1-mx.dtb修改…...

鱼香ros docker配置镜像报错:https://registry-1.docker.io/v2/

使用鱼香ros一件安装docker时的https://registry-1.docker.io/v2/问题 一键安装指令 wget http://fishros.com/install -O fishros && . fishros出现问题&#xff1a;docker pull 失败 网络不同&#xff0c;需要使用镜像源 按照如下步骤操作 sudo vi /etc/docker/dae…...

Android Bitmap治理全解析:从加载优化到泄漏防控的全生命周期管理

引言 Bitmap&#xff08;位图&#xff09;是Android应用内存占用的“头号杀手”。一张1080P&#xff08;1920x1080&#xff09;的图片以ARGB_8888格式加载时&#xff0c;内存占用高达8MB&#xff08;192010804字节&#xff09;。据统计&#xff0c;超过60%的应用OOM崩溃与Bitm…...

Device Mapper 机制

Device Mapper 机制详解 Device Mapper&#xff08;简称 DM&#xff09;是 Linux 内核中的一套通用块设备映射框架&#xff0c;为 LVM、加密磁盘、RAID 等提供底层支持。本文将详细介绍 Device Mapper 的原理、实现、内核配置、常用工具、操作测试流程&#xff0c;并配以详细的…...

大语言模型(LLM)中的KV缓存压缩与动态稀疏注意力机制设计

随着大语言模型&#xff08;LLM&#xff09;参数规模的增长&#xff0c;推理阶段的内存占用和计算复杂度成为核心挑战。传统注意力机制的计算复杂度随序列长度呈二次方增长&#xff0c;而KV缓存的内存消耗可能高达数十GB&#xff08;例如Llama2-7B处理100K token时需50GB内存&a…...

以光量子为例,详解量子获取方式

光量子技术获取量子比特可在室温下进行。该方式有望通过与名为硅光子学&#xff08;silicon photonics&#xff09;的光波导&#xff08;optical waveguide&#xff09;芯片制造技术和光纤等光通信技术相结合来实现量子计算机。量子力学中&#xff0c;光既是波又是粒子。光子本…...

智能AI电话机器人系统的识别能力现状与发展水平

一、引言 随着人工智能技术的飞速发展&#xff0c;AI电话机器人系统已经从简单的自动应答工具演变为具备复杂交互能力的智能助手。这类系统结合了语音识别、自然语言处理、情感计算和机器学习等多项前沿技术&#xff0c;在客户服务、营销推广、信息查询等领域发挥着越来越重要…...

JavaScript基础-API 和 Web API

在学习JavaScript的过程中&#xff0c;理解API&#xff08;应用程序接口&#xff09;和Web API的概念及其应用是非常重要的。这些工具极大地扩展了JavaScript的功能&#xff0c;使得开发者能够创建出功能丰富、交互性强的Web应用程序。本文将深入探讨JavaScript中的API与Web AP…...

jmeter聚合报告中参数详解

sample、average、min、max、90%line、95%line,99%line、Error错误率、吞吐量Thoughput、KB/sec每秒传输的数据量 sample&#xff08;样本数&#xff09; 表示测试中发送的请求数量&#xff0c;即测试执行了多少次请求。 单位&#xff0c;以个或者次数表示。 示例&#xff1a;…...