【keras】mnist数据集FC实现

#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time: 2018/8/15
# @Author: xfLi

import numpy as np
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers.core import Dense, Activation, Dropout
from keras.optimizers import SGD
from keras.utils import np_utils

np.random.seed(1671)

NB_EPOCH = 20
BATCH_SIZE = 128
VERBOSE = 1
NB_CLASSES = 10   # number of outputs = number of digits
OPTIMIZER = SGD() # SGD optimizer, explained later in this chapter
N_HIDDEN = 128
VALIDATION_SPLIT=0.2 # how much TRAIN is reserved for VALIDATION
RESHAPE = 784
DROPOUT = 0.3

(x_train, y_train), (x_test, y_test) = mnist.load_data() #加载数据

x_train = x_train.reshpe(60000, RESHAPE)
x_test = x_test.reshape(10000, RESHAPE)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')

# 归一化
x_train /= 255
x_test /= 255
print(x_train.shape[0], 'train samples')
print(x_test.shpe[0], 'test samples')

# 将类别向量(从0到nb_classes的整数向量)映射为二值类别矩阵,
# 用于应用到以categorical_crossentropy为目标函数的模型中.
y_train = np_utils.to_categorical(y_train, NB_CLASSES)
y_test = np_utils.to_categorical(y_test, NB_CLASSES)

model = Sequential()
model.add(Dense(N_HIDDEN, input_shape=(RESHAPE,)))
model.add(Activation('relu'))
model.add(Dropout(DROPOUT))
model.add(Dense(N_HIDDEN))
model.add(Activation('relu'))
model.add(Dropout(DROPOUT))
model.add(Dense(NB_CLASSES))
model.add(Activation('softmax'))

model.summary()

#编译
model.compile(loss='categorical_crossentropy',
              optimizer=OPTIMIZER,
              metrics=['accuracy'])

history = model.fit(x_train, y_train,
                    batch_size=BATCH_SIZE,
                    epochs=NB_EPOCH,
                    verbose=VERBOSE,
                    validation_split=VALIDATION_SPLIT)
#验证
score = model.evaluate(x_test, y_test, verbose=VERBOSE)
print("\nTest score:", score[0])
print('Test accuracy:', score[1])



猜你喜欢

转载自blog.csdn.net/qq_30159015/article/details/81708988
今日推荐