人工智能深度學習——卷積神經網絡(CNN)

在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述

一、圖像卷積運算

對圖像矩陣與濾波器矩陣進行對應相乘再求和運算,轉化得到新的矩陣。

作用:快速定位圖像中某些邊緣特征

英文:convolution(CNN)

在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述
池化層實現維度縮減

池化:按照一個固定規則對圖像矩陣進行處理,將其轉換為更低維度的矩陣

在這里插入圖片描述
在這里插入圖片描述

卷積神經網絡

把卷積、池化、mlp先后連接在一起,組成卷積神經網絡。

在這里插入圖片描述
激活函數:Relu
在這里插入圖片描述

卷積神經網絡兩大特點

  • 參數共享(parameter sharing):同一個特征過濾器可用于整張圖片

  • 稀疏連接(sparsity of connections):生成的特征圖片每個節點只與原圖片中特定節點連接

在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述

經典的CNN模型

在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述

二、實戰準備

在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述

三、實戰:建立CNN模型,識別圖片中的貓/狗

在這里插入圖片描述

#加載數據
from tensorflow.keras.preprocessing.image import ImageDataGenerator
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')

在這里插入圖片描述

#創建cnn模型
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)))#展開
model.add(Flatten())#全連接層
model.add(Dense(units=128,activation='relu'))#輸出層
model.add(Dense(units=1,activation='sigmoid'))
#配置模型 (優化器,損失函數)
model.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])
#查看模型結構
model.summary()

在這里插入圖片描述

#模型訓練
model.fit(training_set,epochs=25)

在這里插入圖片描述

#訓練集模型準確率
accuracy_train = model.evaluate(training_set)
print(accuracy_train)

在這里插入圖片描述

#測試集模型準確率
test_set = train_datagen.flow_from_directory('./dataset/test_set',target_size=(50,50),batch_size=32,class_mode='binary')
accuracy_test = model.evaluate(test_set)
print(accuracy_test)

在這里插入圖片描述

#預測單張測試圖片
from keras.preprocessing.image import load_img,img_to_array
import numpy as np
pic_dog = 'dog_test.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)
result = '預測為:狗狗' if predictions[0] >= 0.5 else '預測為:貓咪'
print(result)

在這里插入圖片描述

training_set.class_indices

在這里插入圖片描述

#測試多張圖片,驗證準確率
import matplotlib as mlp
font2 = {'family' :'SimHei','weight':'normal','size':20,}mlp.rcParams['font.family'] = 'SimHei'
mlp.rcParams['axes.unicode_minus'] = Falsefrom 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 i in 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)predictions = model.predict(img)img_ori = load_img(img_name,target_size=(250,250))plt.subplot(3,3,i)plt.imshow(img_ori)plt.title('預測為:狗狗' if predictions[0] >= 0.5 else '預測為:貓咪')
plt.show()    

四、實戰:使用VGG16模型提取圖像特征,再根據特征建立mlp模型,實現貓狗圖像識別

#加載數據
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)
print(type(img))

在這里插入圖片描述

#導入VGG16模型
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)
x = np.expand_dims(img,axis=0)
x = preprocess_input(x)#圖像預處理
print(x.shape)

在這里插入圖片描述

#特征輪廓提取
features = model_vgg.predict(x)
print(features.shape)

在這里插入圖片描述

features = features.reshape(1,7*7*512)
print(features.shape)

在這里插入圖片描述

#可視化圖片
from matplotlib import pyplot as plt 
fig = plt.figure(figsize=(2,2))
img = load_img(img_path,target_size=(224,224))
plt.imshow(img)

在這里插入圖片描述

#批量處理圖片
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(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.predict(x)x_vgg = x_vgg.reshape(1,25088)return x_vggimport os
folder = 'dataset/vgg16_set/cat'
# folder = 'dataset/test_set/cat'
dirs = os.listdir(folder)
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]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/vgg16_set/dog'
# folder = 'dataset/test_set/dog'
dirs = os.listdir(folder)
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]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_iprint(features1.shape,features2.shape)
y1 = np.zeros(300)
y2 = np.ones(300)
# y1 = np.zeros(3)
# y2 = np.ones(1)x = np.concatenate((features1,features2),axis=0)
y = np.concatenate((y1,y2),axis=0)
y = y.reshape(-1,1)
print(x.shape,y.shape)

在這里插入圖片描述

#數據分離
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)

在這里插入圖片描述

#建立mlp模型
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()

在這里插入圖片描述

#配置模型,訓練模型
model.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])
model.fit(x_train,y_train,epochs=50)

在這里插入圖片描述

