人工智能-深度學習之卷積神經網絡

深度學習

  • mlp弊端
  • 卷積神經網絡
    • 圖像卷積運算
    • 卷積神經網絡的核心
    • 池化層實現維度縮減
    • 卷積神經網絡
    • 卷積神經網絡兩大特點
    • 卷積運算導致的兩個問題:
    • 圖像填充(padding)
    • 結構組合問題
    • 經典CNN模型
      • LeNet-5模型
      • AlexNet模型
      • VGG-16模型
    • 經典的CNN模型用于新場景
  • 實戰
    • 實戰(1):建立CNN實現貓狗識別
    • 實戰(2):基于VGG16、結合mlp實現貓狗識別


mlp弊端

mlp模型的弊端:圖片大時,參數也很多。
辦法:提取出圖像中的關鍵信息,再建立mlp模型進行訓練。
在這里插入圖片描述

卷積神經網絡

圖像卷積運算

對圖像矩陣與濾波器矩陣進行對應相乘再求和運算,轉化得到新的矩陣。
作用:快速定位圖像中某些邊緣特征
英文:convolution(卷積神經網絡:CNN)
在這里插入圖片描述
在這里插入圖片描述
將圖片與輪廓濾波器進行卷積運算,可快速定位固定輪廓特征的位置
在這里插入圖片描述

卷積神經網絡的核心

計算機根據樣本圖片,自動尋找合適的輪廓過濾器,對新圖片進行輪廓匹配
自動求解W,尋找合適的過濾器。一個過濾器不夠,需要尋找很多過濾器。
在這里插入圖片描述
RGB圖像的卷積:對R/G/B三個通道分別求卷積再相加。(如圖,為兩個過濾器)
在這里插入圖片描述

池化層實現維度縮減

池化:按照一個固定規則對圖像矩陣進行處理,將其轉換為更地維度的矩陣
Srtide為窗口滑動步長,用于池化、卷積的計算中。
保留核心信息的情況下,實現維度縮減。
最大法池化(Max-pooling):
在這里插入圖片描述
平均法池化(Avg-pooling):
在這里插入圖片描述

卷積神經網絡

把卷積、池化、mlp先后連接在一起,組成卷積神經網絡
在這里插入圖片描述

卷積神經網絡兩大特點

1、參數共享(parameter sharing):同一個特征過濾器可用于整張圖片
2、稀疏連接(sparsity of connections):生成的特征圖片每個節點只與原圖片中特定節點連接
在這里插入圖片描述

卷積運算導致的兩個問題:

1、圖像被壓縮,信息丟失
2、邊緣信息使用少,容易被忽略
在這里插入圖片描述

圖像填充(padding)

通過在圖像各邊添加像素,使其在進行卷積運算后維持原圖大小
在這里插入圖片描述
通過padding增加像素的數量,由過濾器尺寸與stride決定

結構組合問題

在這里插入圖片描述

經典CNN模型

1、參考經典CNN結構搭建新模型
2、使用經典CNN模型結構對圖像預處理,再建立MLP模型
經典CNN模型:
1、LeNet-5
2、AlexNet
3、VGG

LeNet-5模型

在這里插入圖片描述

解析:第一次(32-5)/1+1=28,第二次(28-2)/2+1=14,第三次(14-5)/1+1=10,第四次(10-2)/2+1=5.
輸入圖像:32x32灰度圖,一個通道(channel)
訓練參數:約60000個
特點:
1、隨著網絡越深,圖像的高度和寬度在縮小,通道數在增加
2、卷積和池化先后成對使用

AlexNet模型

在這里插入圖片描述
輸入圖像:227x227x3 RGB圖,3個通道
訓練參數:約60000000個
特點:
1、適用于識別較為復雜的彩色圖,可識別1000種類別
2、結構比LeNet更為復雜,使用Relu作為激活函數
結果:
學術界開始相信深度學習技術,在計算機視覺應用中可以得到很不錯的效果

VGG-16模型

在這里插入圖片描述
輸入圖像:227x227x3 RGB圖,3個通道
訓練參數:約138000000個
特點:
1、所有卷積層filter寬和高都是3,步長為1,padding都使用same convolution;
2、所有池化層的filter寬和高都是2,步長為2;
3、相比alexnet,有更多的filter用于提取輪廓信息,具有更高精準性;

經典的CNN模型用于新場景

1、使用經典的CNN模型結構對圖像預處理,再建立MLP模型;
2、參考經典的CNN結構搭建新模型

1、加載經典的CNN模型,剝除其FC層,對圖像進行預處理
2、把預處理完成的數據作為輸入,分類結果為輸出,建立一個mlp模型
3、模型訓練
在這里插入圖片描述

在這里插入圖片描述

實戰

