Keras框架:Alexnet網絡代碼實現

網絡思想:

在這里插入圖片描述
1、一張原始圖片被resize到(224,224,3);
2、使用步長為4x4,大小為11的卷積核對圖像進行卷積,輸出的特征層為96層, 輸出的shape為(55,55,96);
3、使用步長為2的最大池化層進行池化,此時輸出的shape為(27,27,96)
4、使用步長為1x1,大小為5的卷積核對圖像進行卷積,輸出的特征層為256層, 輸出的shape為(27,27,256);
5、使用步長為2的最大池化層進行池化,此時輸出的shape為(13,13,256);
6、使用步長為1x1,大小為3的卷積核對圖像進行卷積,輸出的特征層為384層, 輸出的shape為(13,13,384);
7、使用步長為1x1,大小為3的卷積核對圖像進行卷積,輸出的特征層為384層, 輸出的shape為(13,13,384);
8、使用步長為1x1,大小為3的卷積核對圖像進行卷積,輸出的特征層為256層, 輸出的shape為(13,13,256);
9、使用步長為2的最大池化層進行池化,此時輸出的shape為(6,6,256);
10、兩個全連接層,最后輸出為1000類

細節部分舉例:

第一層
第一層輸入數據為原始圖像的2242243的圖像,這個圖像被11113(3代表 深度,例如RGB的3通道)的卷積核進行卷積運算,卷積核對原始圖像的每次 卷積都會生成一個新的像素。 卷積核的步長為4個像素,朝著橫向和縱向這兩個方向進行卷積。 由此,會生成新的像素; 第一層有96個卷積核,所以就會形成555596個像素層。 pool池化層:這些像素層還需要經過pool運算(池化運算)的處理,池化運 算的尺度由預先設定為33,運算的步長為2,則池化后的圖像的尺寸為: (55-3)/2+1=27。即經過池化處理過的規模為2727*96.

代碼實現:

網絡主體部分:(AlexNet.py)

from keras.models import Sequential
from keras.layers import Dense,Activation,Conv2D,MaxPooling2D,Flatten,Dropout,BatchNormalization
from keras.datasets import mnist
from keras.utils import np_utils
from keras.optimizers import Adam# 注意,為了加快收斂,我將每個卷積層的filter減半,全連接層減為1024
def AlexNet(input_shape=(224,224,3),output_shape=2):# AlexNetmodel = Sequential()# 使用步長為4x4,大小為11的卷積核對圖像進行卷積,輸出的特征層為96層,輸出的shape為(55,55,96);# 所建模型后輸出為48特征層model.add(Conv2D(filters=48, kernel_size=(11,11),strides=(4,4),padding='valid',input_shape=input_shape,activation='relu'))model.add(BatchNormalization())# 使用步長為2的最大池化層進行池化,此時輸出的shape為(27,27,96)# 所建模型后輸出為48特征層model.add(MaxPooling2D(pool_size=(3,3), strides=(2,2), padding='valid'))# 使用步長為1x1,大小為5的卷積核對圖像進行卷積,輸出的特征層為256層,輸出的shape為(27,27,256);# 所建模型后輸出為128特征層model.add(Conv2D(filters=128, kernel_size=(5,5), strides=(1,1), padding='same',activation='relu'))model.add(BatchNormalization())# 使用步長為2的最大池化層進行池化,此時輸出的shape為(13,13,256);# 所建模型后輸出為128特征層model.add(MaxPooling2D(pool_size=(3,3),strides=(2,2),padding='valid'))# 使用步長為1x1,大小為3的卷積核對圖像進行卷積,輸出的特征層為384層,輸出的shape為(13,13,384);# 所建模型后輸出為192特征層model.add(Conv2D(filters=192, kernel_size=(3,3),strides=(1,1), padding='same', activation='relu')) # 使用步長為1x1,大小為3的卷積核對圖像進行卷積,輸出的特征層為384層,輸出的shape為(13,13,384);# 所建模型后輸出為192特征層model.add(Conv2D(filters=192, kernel_size=(3,3), strides=(1,1), padding='same', activation='relu'))# 使用步長為1x1,大小為3的卷積核對圖像進行卷積,輸出的特征層為256層,輸出的shape為(13,13,256);# 所建模型后輸出為128特征層model.add(Conv2D(filters=128, kernel_size=(3,3), strides=(1,1), padding='same', activation='relu'))# 使用步長為2的最大池化層進行池化,此時輸出的shape為(6,6,256);# 所建模型后輸出為128特征層model.add(MaxPooling2D(pool_size=(3,3), strides=(2,2), padding='valid'))# 兩個全連接層,最后輸出為1000類,這里改為2類(貓和狗)# 縮減為1024model.add(Flatten())model.add(Dense(1024, activation='relu'))model.add(Dropout(0.25))model.add(Dense(1024, activation='relu'))model.add(Dropout(0.25))model.add(Dense(output_shape, activation='softmax'))return model