#預測
from sklearn.metrics import accuracy_score
# 獲取預測概率
y_train_pred_prob = model.predict(x_train)
# 二分類:sigmoid輸出,使用0.5作為閾值
y_train_predict = (y_train_pred_prob > 0.5).astype("int32").flatten()accuracy_train = accuracy_score(y_train,y_train_predict)
print(accuracy_train)

在這里插入圖片描述

# 獲取預測概率
y_test_pred_prob = model.predict(x_test)
# 二分類:sigmoid輸出,使用0.5作為閾值
y_test_predict = (y_test_pred_prob > 0.5).astype("int32").flatten()accuracy_test = accuracy_score(y_test,y_test_predict)
print(accuracy_test)

在這里插入圖片描述

#測試多張圖片,驗證準確率
import matplotlib as mlp
font2 = {'family' :'SimHei','weight':'normal','size':20,}mlp.rcParams['font.family'] = 'SimHei'
mlp.rcParams['axes.unicode_minus'] = Falsefrom 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 i in 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=(224,224))img = img_to_array(img_ori)x = np.expand_dims(img,axis=0)x = preprocess_input(x)#vgg16提取特征x_vgg = model_vgg.predict(x)x_vgg = x_vgg.reshape(1,25088)# 獲取預測概率predictions = model.predict(x_vgg)# 二分類:sigmoid輸出,使用0.5作為閾值y_train_predict = (y_train_pred_prob > 0.5).astype("int32").flatten()img_ori = load_img(img_name,target_size=(250,250))plt.subplot(3,3,i)plt.imshow(img_ori)plt.title('預測為:狗狗' if predictions >= 0.5 else '預測為:貓咪')
plt.show()

在這里插入圖片描述

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

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

相關文章

SaaS 建站從 0 到 1 教程:Vue 動態域名 + 后端子域名管理 + Nginx 配置

SaaS 建站從 0 到 1 教程:Vue 動態域名 后端子域名管理 Nginx 配置 一、什么是 SaaS 建站? SaaS(Software as a Service)建站,就是通過一套統一的系統,支持用戶在線注冊、綁定域名、快速生成專屬網站。…

關于神經網絡中回歸的概念

神經網絡中的回歸詳解 引言 神經網絡(NeuralNetworks)是一種強大的機器學習模型,可用于分類和回歸任務。本文聚焦于神經網絡中的回歸(Regression),即預測連續輸出值(如房價、溫度)。…

JAVASCRIPT 前端數據庫-V9--仙盟數據庫架構-—仙盟創夢IDE

老版本 在v1 版本中我們講述了 基礎版的應用JAVASCRIPT 前端數據庫-V1--仙盟數據庫架構-—-—仙盟創夢IDE-CSDN博客接下載我們做一個更復雜的的其他場景由于,V1查詢字段必須 id接下來我們修改了了代碼JAVASCRIPT 前端數據庫-V2--仙盟數據庫架構-—-—仙盟創夢IDE-CS…

k8s核心資料基本操作

NamespaceNamespace是kubernetes系統中的一種非常重要資源,它的主要作用是用來實現多套環境的資源隔離或者多租戶的資源隔離。默認情況下,kubernetes集群中的所有的Pod都是可以相互訪問的。但是在實際中,可能不想讓兩個Pod之間進行互相的訪問…

PostgreSQL——分區表

分區表一、分區表的意義二、傳統分區表2.1、繼承表2.2、創建分區表2.3、使用分區表2.4、查詢父表還是子表2.5、constraint_exclusion參數2.6、添加分區2.7、刪除分區2.8、分區表相關查詢2.9、傳統分區表注意事項三、內置分區表3.1、創建分區表3.2、使用分區表3.3、內置分區表原…

Linux任務調度全攻略

Linux下的任務調度分為兩類,系統任務調度和用戶任務調度。系統任務調度:系統周期性所要執行的工作,比如寫緩存數據到硬盤、日志清理等。在/etc目錄下有一個crontab文件,這個就是系統任務調度的配置文件。/etc/crontab文件包括下面…

回溯算法通關秘籍:像打怪一樣刷題

🚀 回溯算法通關秘籍:像打怪一樣刷題! 各位同學,今天咱們聊聊 回溯算法(Backtracking)。它聽起來玄乎,但其實就是 “暴力搜索 剪枝” 的優雅版。 打個比方:回溯就是在迷宮里探險&am…

嵌入式Linux常用命令

