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
初始化一個模型
model = Sequential()
輸入向量是784維度的,第一個影藏層是1000個節(jié)點,init代表的是鏈接矩陣中的權值初始化
'''
init 初始化參數(shù):
uniform(scale=0.05) :均勻分布,最常用的。Scale就是均勻分布的每個數(shù)據(jù)在-scale~scale之間。此處就是-0.05~0.05。scale默認值是0.05;
lecun_uniform:是在LeCun在98年發(fā)表的論文中基于uniform的一種方法。區(qū)別就是lecun_uniform的scale=sqrt(3/f_in)。f_in就是待初始化權值矩陣的行。
normal:正態(tài)分布(高斯分布)。
identity :用于2維方陣,返回一個單位陣
orthogonal:用于2維方陣,返回一個正交矩陣。
zero:產(chǎn)生一個全0矩陣。
glorot_normal:基于normal分布,normal的默認 sigma^2=scale=0.05,而此處sigma^2=scale=sqrt(2 / (f_in+ f_out)),其中,f_in和f_out是待初始化矩陣的行和列。
glorot_uniform:基于uniform分布,uniform的默認scale=0.05,而此處scale=sqrt( 6 / (f_in +f_out)) ,其中,f_in和f_out是待初始化矩陣的行和列。
he_normal:基于normal分布,normal的默認 scale=0.05,而此處scale=sqrt(2 / f_in),其中,f_in是待初始化矩陣的行。
he_uniform:基于uniform分布,uniform的默認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
第二個隱藏層是500個節(jié)點
model.add(Dense(500, init='glorot_uniform'))
model.add(Activation('relu'))
model.add(Dropout(0.5))
第三層是輸出層,輸出結果是10個類別,所以維度是10
model.add(Dense(10, init='glorot_uniform'))
model.add(Activation('softmax')) # 最后一層用softmax
設定參數(shù)
lr表示學習速率,decay是學習速率的衰減系數(shù)(每個epoch衰減一次),momentum表示動量項,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),這里需要把后面的維度直接拼起來變成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轉換成一個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)
'''
開始訓練,這里參數(shù)比較多。batch_size就是batch_size,nb_epoch就是最多迭代的次數(shù), shuffle就是是否把數(shù)據(jù)隨機打亂之后再進行訓練
verbose是屏顯模式,官方這么說的:verbose: 0 for no logging to stdout, 1 for progress bar logging, 2 for one log line per epoch.
就是說0是不屏顯,1是顯示一個進度條,2是每個epoch都顯示一行數(shù)據(jù)
show_accuracy就是顯示每次迭代后的正確率
validation_split就是拿出百分之多少用來做交叉驗證
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])