本文目錄一覽:
怎樣用python構建一個卷積神經網絡
用keras框架較為方便
首先安裝anaconda,然後通過pip安裝keras
以下轉自wphh的博客。
#coding:utf-8
”’
GPU run command:
THEANO_FLAGS=mode=FAST_RUN,device=gpu,floatX=float32 python cnn.py
CPU run command:
python cnn.py
2016.06.06更新:
這份代碼是keras開發初期寫的,當時keras還沒有現在這麼流行,文檔也還沒那麼豐富,所以我當時寫了一些簡單的教程。
現在keras的API也發生了一些的變化,建議及推薦直接上keras.io看更加詳細的教程。
”’
#導入各種用到的模塊組件
from __future__ import absolute_import
from __future__ import print_function
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation, Flatten
from keras.layers.advanced_activations import PReLU
from keras.layers.convolutional import Convolution2D, MaxPooling2D
from keras.optimizers import SGD, Adadelta, Adagrad
from keras.utils import np_utils, generic_utils
from six.moves import range
from data import load_data
import random
import numpy as np
np.random.seed(1024) # for reproducibility
#加載數據
data, label = load_data()
#打亂數據
index = [i for i in range(len(data))]
random.shuffle(index)
data = data[index]
label = label[index]
print(data.shape[0], ‘ samples’)
#label為0~9共10個類別,keras要求格式為binary class matrices,轉化一下,直接調用keras提供的這個函數
label = np_utils.to_categorical(label, 10)
###############
#開始建立CNN模型
###############
#生成一個model
model = Sequential()
#第一個卷積層,4個卷積核,每個卷積核大小5*5。1表示輸入的圖片的通道,灰度圖為1通道。
#border_mode可以是valid或者full,具體看這裡說明:
#激活函數用tanh
#你還可以在model.add(Activation(‘tanh’))後加上dropout的技巧: model.add(Dropout(0.5))
model.add(Convolution2D(4, 5, 5, border_mode=’valid’,input_shape=(1,28,28)))
model.add(Activation(‘tanh’))
#第二個卷積層,8個卷積核,每個卷積核大小3*3。4表示輸入的特徵圖個數,等於上一層的卷積核個數
#激活函數用tanh
#採用maxpooling,poolsize為(2,2)
model.add(Convolution2D(8, 3, 3, border_mode=’valid’))
model.add(Activation(‘tanh’))
model.add(MaxPooling2D(pool_size=(2, 2)))
#第三個卷積層,16個卷積核,每個卷積核大小3*3
#激活函數用tanh
#採用maxpooling,poolsize為(2,2)
model.add(Convolution2D(16, 3, 3, border_mode=’valid’))
model.add(Activation(‘relu’))
model.add(MaxPooling2D(pool_size=(2, 2)))
#全連接層,先將前一層輸出的二維特徵圖flatten為一維的。
#Dense就是隱藏層。16就是上一層輸出的特徵圖個數。4是根據每個卷積層計算出來的:(28-5+1)得到24,(24-3+1)/2得到11,(11-3+1)/2得到4
#全連接有128個神經元節點,初始化方式為normal
model.add(Flatten())
model.add(Dense(128, init=’normal’))
model.add(Activation(‘tanh’))
#Softmax分類,輸出是10類別
model.add(Dense(10, init=’normal’))
model.add(Activation(‘softmax’))
#############
#開始訓練模型
##############
#使用SGD + momentum
#model.compile里的參數loss就是損失函數(目標函數)
sgd = SGD(lr=0.05, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss=’categorical_crossentropy’, optimizer=sgd,metrics=[“accuracy”])
#調用fit方法,就是一個訓練過程. 訓練的epoch數設為10,batch_size為100.
#數據經過隨機打亂shuffle=True。verbose=1,訓練過程中輸出的信息,0、1、2三種方式都可以,無關緊要。show_accuracy=True,訓練時每一個epoch都輸出accuracy。
#validation_split=0.2,將20%的數據作為驗證集。
model.fit(data, label, batch_size=100, nb_epoch=10,shuffle=True,verbose=1,validation_split=0.2)
“””
#使用data augmentation的方法
#一些參數和調用的方法,請看文檔
datagen = ImageDataGenerator(
featurewise_center=True, # set input mean to 0 over the dataset
samplewise_center=False, # set each sample mean to 0
featurewise_std_normalization=True, # divide inputs by std of the dataset
samplewise_std_normalization=False, # divide each input by its std
zca_whitening=False, # apply ZCA whitening
rotation_range=20, # randomly rotate images in the range (degrees, 0 to 180)
width_shift_range=0.2, # randomly shift images horizontally (fraction of total width)
height_shift_range=0.2, # randomly shift images vertically (fraction of total height)
horizontal_flip=True, # randomly flip images
vertical_flip=False) # randomly flip images
# compute quantities required for featurewise normalization
# (std, mean, and principal components if ZCA whitening is applied)
datagen.fit(data)
for e in range(nb_epoch):
print(‘-‘*40)
print(‘Epoch’, e)
print(‘-‘*40)
print(“Training…”)
# batch train with realtime data augmentation
progbar = generic_utils.Progbar(data.shape[0])
for X_batch, Y_batch in datagen.flow(data, label):
loss,accuracy = model.train(X_batch, Y_batch,accuracy=True)
progbar.add(X_batch.shape[0], values=[(“train loss”, loss),(“accuracy:”, accuracy)] )
“””
Python keras構建CNN
data.py:
#coding:utf-8
“””
Author:wepon
Source:
“””
import os
from PIL import Image
import numpy as np
#讀取文件夾mnist下的42000張圖片,圖片為灰度圖,所以為1通道,圖像大小28*28
#如果是將彩色圖作為輸入,則將1替換為3,並且data[i,:,:,:] = arr改為data[i,:,:,:] = [arr[:,:,0],arr[:,:,1],arr[:,:,2]]
def load_data():
data = np.empty((42000,1,28,28),dtype=”float32″)
label = np.empty((42000,),dtype=”uint8″)
imgs = os.listdir(“./mnist”)
num = len(imgs)
for i in range(num):
img = Image.open(“./mnist/”+imgs[i])
arr = np.asarray(img,dtype=”float32″)
data[i,:,:,:] = arr
label[i] = int(imgs[i].split(‘.’)[0])
return data,label
由於Keras系統升級,cnn.py代碼調整如下:
#coding:utf-8
”’
GPU run command:
THEANO_FLAGS=mode=FAST_RUN,device=gpu,floatX=float32 python cnn.py
CPU run command:
python cnn.py
”’
#導入各種用到的模塊組件
from __future__ import absolute_import
from __future__ import print_function
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation, Flatten
from keras.layers.advanced_activations import PReLU
from keras.layers.convolutional import Convolution2D, MaxPooling2D
from keras.optimizers import SGD, Adadelta, Adagrad
from keras.utils import np_utils, generic_utils
from six.moves import range
from data import load_data
import random
#加載數據
data, label = load_data()
#打亂數據
index = [i for i in range(len(data))]
random.shuffle(index)
data = data[index]
label = label[index]
print(data.shape[0], ‘ samples’)
#label為0~9共10個類別,keras要求格式為binary class matrices,轉化一下,直接調用keras提供的這個函數
label = np_utils.to_categorical(label, 10)
###############
#開始建立CNN模型
###############
#生成一個model
model = Sequential()
#第一個卷積層,4個卷積核,每個卷積核大小5*5。1表示輸入的圖片的通道,灰度圖為1通道。
#border_mode可以是valid或者full,具體看這裡說明:
#激活函數用tanh
#你還可以在model.add(Activation(‘tanh’))後加上dropout的技巧: model.add(Dropout(0.5))
model.add(Convolution2D(4, 5, 5, border_mode=’valid’, input_shape=(1,28,28)))
model.add(Activation(‘tanh’))
#第二個卷積層,8個卷積核,每個卷積核大小3*3。4表示輸入的特徵圖個數,等於上一層的卷積核個數
#激活函數用tanh
#採用maxpooling,poolsize為(2,2)
model.add(Convolution2D(8, 3, 3, border_mode=’valid’))
model.add(Activation(‘tanh’))
model.add(MaxPooling2D(pool_size=(2, 2)))
#第三個卷積層,16個卷積核,每個卷積核大小3*3
#激活函數用tanh
#採用maxpooling,poolsize為(2,2)
model.add(Convolution2D(16, 3, 3, border_mode=’valid’))
model.add(Activation(‘tanh’))
model.add(MaxPooling2D(pool_size=(2, 2)))
#全連接層,先將前一層輸出的二維特徵圖flatten為一維的。
#Dense就是隱藏層。16就是上一層輸出的特徵圖個數。4是根據每個卷積層計算出來的:(28-5+1)得到24,(24-3+1)/2得到11,(11-3+1)/2得到4
#全連接有128個神經元節點,初始化方式為normal
model.add(Flatten())
model.add(Dense(128, init=’normal’))
model.add(Activation(‘tanh’))
#Softmax分類,輸出是10類別
model.add(Dense(10, init=’normal’))
model.add(Activation(‘softmax’))
#############
#開始訓練模型
##############
#使用SGD + momentum
#model.compile里的參數loss就是損失函數(目標函數)
sgd = SGD(l2=0.0,lr=0.05, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss=’categorical_crossentropy’, optimizer=sgd,class_mode=”categorical”)
#調用fit方法,就是一個訓練過程. 訓練的epoch數設為10,batch_size為100.
#數據經過隨機打亂shuffle=True。verbose=1,訓練過程中輸出的信息,0、1、2三種方式都可以,無關緊要。show_accuracy=True,訓練時每一個epoch都輸出accuracy。
#validation_split=0.2,將20%的數據作為驗證集。
model.fit(data, label, batch_size=100, nb_epoch=10,shuffle=True,verbose=1,show_accuracy=True,validation_split=0.2)
“””
#使用data augmentation的方法
#一些參數和調用的方法,請看文檔
datagen = ImageDataGenerator(
featurewise_center=True, # set input mean to 0 over the dataset
samplewise_center=False, # set each sample mean to 0
featurewise_std_normalization=True, # divide inputs by std of the dataset
samplewise_std_normalization=False, # divide each input by its std
zca_whitening=False, # apply ZCA whitening
rotation_range=20, # randomly rotate images in the range (degrees, 0 to 180)
width_shift_range=0.2, # randomly shift images horizontally (fraction of total width)
height_shift_range=0.2, # randomly shift images vertically (fraction of total height)
horizontal_flip=True, # randomly flip images
vertical_flip=False) # randomly flip images
# compute quantities required for featurewise normalization
# (std, mean, and principal components if ZCA whitening is applied)
datagen.fit(data)
for e in range(nb_epoch):
print(‘-‘*40)
print(‘Epoch’, e)
print(‘-‘*40)
print(“Training…”)
# batch train with realtime data augmentation
progbar = generic_utils.Progbar(data.shape[0])
for X_batch, Y_batch in datagen.flow(data, label):
loss,accuracy = model.train(X_batch, Y_batch,accuracy=True)
progbar.add(X_batch.shape[0], values=[(“train loss”, loss),(“accuracy:”, accuracy)] )
“””
CNN詳解-基於python基礎庫實現的簡單CNN
CNN,即卷積神經網絡,主要用於圖像識別,分類。由輸入層,卷積層,池化層,全連接層(Affline層),Softmax層疊加而成。卷積神經網絡中還有一個非常重要的結構:過濾器,它作用於層與層之間(卷積層與池化層),決定了怎樣對數據進行卷積和池化。下面先直觀理解下卷積和池化
二維卷積
三維卷積
池化
好了,知道卷積池化,下面就來實現最簡單的一個卷積網絡:
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/244304.html