圖像預處理部分:(utils.py)

import matplotlib.image as mpimg
import numpy as np
import cv2
import tensorflow as tf
from tensorflow.python.ops import array_opsdef load_image(path):# 讀取圖片,rgbimg = mpimg.imread(path)# 將圖片修剪成中心的正方形short_edge = min(img.shape[:2])yy = int((img.shape[0] - short_edge) / 2)xx = int((img.shape[1] - short_edge) / 2)crop_img = img[yy: yy + short_edge, xx: xx + short_edge]return crop_imgdef resize_image(image, size):with tf.name_scope('resize_image'):images = []for i in image:i = cv2.resize(i, size)images.append(i)images = np.array(images)return imagesdef print_answer(argmax):with open("./data/model/index_word.txt","r",encoding='utf-8') as f:synset = [l.split(";")[1][:-1] for l in f.readlines()]# print(synset[argmax])return synset[argmax]

訓練部分:(train.py)

from keras.callbacks import TensorBoard, ModelCheckpoint, ReduceLROnPlateau, EarlyStopping
from keras.utils import np_utils
from keras.optimizers import Adam
from model.AlexNet import AlexNet
import numpy as np
import utils
import cv2
from keras import backend as K
#K.set_image_dim_ordering('tf')
K.image_data_format() == 'channels_first'def generate_arrays_from_file(lines,batch_size):# 獲取總長度n = len(lines)i = 0while 1:X_train = []Y_train = []# 獲取一個batch_size大小的數據for b in range(batch_size):if i==0:np.random.shuffle(lines)name = lines[i].split(';')[0]# 從文件中讀取圖像img = cv2.imread(r".\data\image\train" + '/' + name)img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)img = img/255X_train.append(img)Y_train.append(lines[i].split(';')[1])# 讀完一個周期后重新開始i = (i+1) % n# 處理圖像X_train = utils.resize_image(X_train,(224,224))X_train = X_train.reshape(-1,224,224,3)Y_train = np_utils.to_categorical(np.array(Y_train),num_classes= 2)   yield (X_train, Y_train)if __name__ == "__main__":# 模型保存的位置log_dir = "./logs/"# 打開數據集的txtwith open(r".\data\dataset.txt","r") as f:lines = f.readlines()# 打亂行,這個txt主要用于幫助讀取數據來訓練# 打亂的數據更有利于訓練np.random.seed(10101)np.random.shuffle(lines)np.random.seed(None)# 90%用于訓練,10%用于估計。num_val = int(len(lines)*0.1)num_train = len(lines) - num_val# 建立AlexNet模型model = AlexNet()# 保存的方式,3代保存一次checkpoint_period1 = ModelCheckpoint(log_dir + 'ep{epoch:03d}-loss{loss:.3f}-val_loss{val_loss:.3f}.h5',monitor='acc', save_weights_only=False, save_best_only=True, period=3)# 學習率下降的方式,acc三次不下降就下降學習率繼續訓練reduce_lr = ReduceLROnPlateau(monitor='acc', factor=0.5, patience=3, verbose=1)# 是否需要早停,當val_loss一直不下降的時候意味著模型基本訓練完畢,可以停止early_stopping = EarlyStopping(monitor='val_loss', min_delta=0, patience=10, verbose=1)# 交叉熵model.compile(loss = 'categorical_crossentropy',optimizer = Adam(lr=1e-3),metrics = ['accuracy'])# 一次的訓練集大小batch_size = 128print('Train on {} samples, val on {} samples, with batch size {}.'.format(num_train, num_val, batch_size))# 開始訓練model.fit_generator(generate_arrays_from_file(lines[:num_train], batch_size),steps_per_epoch=max(1, num_train//batch_size),validation_data=generate_arrays_from_file(lines[num_train:], batch_size),validation_steps=max(1, num_val//batch_size),epochs=50,initial_epoch=0,callbacks=[checkpoint_period1, reduce_lr])model.save_weights(log_dir+'last1.h5')#保存模型

