一、 背景與目的
背景:配置好了theano,弄了gpu, 要學dnn方法。
目的:本篇學習keras基本用法, 學習怎么用keras寫mlp,學keras搞文本的基本要點。
二、 准備
工具包: theano、numpy、keras等工具包
數據集: 如果下不來, 可以用迅雷下,弄到~/.keras/datasets/下面即可
代碼位置:examples/reuters_mlp.py
三、 代碼賞析
'''Trains and evaluate a simple MLP on the Reuters newswire topic classification task. ''' from __future__ import print_function import numpy as np np.random.seed(1337) # for reproducibility from keras.datasets import reuters from keras.models import Sequential from keras.layers import Dense, Dropout, Activation from keras.utils import np_utils from keras.preprocessing.text import Tokenizer max_words = 1000 #vocab大小 batch_size = 32 #mini_batch_size nb_epoch = 5 #大循環次數 print('Loading data...') (X_train, y_train), (X_test, y_test) = reuters.load_data(nb_words=max_words, test_split=0.2) #載入路透社語料
#打印 print(len(X_train), 'train sequences') print(len(X_test), 'test sequences')
#分類數目--原版路透社我記着是10來着,應該是語料用的是大的那個 nb_classes = np.max(y_train)+1 print(nb_classes, 'classes') print('Vectorizing sequence data...')
#tokenize tokenizer = Tokenizer(nb_words=max_words)
#序列化,取df前1000大
#這里有個非常好玩的事, X_train 里面初始存的是wordindex,wordindex是按照詞大小來的(應該是,因為直接就給撇了)
#所以這個效率上還是很高的
#轉化的還是binary,默認不是用tfidf X_train = tokenizer.sequences_to_matrix(X_train, mode='binary') X_test = tokenizer.sequences_to_matrix(X_test, mode='binary') print('X_train shape:', X_train.shape) print('X_test shape:', X_test.shape) print('Convert class vector to binary class matrix (for use with categorical_crossentropy)')
#這個就好理解多了, 編碼而已 Y_train = np_utils.to_categorical(y_train, nb_classes) Y_test = np_utils.to_categorical(y_test, nb_classes) print('Y_train shape:', Y_train.shape) print('Y_test shape:', Y_test.shape) print('Building model...') model = Sequential()
#第一層
#Dense就是全連接層 model.add(Dense(512, input_shape=(max_words,))) #輸入維度, 512==輸出維度 model.add(Activation('relu')) #激活函數 model.add(Dropout(0.5)) #dropout
#第二層 model.add(Dense(nb_classes)) model.add(Activation('softmax'))
#損失函數設置、優化函數,衡量標准 model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
#訓練,交叉驗證 history = model.fit(X_train, Y_train, nb_epoch=nb_epoch, batch_size=batch_size, verbose=1, validation_split=0.1) score = model.evaluate(X_test, Y_test, batch_size=batch_size, verbose=1) print('Test score:', score[0]) print('Test accuracy:', score[1])
四、 訓練速度比較
此表調整到了相對好一點的兩萬詞表,要不然我覺得討論效果沒什么意義
訓練時間-cpu | 訓練時間-gpu | val-cpu | val-gpu | |
第一輪 | 22s | 3s | 79 | 79 |
第二輪 | 22s | 3s | 81 | 81 |
第三輪 | 23s | 3s | 80 | 80 |
第四輪 | 33s | 3s | 78 | 79 |
第五輪 | 40s | 3s | 80 | 80 |
看的出來,即使是mlp,效果的提升也是非常非常大的。