pip install theano
pip install keras
pip install data
import keras
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Convolution2D,Activation,MaxPooling2D,Flatten,Dense
from keras.optimizers import Adam
from keras.utils import np_utils
model = Sequential()
model.add(Convolution2D(
nb_filter = 32, #第一层先设置32个滤波器
nb_row = 5,
nb_col = 5,#设置滤波器大小为5*5
padding = ‘same’#选择滤波器的扫描方式,即是否考虑边缘
input_shape = (1,28,28)#初次设置卷积层需要设置输入的形状
))
model.add(Activation(‘relu’))
它长这样
model.add(MaxPooling2D(
pool_size = (2,2)#设置为2*2的池化块
strides = (2,2)#向右向下的步长
padding = ‘same’
))
model.add(Convolution2D(64,(5,5),padding = 'same'))
model.add(Activation('relu'))
model.add(MaxPooling2D(strides = (2,2),padding = 'same'))
model.add(Flatten())
model.add(Dense(1024))#加入全连接层,其中1024是节点数目
model.add(Activation(‘relu’))
model.add(Dense(10))#输出10个类
model.add(Activation(‘softmax’))#用于分类的softmax函数
代码页:
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 12 09:45:46 2017
@author: genji
"""
import numpy as np
np.random.seed(1337)
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Convolution2D,Activation,MaxPooling2D,Flatten,Dense
from keras.optimizers import Adam
from keras.utils import np_utils
#load data
(X_train,Y_train),(X_test,Y_test) = mnist.load_data()#X.shape(60000,28,28),Y.shape(10000)
#data pre_processing
X_train = X_train.reshape(-1,1,28,28)
X_test = X_test.reshape(-1,1,28,28)
Y_train = np_utils.to_categorical(Y_train,num_classes = 10)
Y_test = np_utils.to_categorical(Y_test,num_classes = 10)
model = Sequential()
model.add(Convolution2D(
nb_filter = 32,#第一层卷积层中滤波器的个数#
nb_row = 5, #滤波器的长度为5#
nb_col = 5, #滤波器的宽度为5#
border_mode = 'same', #padding mode 为same#
input_shape = (1,28,28),
))
model.add(Activation('relu'))#激活函数为relu
model.add(MaxPooling2D(
pool_size = (2,2),#下采样格为2*2
strides = (2,2),
padding = 'same', #padding mode is 'same'
))
model.add(Convolution2D(64,(5,5),padding = 'same'))
model.add(Activation('relu'))
model.add(MaxPooling2D(strides = (2,2),padding = 'same'))
model.add(Flatten())#将多维的输入一维化
model.add(Dense(1024))#全连接层 1024个点
model.add(Activation('relu'))
model.add(Dense(10))
model.add(Activation('softmax'))#softmax 用于分类
adam = Adam()#学习速率lr=0.0001
model.compile(optimizer = adam,
loss = 'categorical_crossentropy',
metrics = ['accuracy'])
print('Training ========== (。・`ω´・) ========')
model.fit(X_train,Y_train,epochs = 1, batch_size = 64)#全部训练次数1次,每次训练批次大小64
print('Testing ========== (。・`ω´・) ========')
loss,accuracy = model.evaluate(X_test,Y_test)
print('\nTest loss:',loss)
print('\nTest accuracy',accuracy)