keras 手動搭建alexnet並訓練mnist資料集

dota2職業選手發表於2020-11-27
# -*- coding: utf-8 -*-
# @Time    : 2020/11/26 10:11 PM
# @Author  : yuhao
# @Email   : hhhhh
# @File    : alexnet.py
import numpy as np
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
from keras.callbacks import ModelCheckpoint
from keras.utils import to_categorical

##-------------------1.讀取本地mnist資料集-------------------
mnist = np.load('./mnist.npz')
x_train, y_train = mnist['x_train'], mnist['y_train']
x_test, y_test = mnist['x_test'], mnist['y_test']
mnist.close()
#新增維度
x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)
x_test = x_test.reshape(x_test.shape[0], 28, 28, 1)
#將標籤轉化為one-hot編碼
y_train = to_categorical(y_train, num_classes=10)
y_test = to_categorical(y_test, num_classes=10)

##-------------------2.搭建keras序貫型網路模型-------------------
model = Sequential()
#conv1
model.add(Conv2D(96, (11, 11), strides=(1, 1),  padding='same', activation='relu', input_shape=(28, 28, 1)))
model.add(MaxPooling2D(pool_size=(3, 3), strides=(2, 2)))
#conv2
model.add(Conv2D(256, (5, 5), strides=(1, 1),  padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(3, 3), strides=(2, 2)))
#conv3
model.add(Conv2D(384, (3, 3), strides=(1, 1),  padding='same', activation='relu'))
#conv4
model.add(Conv2D(384, (3, 3), strides=(1, 1),  padding='same', activation='relu'))
#conv5
model.add(Conv2D(256, (3, 3), strides=(1, 1),  padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(3, 3), strides=(2, 2)))
#fc5
model.add(Flatten())
model.add(Dense(4096, activation='relu'))
model.add(Dropout(0.8))
#fc6
model.add(Dense(1000, activation='relu'))
model.add(Dropout(0.8))
#fc7
model.add(Dense(10, activation='softmax'))

##-------------------3.訓練模型-------------------
#設定loss函式、優化器...
model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])
model.summary()
#訓練
checkpoint = ModelCheckpoint('./model_{epoch:02d}_{val_acc:.4f}.h5', save_best_only=False, period=5)
model.fit(x_train, y_train, batch_size=64, epochs=5, validation_data=(x_test,y_test))
model.save('./model.h5')



 

相關文章