keras 手动搭建alexnet并训练mnist数据集

# -*- 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')



 

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页