keras 搭建簡單模型python
扁平化model.add(Flatten()) 能夠用 全局平均池化代替 model.add(GlobalAveragePooling2D())網絡
方法1app
# 序列模型 # 序列模型屬於通用模型的一種,由於很常見,因此這裏單獨列出來進行介紹,這種模型各層之間 # 是依次順序的線性關係,在第k層和第k+1層之間能夠加上各類元素來構造神經網絡 # 這些元素能夠經過一個列表來制定,而後做爲參數傳遞給序列模型來生成相應的模型 from keras.models import Sequential from keras.layers import Dense from keras.layers import Activation # Dense至關於構建一個全鏈接層,32指的是全鏈接層上面神經元的個數 layers = [Dense(32, input_shape=(784,)), Activation('relu'), Dense(10), Activation('softmax')] model = Sequential(layers)
#輸出模型結構 model.summary()
方法2 ide
效果同方法1同樣函數
from keras.models import Sequential from keras.layers import Dense from keras.layers import Activation model = Sequential() model.add(Dense(32, input_shape=(784,))) model.add(Activation('relu')) model.add(Dense(10)) model.add(Activation('softmax')) model.summary()
一個稍複雜的例子學習
# 通用模型 # 通用模型能夠用來設計很是複雜、任意拓撲結構的神經網絡,例若有向無環圖網絡 # 相似於序列模型,通用模型經過函數化的應用接口來定義模型 # 使用函數化的應用接口有好多好處,好比:決定函數執行結果的惟一要素是其返回值,而決定 # 返回值的惟一要素則是其參數,這大大減輕了代碼測試的工做量 # 在通用模型中,定義的時候,從輸入的多維矩陣開始,而後定義各層及其要素,最後定義輸出層 # 將輸入層和輸出層做爲參數歸入通用模型中就能夠定義一個模型對象 from keras.layers import Input from keras.layers import Dense from keras.models import Model # 定義輸入層 input = Input(shape=(784,)) # 定義各個鏈接層,假設從輸入層開始,定義兩個隱含層,都有64個神經元,都使用relu激活函數 x = Dense(64, activation='relu')(input) x = Dense(64, activation='relu')(x) # 定義輸出層,使用最近的隱含層做爲參數 y = Dense(10, activation='softmax')(x) # 全部要素都齊備之後,就能夠定義模型對象了,參數很簡單,分別是輸入和輸出,其中包含了 # 中間的各類信息 model = Model(inputs=input, outputs=y) # 當模型對象定義完成以後,就能夠進行編譯了,並對數據進行擬合,擬合的時候也有兩個參數 # 分別對應於輸入和輸出 model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy']) model.fit(data, labels)
一個更加複雜的例子測試
import numpy as np from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense from keras.layers import Dropout from keras.layers import Flatten from keras.layers.convolutional import Conv2D from keras.layers.convolutional import MaxPooling2D # 先讀入數據 (X_train, y_train), (X_test, y_test) = mnist.load_data("../test_data_home") # 看一下數據集的樣子 print(X_train[0].shape) print(y_train[0]) # 下面把訓練集中的手寫黑白字體變成標準的四維張量形式,即(樣本數量,長,寬,1) # 並把像素值變成浮點格式 X_train = X_train.reshape(X_train.shape[0], 28, 28, 1).astype('float32') X_test = X_test.reshape(X_test.shape[0], 28, 28, 1).astype('float32') # 因爲每一個像素值都介於0到255,因此這裏統一除以255,把像素值控制在0-1範圍 X_train /= 255 X_test /= 255 # 因爲輸入層須要10個節點,因此最好把目標數字0-9作成One Hot編碼的形式 def tran_y(y): y_ohe = np.zeros(10) y_ohe[y] = 1 return y_ohe # 把標籤用One Hot編碼從新表示一下 y_train_ohe = np.array([tran_y(y_train[i]) for i in range(len(y_train))]) y_test_ohe = np.array([tran_y(y_test[i]) for i in range(len(y_test))]) # 搭建卷積神經網絡 model = Sequential() # 添加一層卷積層,構造64個過濾器,每一個過濾器覆蓋範圍是3*3*1 # 過濾器步長爲1,圖像四周補一圈0,並用relu進行非線性變化 model.add(Conv2D(filters=64, kernel_size=(3, 3), strides=(1, 1), padding='same', input_shape=(28, 28, 1), activation='relu')) # 添加一層最大池化層 model.add(MaxPooling2D(pool_size=(2, 2))) # 設立Dropout層,Dropout的機率爲0.5 model.add(Dropout(0.5)) # 重複構造,搭建深度網絡 model.add(Conv2D(128, kernel_size=(3, 3), strides=(1, 1), padding='same', activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.5)) model.add(Conv2D(256, kernel_size=(3, 3), strides=(1, 1), padding='same', activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.5)) # 把當前層節點展平 model.add(Flatten()) # 構造全鏈接層神經網絡層 model.add(Dense(128, activation='relu')) model.add(Dense(64, activation='relu')) model.add(Dense(32, activation='relu')) model.add(Dense(10, activation='softmax')) # 定義損失函數,通常來講分類問題的損失函數都選擇採用交叉熵 model.compile(loss='categorical_crossentropy', optimizer='adagrad', metrics=['accuracy']) # 放入批量樣本,進行訓練 model.fit(X_train, y_train_ohe, validation_data=(X_test, y_test_ohe) , epochs=20, batch_size=128) # 在測試集上評價模型的準確率 # verbose : 進度表示方式。0表示不顯示數據,1表示顯示進度條 scores = model.evaluate(X_test, y_test_ohe, verbose=0)
遷移學習的例子字體
# 使用遷移學習的思想,以VGG16做爲模板搭建模型,訓練識別手寫字體 # 引入VGG16模塊 from keras.applications.vgg16 import VGG16 # 其次加載其餘模塊 from keras.layers import Input from keras.layers import Flatten from keras.layers import Dense from keras.layers import Dropout from keras.models import Model from keras.optimizers import SGD # 加載字體庫做爲訓練樣本 from keras.datasets import mnist # 加載OpenCV(在命令行中窗口中輸入pip install opencv-python),這裏爲了後期對圖像的處理, # 你們使用pip install C:\Users\28542\Downloads\opencv_python-3.4.1+contrib-cp35-cp35m-win_amd64.whl # 好比尺寸變化和Channel變化。這些變化是爲了使圖像知足VGG16所須要的輸入格式 import cv2 import h5py as h5py import numpy as np # 創建一個模型,其類型是Keras的Model類對象,咱們構建的模型會將VGG16頂層去掉,只保留其他的網絡 # 結構。這裏用include_top = False代表咱們遷移除頂層之外的其他網絡結構到本身的模型中(意思是頂層不用) # weights='imagenet'使用imagenet大賽第一名的參數。 # VGG模型對於輸入圖像數據要求高寬至少爲48個像素點,因爲硬件配置限制,咱們選用48個像素點而不是原來 # VGG16所採用的224個像素點。即便這樣仍然須要24GB以上的內存,或者使用數據生成器 model_vgg = VGG16(include_top=False, weights='imagenet', input_shape=(48, 48, 3)) for layer in model_vgg.layers:#遍歷vgg模型的每一層 layer.trainable = False #每層的,參數都設置爲不可變動的,使用初始參數 model = Flatten(name='flatten')(model_vgg.output) # 扁平化,將vgg模型的輸出。當作本身模型的輸入 model = Dense(4096, activation='relu', name='fc1')(model) model = Dense(4096, activation='relu', name='fc2')(model) model = Dropout(0.5)(model) model = Dense(10, activation='softmax')(model) model_vgg_mnist = Model(inputs=model_vgg.input, outputs=model, name='vgg16') # 打印模型結構,包括所須要的參數 model_vgg_mnist.summary() model_vgg = VGG16(include_top=False, weights='imagenet', input_shape=(224, 224, 3)) for layer in model_vgg.layers: layer.trainable = False model = Flatten()(model_vgg.output) model = Dense(4096, activation='relu', name='fc1')(model) model = Dense(4096, activation='relu', name='fc2')(model) model = Dropout(0.5)(model) model = Dense(10, activation='softmax', name='prediction')(model) model_vgg_mnist_pretrain = Model(model_vgg.input, model, name='vgg16_pretrain') model_vgg_mnist_pretrain.summary() # 新的模型不須要訓練原有卷積結構裏面的1471萬個參數,可是注意參數仍是來自於最後輸出層前的兩個 # 全鏈接層,一共有1.2億個參數須要訓練 sgd = SGD(lr=0.05, decay=1e-5) #sgd 隨機梯度降低法,做爲優化器 model_vgg_mnist.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy']) # 由於VGG16對網絡輸入層的要求,咱們用OpenCV把圖像從32*32變成48*48,函數cv2.COLOR_GRAY2RGB 把黑白圖像轉成RGB圖像 # 並把訓練數據轉化成張量形式,供keras輸入 (X_train, y_train), (X_test, y_test) = mnist.load_data("../test_data_home") X_train, y_train = X_train[:10000], y_train[:10000] X_test, y_test = X_test[:1000], y_test[:1000] X_train = [cv2.cvtColor(cv2.resize(i, (48, 48)), cv2.COLOR_GRAY2RGB) for i in X_train] X_train = np.concatenate([arr[np.newaxis] for arr in X_train]).astype('float32') X_test = [cv2.cvtColor(cv2.resize(i, (48, 48)), cv2.COLOR_GRAY2RGB) for i in X_test] X_test = np.concatenate([arr[np.newaxis] for arr in X_test]).astype('float32') print(X_train.shape) print(X_test.shape) X_train = X_train / 255 X_test = X_test / 255 def tran_y(y): y_ohe = np.zeros(10) y_ohe[y] = 1 return y_ohe y_train_ohe = np.array([tran_y(y_train[i]) for i in range(len(y_train))]) y_test_ohe = np.array([tran_y(y_test[i]) for i in range(len(y_test))]) model_vgg_mnist.fit(X_train, y_train_ohe, validation_data=(X_test, y_test_ohe), epochs=100, batch_size=50)