Keras-mnist111
日期:2016 /06 /03 15:15:52
版本 python ??
!/usr/bin/python
-- coding:utf-8 --
fromfutureimport print_function
import numpy as np
np.random.seed(1337) # for reproducibility
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
from keras.optimizers import SGD, Adam, RMSprop
from keras.utils import np_utils
batch_size = 128
nb_classes = 10
nb_epoch = 1
初始化一個(gè)模型
model = Sequential()
輸入向量是784維度的沙热,第一個(gè)影藏層是1000個(gè)節(jié)點(diǎn)庶近,init代表的是鏈接矩陣中的權(quán)值初始化
'''
init 初始化參數(shù):
uniform(scale=0.05) :均勻分布,最常用的。Scale就是均勻分布的每個(gè)數(shù)據(jù)在-scale~scale之間。此處就是-0.05~0.05。scale默認(rèn)值是0.05;
lecun_uniform:是在LeCun在98年發(fā)表的論文中基于uniform的一種方法。區(qū)別就是lecun_uniform的scale=sqrt(3/f_in)娘汞。f_in就是待初始化權(quán)值矩陣的行。
normal:正態(tài)分布(高斯分布)夕玩。
identity :用于2維方陣你弦,返回一個(gè)單位陣
orthogonal:用于2維方陣,返回一個(gè)正交矩陣燎孟。
zero:產(chǎn)生一個(gè)全0矩陣禽作。
glorot_normal:基于normal分布,normal的默認(rèn) sigma^2=scale=0.05缤弦,而此處sigma^2=scale=sqrt(2 / (f_in+ f_out))领迈,其中,f_in和f_out是待初始化矩陣的行和列碍沐。
glorot_uniform:基于uniform分布狸捅,uniform的默認(rèn)scale=0.05,而此處scale=sqrt( 6 / (f_in +f_out)) 累提,其中尘喝,f_in和f_out是待初始化矩陣的行和列。
he_normal:基于normal分布斋陪,normal的默認(rèn) scale=0.05朽褪,而此處scale=sqrt(2 / f_in),其中无虚,f_in是待初始化矩陣的行缔赠。
he_uniform:基于uniform分布,uniform的默認(rèn)scale=0.05友题,而此處scale=sqrt( 6 / f_in)嗤堰,其中,f_in待初始化矩陣的行度宦。
'''
model.add(Dense(1000, input_dim=784, init='glorot_uniform'))
model.add(Activation('relu')) # 激活函數(shù)是tanh
model.add(Dropout(0.5)) # 采用50%的dropout
第二個(gè)隱藏層是500個(gè)節(jié)點(diǎn)
model.add(Dense(500, init='glorot_uniform'))
model.add(Activation('relu'))
model.add(Dropout(0.5))
第三層是輸出層踢匣,輸出結(jié)果是10個(gè)類別告匠,所以維度是10
model.add(Dense(10, init='glorot_uniform'))
model.add(Activation('softmax')) # 最后一層用softmax
設(shè)定參數(shù)
lr表示學(xué)習(xí)速率,decay是學(xué)習(xí)速率的衰減系數(shù)(每個(gè)epoch衰減一次)离唬,momentum表示動(dòng)量項(xiàng)后专,Nesterov的值是False或者True,表示使不使用Nesterov momentum输莺。
sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9,nesterov=True)
loss代表的是損失函數(shù), optimizer代表的是優(yōu)化方法, class_mode代表
使用交叉熵作為loss函數(shù)戚哎,就是熟知的log損失函數(shù)
model.compile(loss='categorical_crossentropy',optimizer=sgd, class_mode='categorical')
使用Keras自帶的mnist工具讀取數(shù)據(jù)(第一次需要聯(lián)網(wǎng))
(X_train, y_train), (X_test, y_test) = mnist.load_data()
由于輸入數(shù)據(jù)維度是(num, 28, 28),這里需要把后面的維度直接拼起來(lái)變成784維
X_train = X_train.reshape(X_train.shape[0],X_train.shape[1]X_train.shape[2])
X_test = X_test.reshape(X_test.shape[0], X_test.shape[1]X_test.shape[2])
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.shape[0], 'test samples')
這里需要把index轉(zhuǎn)換成一個(gè)one hot的矩陣
Y_train = (np.arange(10) == y_train[:,None]).astype(int)
Y_test = (np.arange(10) == y_test[:,None]).astype(int)
'''
convert class vectors to binary class matrices
Y_train = np_utils.to_categorical(y_train, nb_classes)
Y_test = np_utils.to_categorical(y_test, nb_classes)
'''
開(kāi)始訓(xùn)練模闲,這里參數(shù)比較多建瘫。batch_size就是batch_size崭捍,nb_epoch就是最多迭代的次數(shù)尸折, shuffle就是是否把數(shù)據(jù)隨機(jī)打亂之后再進(jìn)行訓(xùn)練
verbose是屏顯模式,官方這么說(shuō)的:verbose: 0 for no logging to stdout, 1 for progress bar logging, 2 for one log line per epoch.
就是說(shuō)0是不屏顯殷蛇,1是顯示一個(gè)進(jìn)度條实夹,2是每個(gè)epoch都顯示一行數(shù)據(jù)
show_accuracy就是顯示每次迭代后的正確率
validation_split就是拿出百分之多少用來(lái)做交叉驗(yàn)證
model.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=nb_epoch,shuffle=True, verbose=1, show_accuracy=True, validation_split=0.3)
print ('test set')
score = model.evaluate(X_test, Y_test, batch_size=200,show_accuracy=True, verbose=1)
print('Test score:', score[0])
print('Test accuracy:', score[1])