預測部分:(predict.py)

import numpy as np
import utils
import cv2
from keras import backend as K
from model.AlexNet import AlexNet# K.set_image_dim_ordering('tf')
K.image_data_format() == 'channels_first'if __name__ == "__main__":model = AlexNet()model.load_weights("./logs/last1.h5")img = cv2.imread("./test2.jpg")img_RGB = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)img_nor = img_RGB/255img_nor = np.expand_dims(img_nor,axis = 0)img_resize = utils.resize_image(img_nor,(224,224))#utils.print_answer(np.argmax(model.predict(img)))print('the answer is: ',utils.print_answer(np.argmax(model.predict(img_resize))))cv2.imshow("ooo",img)cv2.waitKey(0)

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

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

相關文章

PHP對象傳遞方式

<?phpheader(content-type:text/html;charsetutf-8);class Person{public $name;public $age;}$p1 new Person;$p1->name 金角大王;$p1->age 400;//這個地方&#xff0c;到底怎樣?$p2 $p1;$p2->name 銀角大王;echo <pre>;echo p1 name . $p1->n…

微軟Azure CDN現已普遍可用

微軟宣布Azure CDN一般可用&#xff08;GA&#xff09;&#xff0c;客戶現在可以從微軟的全球CDN網絡提供內容。最新版本是對去年五月份發布的公眾預覽版的跟進。\\今年5月&#xff0c;微軟與Verizon和Akamai一起推出了原生CDN產品。現在推出了GA版本&#xff0c;根據發布博文所…

數據科學生命周期_數據科學項目生命周期第1部分

數據科學生命周期This is series of how to developed data science project.這是如何開發數據科學項目的系列。 This is part 1.這是第1部分。 All the Life-cycle In A Data Science Projects-1. Data Analysis and visualization.2. Feature Engineering.3. Feature Selec…

Keras框架:VGG網絡代碼實現

VGG概念&#xff1a; VGG之所以經典&#xff0c;在于它首次將深度學習做得非常“深”&#xff0c;達 到了16-19層&#xff0c;同時&#xff0c;它用了非常“小”的卷積核&#xff08;3X3&#xff09;。 網絡框架&#xff1a; VGG的結構&#xff1a; 1、一張原始圖片被resize…

Django筆記1

內容整理1.創建django工程django-admin startproject 工程名2.創建APPcd 工程名python manage.py startapp cmdb3.靜態文件project.settings.pySTATICFILES_dirs {os.path.join(BASE_DIR, static),}4.模板路徑DIRS > [os.path.join(BASE_DIR, templates),]5.settings中mid…

BZOJ 2003 [Hnoi2010]Matrix 矩陣

題目鏈接 https://www.lydsy.com/JudgeOnline/problem.php?id2003 題解 考慮搜索。 確定了第一行和第一列&#xff0c;那么就確定了整個矩陣&#xff0c;因此搜索的范圍可以降到399個位置。 首先搜索第一行&#xff0c;顯然每個不是第一行第一列的位置都可以由三個位置唯一確定…

Keras框架:resent50代碼實現

Residual net概念 概念&#xff1a; Residual net(殘差網絡)&#xff1a;將靠前若干層的某一層數據輸出直接跳過多層引入到后面數據層的輸入 部分。 殘差神經單元&#xff1a;假定某段神經網絡的輸入是x&#xff0c;期望輸出是H(x)&#xff0c;如果我們直接將輸入x傳到輸出作…

MySQL數據庫的回滾失敗(JAVA)

這幾天在學習MySQL數據的知識&#xff0c;有一個小測試&#xff0c;用來測試數據庫的提交和回滾。 剛開始的時候真的沒把這個當回事&#xff0c;按照正常的步驟來講的話&#xff0c;如下所示&#xff0c;加載驅動&#xff0c;獲取數據庫的連接&#xff0c;并且把數據庫的自動提…