實戰(1):建立CNN實現貓狗識別

任務:基于dataset/training_set數據,根據提供的結構,建立CNN模型
1、識別圖片中的貓/狗、計算dataset/test_set測試數據預測準確率
2、從網站下載貓/狗圖片,對其進行預測
在這里插入圖片描述

#load the data
from keras.preprocessing.image import ImageDataGenrator
train_datagen = ImageDataGenerator(rescale=1./255)
training_set = train_datagen.flow_from_directory('./dataset/training_set',target_size=(50,50),batch_size=32,class_mode='binary')#set up the cnn model
from keras.models import Sequential
form 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'))#configure the model
model.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])
model.summary()#train the model
model.fit_generator(training_set,epochs=25)
#accuracy on the training data
accuracy_train = model.evaluate_generator(training_set)
print(accuracy_train)
#accuracy on the test data
test_set = train_datagen.flow_from_directory('./dataset/test_set',target_size=(50,50),batch_size=32,class_mode='binary')
accuracy_test = model.evaluate_generator(test_set)
print(accuracy_test)#load single image
from keras.preprocessing.image import load_img, img_to_array
pic_dog = 'dog.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)
result = model.predict_classes(pic_dog)
print(result)pic_cat = 'cat.jpg'
pic_cat = load_img(pic_cat,target_size=(50,50))
pic_cat = img_to_array(pic_cat)
pic_cat = pic_cat/255
pic_cat = pic_cat.reshape(1,50,50,3)
result = model.predict_classes(pic_cat)
print(result)
#補充說明,以下方法可以查看輸出的數字是什么標簽,如'cat':0,'dogs':1
training_set.class_indices
#make prediction on multiple images
import matplotlib as mlp
font2 = {'family':'SomHei','weight':'normal','size': 20,}
mlp.rcParams['font.family'] = 'SimHei'
mlp.rcParams['axes.unicode_minus'] = False
from matplotlib import pyplot as plt
from matplotlib.image import imread
from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array
from keras.models import load_model
a = [i for range(1,10)]
fig = plt.figure(figsize=(10,10))
for i in a:img_name = str(i)+'.jpg'img_ori = load_img(img_name,target_size=(50,50))img = img_to_array(img_ori)img = img.astype('float32')/255img = img.reshape(1,50,50,3)result = model.predict_classes(img)img_ori = load_img(img_name, target_size=(250,250))plt.subplot(3,3,i)plt.imshow(img_ori)plt.title('預測為:狗狗' if result[0][0] == 1 else '預測為:貓咪')
plt.show()

實戰(2):基于VGG16、結合mlp實現貓狗識別

任務:使用VGG16的結構提取圖像特征,再根據特征建立mlp模型,實現貓狗圖像識別。訓練/測試數據:dataset\data_vgg
1、對數據進行分離、計算測試數據預測準確率
2、從網站下載貓/狗圖片,對其進行預測
備注:mlp模型只有一個隱藏層(10個神經元)

#load the data 
from keras.preprocessing.image import load_img,img_to_array
img_path = '1.jpg'
img = load_img(img_path,target_size=(224,224))
img = img_to_array(img)
type(img)from karas.applications.vgg16 import VGG16
from keras.applications.vgg16 import preprocess_input
import numpy as nn
model_vgg = VGG16(weights='imagenet',include_top=False)
x = np.expand_dims(img,axis=0)
x = preprocess_input(x)
print(x.shape)#特征提取
features = model_vgg.predict(x)
print(features.shape)
#flatten
features = features.reshape(1,7*7*512)
print(features.shape)
#visualize the data
%matplotlib inline
from matplotlib import pyplot as plt
fig = plt.figure(figsize=(5,5))
img = load_img(img_path,target_size=(224,224))
plt.imshow(img)
#此處為批量處理
#load image and preprocess it with vgg16 structure
from keras.preprocessing.image import img_to_array,load_img
from keras.applications.vgg16 import VGG16
from keras.applications.vgg16 import preprocess_input
import numpy as npmodel_vgg = VGG16(weight='imagent',include_top=False)
#define a method to load and preprocess the image
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.predict(x)x_vgg = x_vgg.reshape(1,25088)return x_vgg#list file names of the training datasets
import os
folder = "dataset/data_vgg/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 = "dataset/data_vgg/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 results
print(features1.shape,features2.shape)
y1 = np.zeros(300)
y2 = np.ones(300)#generate the training data
X = np.concatenate((features1,features2),axis=0)
y = np.concatenate((y1,y2),axis=0)
y = y.reshape(-1,1)
print(X.shape,y.shape)#split the training and test data
from sklearn.model_selection import train_test_split
X_train,y_trian,X_test,y_test = train_test_split(X,y,test_size=0.3,random_state=50)
pirnt(X_train.shape,X_test.shape,X/shape)#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()
#configure the model
model.compile(optimizer='adam',loss='binary_crossentropy',metric=['accuracy'])
#train the model
model.fit(X_train,y_train,epochs=50)from sklearn.metrics import accuracy_score
y_train_predict = model.predict_classes(X_train)
accuracy_train = accuracy_score(y_train,y_train_predict)
print(accuracy_train)#測試準確率
y_test_predict = model.predict_classes(X_test)
accuracy_test = accuracy_score(y_test,y_test_predict)
print(accuracy_test)# coding:utf-8 批量處理圖片
import matplotlib as mlp
font2 = { 'family' : 'SimHei','weight' : 'normal','size'   : 20,
}
mlp.rcParams['font.family'] = 'SimHei'
mlp.rcParams['axes.unicode_minus'] = False
from matplotlib import pyplot as plt
from matplotlib.image import imread
from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array
from keras.models import load_model
#from cv2 import load_img
a = [i for i in range(1,10)]
fig = plt.figure(figsize=(10,10))
for i in a:img_name = str(i)+'.jpg'img_path = img_nameimg = 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(4,25088)result = model.predict_classes(x_vgg)img_ori = load_img(img_name, target_size=(250, 250))plt.subplot(3,3,i)plt.imshow(img_ori)plt.title('預測為:狗狗' if result[0][0] == 1 else '預測為:貓咪')
plt.show()

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/pingmian/79300.shtml
繁體地址,請注明出處:http://hk.pswp.cn/pingmian/79300.shtml
英文地址,請注明出處:http://en.pswp.cn/pingmian/79300.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

