Keras 實現AlexNet
阿新 • • 發佈:2018-11-05
from keras.models import Sequential from keras.layers import Dense, Flatten, Dropout from keras.layers.convolutional import Conv2D, MaxPooling2D from keras.utils.np_utils import to_categorical import numpy as np seed = 7 np.random.seed(seed) # 建立模型序列 model = Sequential() #第一層卷積網路,使用96個卷積核,大小為11x11步長為4, 要求輸入的圖片為227x227, 3個通道,不加邊,啟用函式使用relu model.add(Conv2D(96, (11, 11), strides=(1, 1), input_shape=(28, 28, 1), padding='same', activation='relu', kernel_initializer='uniform')) # 池化層 model.add(MaxPooling2D(pool_size=(3, 3), strides=(2, 2))) # 第二層加邊使用256個5x5的卷積核,加邊,啟用函式為relu model.add(Conv2D(256, (5, 5), strides=(1, 1), padding='same', activation='relu', kernel_initializer='uniform')) #使用池化層,步長為2 model.add(MaxPooling2D(pool_size=(3, 3), strides=(2, 2))) # 第三層卷積,大小為3x3的卷積核使用384個 model.add(Conv2D(384, (3, 3), strides=(1, 1), padding='same', activation='relu', kernel_initializer='uniform')) # 第四層卷積,同第三層 model.add(Conv2D(384, (3, 3), strides=(1, 1), padding='same', activation='relu', kernel_initializer='uniform')) # 第五層卷積使用的卷積核為256個,其他同上 model.add(Conv2D(256, (3, 3), strides=(1, 1), padding='same', activation='relu', kernel_initializer='uniform')) model.add(MaxPooling2D(pool_size=(3, 3), strides=(2, 2))) model.add(Flatten()) model.add(Dense(4096, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(4096, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(10, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy']) model.summary()