[深度学习框架] Keras上使用RNN进行mnist分类
2017-11-29 20:48
761 查看
import numpy as np np.random.seed(1337) # for reproducibility from keras.datasets import mnist from keras.utils import np_utils from keras.models import Sequential from keras.layers import SimpleRNN, Activation, Dense from keras.optimizers import Adam TIME_STEPS = 28 # same as the height of the image INPUT_SIZE = 28 # same as the width of the image BATCH_SIZE = 50 BATCH_INDEX = 0 OUTPUT_SIZE = 10 CELL_SIZE = 50 LR = 0.001 # download the mnist to the path '~/.keras/datasets/' if it is the first time to be called # X shape (60,000 28x28), y shape (10,000, ) (X_train, y_train), (X_test, y_test) = mnist.load_data() # data pre-processing X_train = X_train.reshape(-1, 28, 28) / 255. # normalize X_test = X_test.reshape(-1, 28, 28) / 255. # normalize y_train = np_utils.to_categorical(y_train, num_classes=10) y_test = np_utils.to_categorical(y_test, num_classes=10) # build RNN model model = Sequential() # RNN cell model.add(SimpleRNN( # for batch_input_shape, if using tensorflow as the backend, we have to put None for the batch_size. # Otherwise, model.evaluate() will get error. batch_input_shape=(None, TIME_STEPS, INPUT_SIZE), # Or: input_dim=INPUT_SIZE, input_length=TIME_STEPS, output_dim=CELL_SIZE, unroll=True, )) # output layer model.add(Dense(OUTPUT_SIZE)) model.add(Activation('softmax')) # optimizer adam = Adam(LR) model.compile(optimizer=adam, loss='categorical_crossentropy', metrics=['accuracy']) # training for step in range(4001): # data shape = (batch_num, steps, inputs/outputs) X_batch = X_train[BATCH_INDEX: BATCH_INDEX+BATCH_SIZE, :, :] Y_batch = y_train[BATCH_INDEX: BATCH_INDEX+BATCH_SIZE, :] cost = model.train_on_batch(X_batch, Y_batch) BATCH_INDEX += BATCH_SIZE BATCH_INDEX = 0 if BATCH_INDEX >= X_train.shape[0] else BATCH_INDEX if step % 500 == 0: cost, accuracy = model.evaluate(X_test, y_test, batch_size=y_test.shape[0], verbose=False) print('test cost: ', cost, 'test accuracy: ', accuracy)
相关文章推荐
- [深度学习框架] Keras上使用CNN进行mnist分类
- 使用深度学习Caffe框架的C++接口进行物体分类
- [深度学习框架] Keras上使用神经网络进行mnist分类
- 基于深度学习框架Keras的CNN分类Mnist
- DeepLearning tutorial(7)深度学习框架Keras的使用-进阶
- 使用深度学习TensorFlow框架进行图片识别
- DeepLearning tutorial(7)深度学习框架Keras的使用-进阶
- tensorflow学习笔记之使用tensorflow进行MNIST分类(1)
- Keras(2):使用Keras构建神经网络进行Mnist手写字体分类,并定性分析各种超参数的影响
- Keras 深度学习框架Python Example:CNN/mnist
- DeepLearning tutorial(7)深度学习框架Keras的使用-进阶
- 深度学习框架Keras使用心得
- 深度学习框架TensorFlow学习与应用(六)——卷积神经网络应用于MNIST数据集分类
- 深度学习框架Keras使用心得
- 使用深度学习TensorFlow框架进行图片识别
- 神经网络与深度学习 1.6 使用Python实现基于梯度下降算法的神经网络和MNIST数据集的手写数字分类程序
- 使用Keras构建神经网络进行Mnist手写字体分类
- 深度学习框架Keras使用心得
- 【神经网络与深度学习】【Qt开发】【VS开发】从caffe-windows-visual studio2013到Qt5.7使用caffemodel进行分类的移植过程<二>
- [深度学习框架] Tensorflow上使用CNN进行mnist分类