藍橋杯電子賽_繼電器和蜂鳴器

目錄 一 前言 二 繼電器和蜂鳴器實物 三 分析部分 (1)bsp_init.c (2)蜂鳴器和繼電器原理圖 (3)ULN2003 (4)他們倆所連接的鎖存器 四 代碼 在這里要特別說一點!&…

仿騰訊會議——主界面設計創建房間加入房間客戶端實現

1、實現騰訊會議主界面 2、添加Qt類WeChatDialog 3、定義創建會議和加入會議的函數 4、實現顯示名字、頭像的函數 調用函數 5、在中間者類中綁定函數 6、實現創建房間的槽函數 7、實現加入房間的槽函數 8、設置界面標題 9、服務器定義創建和進入房間函數 10、服務器實現創建房間…

網絡編程初識

注:此博文為本人學習過程中的筆記 1.socket api 這是操作系統提供的一組api,由傳輸層向應用層提供。 2.傳輸層的兩個核心協議 傳輸層的兩個核心協議分別是TCP協議和UDP協議,它們的差別非常大,編寫代碼的風格也不同&#xff0c…

【質量管理】現代TRIZ問題識別中的功能分析——功能模型

功能模型的定義 功能模型是對工程系統進行功能分析的一個階段,目的是建立工程系統的功能模型。功能模型描述了工程系統和超系統組件的功能,包括有用功能、性能水平和成本等。 在文章【質量管理】現代TRIZ中問題識別中的功能分析——相互接觸分析-CSDN博客…

廣告事件聚合系統設計

需求背景 廣告事件需要進行統計,計費,分析等。所以我們需要由數據接入,數據處理,數據存儲,數據查詢等多個服務模塊去支持我們的廣告系統 規模上 10000 0000個點擊(10000 00000 / 100k 1wQPS) …

C語言中,sizeof關鍵字(詳細介紹)