📟 核心文件與目錄操作pwd-> 功能: 打印當前工作目錄的絕對路徑。-> 示例: pwd -> 輸出 /home/user/projectls [選項] [目錄]-> 功能: 列出目錄內容。-> 常用選項:-l: 長格式顯示(詳細信息)-a: 顯示所有文件(包括隱…

深入理解 Linux 內核進程管理

在 Linux 系統中,進程是資源分配和調度的基本單位,內核對進程的高效管理直接決定了系統的性能與穩定性。本文將從進程描述符的結構入手,逐步剖析進程的創建、線程實現與進程終結的完整生命周期,帶您深入理解 Linux 內核的進程管理…

ACP(三):讓大模型能夠回答私域知識問題

讓大模型能夠回答私域知識問題 未經過特定訓練答疑機器人,是無法準確回答“我們公司項目管理用什么工具”這類內部問題。根本原因在于,大模型的知識來源于其訓練數據,這些數據通常是公開的互聯網信息,不包含任何特定公司的內部文檔…

使用Xterminal連接Linux服務器

使用Xterminal連接Linux服務器(VMware虛擬機)的步驟如下,前提是虛擬機已獲取IP(如 192.168.31.105)且網絡互通: 一、準備工作(服務器端確認)確保SSH服務已安裝并啟動 Linux服務器需要…

ChatBot、Copilot、Agent啥區別

以下內容為AI生成ChatBot(聊天機器人)、Copilot(副駕駛)和Agent(智能體/代理)是AI應用中常見的三種形態,它們在人機交互、自動化程度和任務處理能力上有著顯著的區別。特征維度ChatBot (聊天機器…

2025 年大語言模型架構演進:DeepSeek V3、OLMo 2、Gemma 3 與 Mistral 3.1 核心技術剖析

編者按: 在 Transformer 架構誕生八年之際,我們是否真的見證了根本性的突破,還是只是在原有設計上不斷打磨?今天我們為大家帶來的這篇文章,作者的核心觀點是:盡管大語言模型在技術細節上持續優化&#xff0…

基于Matlab GUI的心電信號QRS波群檢測與心率分析系統

心電信號(Electrocardiogram, ECG)是臨床診斷心臟疾病的重要依據,其中 QRS 波群的準確檢測對于心率分析、心律失常診斷及自動化心電分析系統具有核心意義。本文設計并實現了一套基于 MATLAB GUI 的心電信號處理與分析系統,集成了數…

1臺SolidWorks服務器能帶8-10人并發使用

在工業設計和機械工程領域,SolidWorks作為主流的三維CAD軟件,其服務器部署方案直接影響企業協同效率。通過云飛云共享云桌面技術實現多人并發使用SolidWorks時,實際承載量取決于硬件配置、網絡環境、軟件優化等多維度因素的綜合作用。根據專業…

String、StringBuilder和StringBuffer的區別

目錄一. String:不可變的字符串二.StringBuilder:可變字符串三.StringBuffer:線程安全的可變字符串四.總結在 Java 開發中,字符串處理是日常編碼中最頻繁的操作之一。String、StringBuilder 和 StringBuffer 這三個類雖然都用于操…

Power Automate List Rows使用Fetchxml查詢的一個bug

看一段FetchXML, 這段查詢在XRMtoolbox中的fech test工具里執行完全ok<fetch version"1.0" mapping"logical" distinct"true" no-lock"false"> <entity name"new_projectchange"> <link-entity name"sy…

Letta(MemGPT)有狀態AI代理的開源框架

1. 項目概述Letta&#xff08;前身為 MemGPT&#xff09;是一個用于構建有狀態AI代理的開源框架&#xff0c;專注于提供長期記憶和高級推理能力。該項目是MemGPT研究論文的實現&#xff0c;引入了"LLM操作系統"的概念用于內存管理。核心特點有狀態代理&#xff1a;具…

除了ollama還有哪些模型部署方式?多樣化模型部署方式

在人工智能的浪潮中&#xff0c;模型部署是釋放其強大能力的關鍵一環。大家都知道ollama&#xff0c;它在模型部署領域有一定知名度&#xff0c;操作相對簡單&#xff0c;受到不少人的青睞。但其實&#xff0c;模型部署的世界豐富多樣&#xff0c;今天要給大家介紹一款工具&…

Linux系統學習之進階命令匯總

文章目錄一、系統信息1.1 查看系統信息&#xff1a;uname1.2 查看主機名&#xff1a;hostname1.3 查看cpu信息&#xff1a;1.4 當前已加載的內核模塊: lsmod1.5 查看磁盤空間使用情況: df1.6 管理磁盤分區: fdisk1.7 查看目錄或文件磁盤使用情況: du1.8 查看I/O使用情況: iosta…