條件概率分布_條件概率

條件概率分布If you’re currently in the job market or looking to switch careers, you’ve probably noticed an increase in popularity of Data Science jobs. In 2019, LinkedIn ranked “data scientist” the №1 most promising job in the U.S. based on job openin…

MP實戰系列(十七)之樂觀鎖插件

聲明&#xff0c;目前只是僅僅針對3.0以下版本&#xff0c;2.0以上版本。 意圖&#xff1a; 當要更新一條記錄的時候&#xff0c;希望這條記錄沒有被別人更新 樂觀鎖實現方式&#xff1a; 取出記錄時&#xff0c;獲取當前version 更新時&#xff0c;帶上這個version 執行更新時…

二叉樹刪除節點,(查找二叉樹最大值節點)

從根節點往下分別查找左子樹和右子樹的最大節點&#xff0c;再比較左子樹&#xff0c;右子樹&#xff0c;根節點的大小得到結果&#xff0c;在得到左子樹和右子樹最大節點的過程相似&#xff0c;因此可以采用遞歸的 //樹節點結構 public class TreeNode { TreeNode left;…

Tensorflow框架:InceptionV3網絡概念及實現

卷積神經網絡遷移學習-Inception ? 有論文依據表明可以保留訓練好的inception模型中所有卷積層的參數&#xff0c;只替換最后一層全連接層。在最后 這一層全連接層之前的網絡稱為瓶頸層。 ? 原理&#xff1a;在訓練好的inception模型中&#xff0c;因為將瓶頸層的輸出再通過…

View詳解(4)

在上文中我們簡單介紹了Canvas#drawCircle()的使用方式&#xff0c;以及Paint#setStyle(),Paint#setStrokeWidth(),Paint#setColor()等相關函數&#xff0c;不知道小伙伴們了解了多少&#xff1f;那么是不是所有的圖形都能通過圓來描述呢&#xff1f;當然不行&#xff0c;那么熟…

成為一名真正的數據科學家有多困難

Data Science and Machine Learning are hard sports to play. It’s difficult enough to motivate yourself to sit down and learn some maths, let alone to becoming an expert on the matter.數據科學和機器學習是一項艱巨的運動。 激勵自己坐下來學習一些數學知識是非常…

Ubuntu 裝機軟件

Ubuntu16.04 軟件商店閃退打不開 sudo apt-get updatesudo apt-get dist-upgrade# 應該執行一下更新就好&#xff0c;不需要重新安裝軟件中心 sudo apt-get install –reinstall software-center Ubuntu16.04 深度美化 https://www.jianshu.com/p/4bd2d9b1af41 Ubuntu18.04 美化…

數據分析中的統計概率_了解統計和概率:成為專家數據科學家

數據分析中的統計概率Data Science is a hot topic nowadays. Organizations consider data scientists to be the Crme de la crme. Everyone in the industry is talking about the potential of data science and what data scientists can bring in their BigTech and FinT…

Keras框架:Mobilenet網絡代碼實現

Mobilenet概念&#xff1a; MobileNet模型是Google針對手機等嵌入式設備提出的一種輕量級的深層神經網絡&#xff0c;其使用的核心思想便是depthwise separable convolution。 Mobilenet思想&#xff1a; 通俗地理解就是3x3的卷積核厚度只有一層&#xff0c;然后在輸入張量上…

clipboard 在 vue 中的使用

簡介 頁面中用 clipboard 可以進行復制粘貼&#xff0c;clipboard能將內容直接寫入剪切板 安裝 npm install --save clipboard 使用方法一 <template><span>{{ code }}</span><iclass"el-icon-document"title"點擊復制"click"co…

數據驅動開發_開發數據驅動的股票市場投資方法

數據驅動開發Data driven means that your decision are driven by data and not by emotions. This approach can be very useful in stock market investment. Here is a summary of a data driven approach which I have been taking recently數據驅動意味著您的決定是由數據…

前端之sublime text配置

接下來我們來了解如何調整sublime text的配置&#xff0c;可能很多同學下載sublime text的時候就是把它當成記事本來使用&#xff0c;也就是沒有做任何自定義的配置&#xff0c;做一些自定義的配置可以讓sublime text更適合我們的開發習慣。 那么在利用剛才的命令面板我們怎么打…