卷积神经网络(二)

1 卷积运算的两个问题:

1.1 图像边缘信息使用少

        边缘的像素点可能只会被用一次或者2次,中间的会用的更多。

1.2 图像被压缩

        5*5的图像,如果经过3*3的卷积核后,大小变成3*3的。

        N*N的图像,果经过F*F的卷积核后,大小变成(N-F+1)*(N-F+1)的。

为了解决这个问题,在边缘会增加像素。像素点增加多少,取决于卷积核的尺寸和滑动的步长。

2 CNN模型:

卷积层,池化层,展开层,全连接层,如何组合成一个有效的模型。这可以参考经典的CNN模型。

一种方法,是参考经典的模型来搭建自己的模型。另外一种方法,可以利用经典模型的部分模块对图像进行预处理,然后用处理完的数据搭建自己的模型。

2.1 LeNet-5

输入图像:32*32灰度图,1个通道

训练参数:约60000个

随着通道越来越深,图像尺寸变小,通道增多;卷积和池化成对出现

2.2 AlexNet-5

原始图像经过96个11*11的filter,步长为4变换成:(227-11)/4+1=55,图像变化成55*55*96

55x55x96经过3*3步长为2的池化变化成:(55-3)/2+1=27,图像变化成27*27*96

....

输入图像:227*227*3 RGB图,3个通道
训练参数:约60 000 000个
特点:

      1 适用于识别较为复杂的彩色图,可识别10000种类别
      2 结构比LeNet更为复杂,使用Relu作为激活函数

2.3 VGG16

与AlexNet不同的是,在VGG16种卷积核和池化层的大小都是固定的。

输入图像:227*227*3 RGB图,3个通道
训练参数:约138 000 000个
特点:1 所有卷积核的宽和高都是3,步长是1.padding都使用same convolution
      2 所有池化层的filter宽和高都是2,步长都是2
      3 相比于alexnet,有更多的filter用于提取轮廓信息,具有更高的准确性

3 CNN模型的搭建

一种方法,是参考经典的模型来搭建自己的模型。

另外一种方法,可以利用经典模型的部分模块对图像进行预处理,然后用处理完的数据搭建自己的模型。

比如在VGG16种,可以去除掉FC层,替换成一个MLP层,然后再加一个FC层来复用原理的模型,然后吧7*7*512作为输入给到MLP进行训练。

4 代码示例

4.1 建立CNN模型进行猫狗识别

1 加载数据

#load the data
from keras.preprocessing.image import ImageDataGenerator
#归一化
train_datagen = ImageDataGenerator(rescale=1./255)
#从目录里面导入数据
training_set = train_datagen.flow_from_directory('./cats_and_dogs_filtered/train/', target_size=(50,50), batch_size=32,class_mode='binary')

2 建立模型

#set up the cnn model
from keras.models import Sequential
from keras.layers import Conv2D, MaxPool2D, Flatten, Dense
model = Sequential()
#卷积层
model.add(Conv2D(32,(3,3), input_shape=(50,50,3), activation = 'relu'))
#池化层
model.add(MaxPool2D(pool_size=(2,2)))
#卷积层
model.add(Conv2D(32,(3,3), activation = 'relu'))
#池化层
model.add(MaxPool2D(pool_size=(2,2)))
#flattening layer
model.add(Flatten())
#FC layer
model.add(Dense(units=128, activation = 'relu'))
model.add(Dense(units=1, activation='sigmoid'))

3 参数配置

#configure the model
model.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics=['accuracy'])

4 查看模型结构

model.summary()

Model: "sequential_4"
_________________________________________________________________Layer (type)                Output Shape              Param #   
=================================================================conv2d_5 (Conv2D)           (None, 48, 48, 32)        896       max_pooling2d_4 (MaxPooling  (None, 24, 24, 32)       0         2D)                                                             conv2d_6 (Conv2D)           (None, 22, 22, 32)        9248      max_pooling2d_5 (MaxPooling  (None, 11, 11, 32)       0         2D)                                                             flatten_2 (Flatten)         (None, 3872)              0         dense_4 (Dense)             (None, 128)               495744    dense_5 (Dense)             (None, 1)                 129       =================================================================
Total params: 506,017
Trainable params: 506,017
Non-trainable params: 0

5 训练模型

#train the model
model.fit_generator(training_set, epochs=25)

