keras使用MLP分类MNIST

MLP(多层感知器神经网络)即多层全连接神经网络模型。

from keras.datasets import mnist
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import Dense,Dropout,Activation

batch_size=128
nb_classes=10
nb_epoch=10
img_size=28*28

(x_train,y_train),(x_test,y_test)=mnist.load_data("E:\Code\PycharmProjects\KerasStudying\data\mnist.npz")

x_train=x_train.reshape(-1,img_size).astype('float32')/255
x_test=x_test.reshape(-1,img_size).astype('float32')/255
y_train=np_utils.to_categorical(y_train,nb_classes)
y_test=np_utils.to_categorical(y_test,nb_classes)


model=Sequential([
    Dense(512,input_shape=(img_size,),activation='relu',),
    Dropout(0.2),
    Dense(512,input_shape=(512,),activation='relu'),
    Dropout(0.2),
    Dense(10,input_shape=(512,),activation='softmax'),
])

model.summary()

model.compile(optimizer='rmsprop',loss='categorical_crossentropy',metrics=['accuracy'])


model.fit(x_train,y_train,batch_size=batch_size,epochs=10,verbose=0,validation_data=(x_test,y_test))

score=model.evaluate(x_test,y_test,verbose=0)
print('accuracy:'+str(score[1]))

这里写图片描述

你可能感兴趣的:(python与人工睿智,机器学习入门与放弃)