目錄 ?1. 基本用法?(1) ?基本數據類型?(2) ?變量?(3) ?數組?(4) ?指針? ?2. 特殊用法?(1) ?結構體與內存對齊?(2) ?動態內存分配?(3) ?表達式? ?3. 注意事項??1)sizeof 與 strlen 的區別?:?2)變長數組(VLA…

ADK 第三篇 Agents (LlmAgent)

Agents 在智能體開發套件(ADK)中,智能體(Agent)是一個獨立的執行單元,旨在自主行動以實現特定目標。智能體能夠執行任務、與用戶交互、使用外部工具,并與其他智能體協同工作。 在ADK中&#x…

【深度學習】典型的 CNN 網絡

目錄 一、LeNet-5 (1)LeNet-5 網絡概覽 (2)網絡結構詳解 (3)關鍵組件與數學原理 3.1 局部感受野與卷積運算 3.2 權重共享 3.3 子采樣(Pooling) 3.4 激活函數 (4…

4.8/Q1,中山大學用NHANES:膳食煙酸攝入量與非酒精性脂肪肝之間的關聯

文章題目:Association between Dietary Niacin Intake and Nonalcoholic Fatty Liver Disease: NHANES 2003-2018 DOI:10.3390/nu15194128 中文標題:膳食煙酸攝入量與非酒精性脂肪肝之間的關聯:NHANES 2003-2018 發表雜志&#xf…

高效管理遠程服務器Termius for Mac 保姆級教程

以下是 Termius for Mac 保姆級教程,涵蓋安裝配置、核心功能、實戰案例及常見問題解決方案,助你高效管理遠程服務器(如Vultr、AWS等)。 一、Termius 基礎介紹 1. Termius 是什么? 跨平臺SSH客戶端:支持Ma…

理解數學概念——支集(支持)(support)

1. 支集(support)的定義 在數學中,一個實函數 f 的支集(support)是函數的不被映射到 0 的元素域(即定義域)的子集。若 f 的(定義)域(domain)是一個拓撲空間(即符合拓撲的集合),則 f 的支集則定義為包含( f 的元素域中)不被映射到0的所有點之最小閉集…

Vue 3 Element Plus 瀏覽器使用例子

Element Plus 是一個基于 Vue 3 的流行開源 UI 庫,提供了一系列的組件,幫助開發者快速構建現代化的用戶界面。它的設計簡潔、現代,包含了許多可定制的組件,如按鈕、表格、表單、對話框等,適合用于開發各種 Web 應用。 …

SSR vs SSG:前端渲染模式終極對決(附 Next.js/Nuxt.js 實戰案例)

一、引言:前端渲染模式的進化之路 隨著互聯網的發展,用戶對于網頁的加載速度和交互體驗要求越來越高。前端渲染技術作為影響網頁性能的關鍵因素,也在不斷地發展和演進。從最初的客戶端渲染(CSR),到后來的服…

算法筆記.分解質因數

代碼實現&#xff1a; #include<iostream> using namespace std; void breakdown(int x) {int t x;for(int i 2;i < x/i;i){if(t%i 0){int counts 0;while(t % i 0){t/i;counts;}cout << i <<" "<< counts<<endl;}}if(t >…

CUDA Error: the provided PTX was compiled with an unsupported toolchain

CUDA程序編譯時生成的PTX代碼與系統上的CUDA驅動版本不兼容 CUDA 編譯器版本&#xff1a; CUDA 12.6 (nvcc 編譯器版本) CUDA 驅動版本&#xff1a; CUDA 12.3 (nvidia-smi 驅動版本) 解決方法&#xff1a; 驅動版本下載參考&#xff1a;Your connected workspace for wiki…

計算機組成原理實驗(7) 堆指令部件模塊實驗

實驗七 堆指令部件模塊實驗 一、實驗目的 1、掌握指令部件的組成方式。 2、熟悉指令寄存器的打入操作&#xff0c;PC計數器的設置和加1操作&#xff0c;理解跳轉指令的實現過程。 二、實驗要求 按照實驗步驟完成實驗項目&#xff0c;掌握數據打入指令寄存器IR1、PC計數器的…

2022 年 6 月大學英語四級考試真題(第 2 套)——閱讀版——仔細閱讀題

&#x1f3e0;個人主頁&#xff1a;fo安方的博客? &#x1f482;個人簡歷&#xff1a;大家好&#xff0c;我是fo安方&#xff0c;目前中南大學MBA在讀&#xff0c;也考取過HCIE Cloud Computing、CCIE Security、PMP、CISP、RHCE、CCNP RS、PEST 3等證書。&#x1f433; &…

磁盤文件系統

磁盤文件系統 一、磁盤結構1.1 認識一下基礎的硬件設備以及真實的機房環境1.2 磁盤物理結構與存儲結構1、磁盤物理結構2、磁盤的存儲結構3、CHS地址定位4、磁盤的邏輯結構&#xff08;LBA&#xff09;5 磁盤真實過程5 CHS && LBA地址 二、理解分區、格式化1 引?"…

基于LangChain 實現 Advanced RAG-后檢索優化(下)-上下文壓縮與過濾

摘要 Advanced RAG 的后檢索優化&#xff0c;是指在檢索環節完成后、最終響應生成前&#xff0c;通過一系列策略與技術對檢索結果進行深度處理&#xff0c;旨在顯著提升生成內容的相關性與質量。在這些優化手段中&#xff0c;上文壓縮與過濾技術是提升檢索結果質量的重要手段。…

為什么 Vite 速度比 Webpack 快?

一、webpack會先進行編譯&#xff0c;再運行&#xff0c;vite會直接啟動&#xff0c;再按需編譯文件。 首先看兩張圖&#xff0c;可以清晰的看到&#xff0c;上面的圖是webpack編譯過的&#xff0c;而下面的圖是vite直接使用工程內文件。 二、區別于Webpack先打包的方式&am…