6 计算训练集的准确度

#accuracy on the training data
accuracy_train = model.evaluate(training_set)
print(accuracy_train)

7 计算测试集的准确度

#accuracy on the test data
test_set = train_datagen.flow_from_directory('./cats_and_dogs_filtered/validation/', target_size=(50,50), batch_size=32,class_mode='binary')
#accuracy on the training data
accuracy_test = model.evaluate(test_set)
print(accuracy_test)

8 网站下载图片的测试

#load signal image
from keras.utils import load_img, img_to_array
#pic_dog = './cats_and_dogs_filtered/test_from_internet.jpg'
pic_dog = './cats_and_dogs_filtered/train/dogs/dog.1.jpg'pic_dog = load_img(pic_dog,target_size=(50,50))
pic_dog = img_to_array(pic_dog)
pic_dog = pic_dog/255
pic_dog = pic_dog.reshape(1,50,50,3)
predictions = model.predict(pic_dog)
print(predictions)# 对于二分类问题
if predictions.shape[1] == 1:result = (predictions > 0.5).astype(int)
# 对于多分类问题
else:result = np.argmax(predictions, axis=1)print(result)

4.2 改造VGG16进行识别

1 加载和预处理图片格式,利用VGG16处理图片

from keras.utils import load_img, img_to_array
from keras.applications.vgg16 import VGG16
from keras.applications.vgg16 import preprocess_input
import numpy as np
model_vgg = VGG16(weights='imagenet', include_top=False)
def modelProcess(img_path, model):img = load_img(img_path,target_size=(224,224))img = img_to_array(img)x = np.expand_dims(img, axis = 0)x = preprocess_input(x)x_vgg = model_vgg.predict(x)x_vgg = x_vgg.reshape(1,25088)return x_vgg
import os
folder = "./cats_and_dogs_filtered/train/cats"
dirs = os.listdir(folder)#generate path for the images
img_path = []
for i in dirs:if os.path.splitext(i)[1] == ".jpg":img_path.append(i)
img_path = [folder+"//"+i for i in img_path]#preprocess multiple images
features1 = np.zeros([len(img_path), 25088])
for i in range(len(img_path)):feature_i = modelProcess(img_path[i], model_vgg)print('preprocessed: ', img_path[i])features1[i] = feature_ifolder = "./cats_and_dogs_filtered/train/dogs"
dirs = os.listdir(folder)#generate path for the images
img_path = []
for i in dirs:if os.path.splitext(i)[1] == ".jpg":img_path.append(i)
img_path = [folder+"//"+i for i in img_path]#preprocess multiple images
features2 = np.zeros([len(img_path), 25088])
for i in range(len(img_path)):feature_i = modelProcess(img_path[i], model_vgg)print('preprocessed: ', img_path[i])features2[i] = feature_i#label the result
print(features1.shape, features2.shape)
y1 = np.zeros(1000)
y2 = np.ones(1000)X = np.concatenate((features1,features2),axis=0)
y = np.concatenate((y1,y2), axis=0)

2 分离测试和训练数据

#split the traing and test data
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.3,random_state=50)
print(X_train.shape, X_test.shape, X.shape)

3 建立模型

#set up the mlp model
from keras.models import Sequential
from keras.layers import Dense
model = Sequential()
model.add(Dense(units=10, activation='relu',input_dim=25088))
model.add(Dense(units=1, activation='sigmoid'))
model.summary()
 Layer (type)                Output Shape              Param #   
=================================================================dense_12 (Dense)            (None, 10)                250890    dense_13 (Dense)            (None, 1)                 11        =================================================================
Total params: 250,901
Trainable params: 250,901
Non-trainable params: 0

4 配置和训练模型

#confg the model
model.compile(optimizer='adam', loss = 'binary_crossentropy', metrics=['accuracy'])
#train the model
model.fit(X_train, y_train, epochs=50)

5 训练集测试

from sklearn.metrics import accuracy_score
y_train_predict_probs= model.predict(X_train)
y_train_predict =  (y_train_predict_probs > 0.5).astype(int)
accuracy_train = accuracy_score(y_train,y_train_predict)
print(accuracy_train)

6 测试集测试

from sklearn.metrics import accuracy_score
y_test_predict_probs= model.predict(X_test)
y_test_predict =  (y_test_predict_probs > 0.5).astype(int)
accuracy_test = accuracy_score(y_test,y_test_predict)
print(accuracy_test)

