keras用CNN识别mnist

import numpy as np
np.random.seed(1337) #重复性
from keras.datasets import mnist
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Activation,Convolution2D,MaxPool2D,Flatten
from keras.optimizers import Adam
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets("/Users/wutao/PycharmProjects/手写数字识别/MNIST_data", one_hot=True)
X_train, Y_train = mnist.train.images, mnist.train.labels
X_test, Y_test = mnist.test.images, mnist.test.labels
X_train = X_train.reshape(-1, 1, 28, 28).astype('float32')
X_test = X_test.reshape(-1, 1, 28, 28).astype('float32')

# 搭建CNN
model = Sequential()

# conv1
model.add(Convolution2D(
    nb_filter=32,
    nb_row = 5,
    nb_col = 5,
    border_mode='same',
    input_shape= (1,28,28),
    ))
model.add(Activation('relu'))

# pooling1
model.add(MaxPool2D(
    pool_size=(2,2),
    strides=(3,3),
    border_mode='same'
    ))

# conv2
model.add(Convolution2D(64,5,5,border_mode="same"))
model.add(Activation('relu'))

# pooling2
model.add(MaxPool2D(pool_size=(2,2),border_mode='same'))

# 全连接层1
model.add(Flatten())
model.add(Dense(1024))
model.add(Activation('relu'))

# 全连接层2
model.add(Dense(10))
model.add(Activation('softmax'))

# optimizer
adam = Adam(lr=1e-4)

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

print('Training...................')
model.fit(X_train,Y_train,nb_epoch=1,batch_size=32)

print('\nTesting..................')
loss,accuracy = model.evaluate(X_test,Y_test)

print('test loss:',loss)
print('test accuracy:',accuracy)
阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