7 下载图片测试

#load the data cat
from keras.utils import load_img, img_to_array
pic_path = './cats_and_dogs_filtered/test_from_ie_cat.jpeg'
pic_cat = load_img(pic_path,target_size=(224,224))
img = img_to_array(pic_cat)
x = np.expand_dims(img, axis = 0)
x = preprocess_input(x)
features = model_vgg.predict(x)
features = features.reshape(1,7*7*512)
result_tmp = model.predict(features)
result =  (result_tmp > 0.5).astype(int)
print(result)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/bicheng/78575.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

组网技术-DHCP服务器,RIP协议,OSPF协议

1.DHCP Server提供三种IP地址分配策略: 手工分配地址 自动分配地址 n 动态分配地址 2.DHCP报文类型 DHCP DISCOVER(广播):用于寻址DHCP Server DHCP OFFER(单播):携带分配给客户端的IP地址 DHCP REQUEST(…

反爬策略应对指南:淘宝 API 商品数据采集的 IP 代理与请求伪装技术

一、引言​ 在电商数据驱动决策的时代,淘宝平台海量的商品数据极具价值。然而,淘宝为保障平台安全和用户体验,构建了严密的反爬体系。当采集淘宝 API 商品数据时,若不采取有效措施,频繁的请求极易触发反爬机制&#x…

学习笔记(算法学习+Maven)

单调队列优化多重背包 #include <bits/stdc.h> using namespace std; const int M 2010; const int N 20010; int q[N]; int hh 0, tt -1; int f[N]; int g[N]; int v[M], w[M], s[M]; int n, m; int main() { cin >> n >> m; for (int i 1; …

WPF之项目创建

文章目录 引言先决条件创建 WPF 项目步骤理解项目结构XAML 与 C# 代码隐藏第一个 "Hello, WPF!" 示例构建和运行应用程序总结相关学习资源 引言 Windows Presentation Foundation (WPF) 是 Microsoft 用于构建具有丰富用户界面的 Windows 桌面应用程序的现代框架。它…

JAVAEE初阶01

个人主页 JavaSE专栏 JAVAEE初阶01 操作系统 1.对下&#xff08;硬件&#xff09;管理各种计算机设备 2.对上&#xff08;软件&#xff09;为各种软件提供一个稳定的运行环境 线程 运行的程序在操作系统中以进程的形式存在 进程是系统分配资源的最小单位 进程与线程的关…

HTML快速入门-4:HTML <meta> 标签属性详解

<meta> 标签是 HTML 文档头部&#xff08;<head> 部分&#xff09;的重要元素&#xff0c;用于提供关于文档的元数据&#xff08;metadata&#xff09;。这些数据不会直接显示在页面上&#xff0c;但对浏览器、搜索引擎和其他服务非常重要。 常用属性 1. name 和 …

前端基础之《Vue(12)—插件封装》

一、插件封装 1、在Vue生态中&#xff0c;除了Vue本身&#xff0c;其它所有的与Vue相关的第三方包&#xff0c;都是插件 例子&#xff1a; import VueRouter form vue-router Vue.use(VueRouter) // 注册插件 2、如何封装Vue插件 &#xff08;1&#xff09;第一种写法 const…

TCP基础题:音乐播放列表管理系统

需求描述 服务器端 创建一个 TCP 服务器&#xff0c;监听本地的 9999 端口&#xff0c;支持多个客户端连接。维护一个音乐播放列表&#xff0c;每个音乐条目包含歌曲名称、歌手、时长等信息。能够处理客户端的以下请求&#xff1a; 添加音乐到播放列表&#xff1a;接收客户端发…

Verilog 语法 (二)

在掌握了 Verilog 的基础语法和常用程序框架之后&#xff0c;本节将带大家深入学习一些 高级设计知识点。这些内容包括&#xff1a; 阻塞赋值&#xff08;&#xff09;与非阻塞赋值&#xff08;<&#xff09;的区别及使用场景&#xff1b; assign 和 always 语句的差异&am…

OpenCV 图形API(61)图像特征检测------检测图像边缘的函数Canny()

操作系统&#xff1a;ubuntu22.04 OpenCV版本&#xff1a;OpenCV4.9 IDE:Visual Studio Code 编程语言&#xff1a;C11 算法描述 使用Canny算法在图像中查找边缘。 该函数在输入图像中查找边缘&#xff0c;并使用Canny算法在输出映射&#xff08;edges&#xff09;中标记它们…

ubantu中下载编译安装qt5.15.3

操作步骤如下&#xff1a; 克隆 Qt 仓库&#xff1a; git clone https://code.qt.io/qt/qt5.git cd qt5 切换到 Qt 5.15.3 标签&#xff1a; git checkout v5.15.3-lts-lgpl 初始化子模块&#xff1a; perl init-repository 配置和编译 Qt&#xff1a; ./configure -prefix $H…

毕业论文设计基本内容和要求:

毕业设计基本内容和要求&#xff1a; 研究内容 调查了解LAMP架构和PHP开发&#xff1b; 学习百度旅游调用的其他产品线服务并熟悉请求接口&#xff1b; 学习社区业务层规范&#xff1b; 设计并实现旅游主要模块&#xff1b; 技术指标 熟悉企业中流程运转的方式&#xff0c;…

【大语言模型】大语言模型(LLMs)在工业缺陷检测领域的应用

大语言模型&#xff08;LLMs&#xff09;在工业缺陷检测领域的应用场景正在快速扩展&#xff0c;结合其多模态理解、文本生成和逻辑推理能力&#xff0c;为传统检测方法提供了新的技术路径。以下是该领域的主要应用场景及相关技术进展&#xff1a; 1. 多模态缺陷检测与解释 视…

【AI插件开发】Notepad++ AI插件开发1.0发布和使用说明

一、产品简介 AiCoder是一款为Notepad设计的轻量级AI辅助插件&#xff0c;提供以下核心功能&#xff1a; 嵌入式提问&#xff1a;对选中的文本内容进行AI分析&#xff0c;通过侧边栏聊天界面与AI交互&#xff0c;实现多轮对话、问题解答或代码生成。对话式提问&#xff1a;独…

第2讲:R语言中的色彩美学——科研图表配色指南

目录 一、背景导引:科研图表为何需要“配色讲究”? 二、色彩基础认知:别让“红绿盲”错过你的科研成果 三、R语言中的配色库全景图 四、案例演示与代码实战 🎨案例1:ggplot2 + viridis 配色的热图 🎨案例2:MetBrewer 中的印象派色彩 五、技巧点拨:如何为SCI图…

基于Django的个性化股票交易管理系统

本项目基于Python3.6、Django2.1、MySql8.0&#xff08;最好不要使用5.6&#xff0c;字符集等方面均不兼容&#xff0c;否则导入数据库会出错&#xff09;与股票信息工具包TuShare实现。 创建或激活对应Python开发环境 这里使用了conda来管理环境&#xff0c;强烈推荐&#xf…

超越GPT-4?下一代大模型的技术突破与挑战

超越GPT-4&#xff1f;下一代大模型的技术突破与挑战 引言&#xff1a;大模型的演进历程 人工智能领域近年来最引人注目的发展莫过于大型语言模型(Large Language Models, LLMs)的快速进步。从GPT-3到GPT-4&#xff0c;再到如今各种宣称"超越GPT-4"的模型不断涌现&…

Js 之点击下拉搜索Ajax-Bootstrap-Select

一、效果图 二、文档 https://gitcode.com/gh_mirrors/aj/Ajax-Bootstrap-Select/tree/master 三、示例代码 引入插件js、css <link rel"stylesheet" href"{php echo MODULE_URL}template/lib/bootstrap-select/css/bootstrap-select.min.css"> <…

无线监控系统分类全解析:搭配视频融合平台EasyCVR开启高效监控

随着技术的发展&#xff0c;无线监控系统在家庭、小型企业、特定行业以及室外恶劣环境中的应用越来越广泛。本文将介绍几种常见的无线监控系统&#xff0c;分析其优缺点&#xff0c;并结合EasyCVR视频融合平台的功能&#xff0c;探讨如何优化无线监控系统的性能和应用。 一、主…

WebRTC服务器Coturn服务器中的通信协议

1、概述 作为WebRTC服务器&#xff0c;coturn通信协议主要是STUN和TURN协议 STUN&TURN协议头部都是20个字节,用 Message Type来区分不同的协议 |------2------|------2------|------------4------------|------------------------12-------------------------|-----------…