今年 1 月 12 日,Keras 做者 François Chollet 在推特上表示由於中文讀者的普遍關注,他已經在 GitHub 上展開了一個 Keras 中文文檔項目。而昨日,François Chollet 再一次在推特上表示 Keras 官方文檔已經基本完成!他很是感謝翻譯和校對人員兩個多月的不懈努力,也但願 Keras 中文使用者能繼續幫助提高文檔質量。
這一次發佈的是 Keras 官方中文文檔,它獲得了嚴謹的校對而提高了總體質量。但該項目還在進行中,雖然目前已經上線了不少 API 文檔和使用教程,但仍然有一部份內容沒有完成。其實早在官方中文文檔出現之前,就有開發者構建了 Keras 的中文文檔,並且不少讀者都在使用 MoyanZitto 等人構建的中文文檔。
如下咱們將簡要介紹此次官方發佈的 Keras 文檔。
Keras 是一個用 Python 編寫的高級神經網絡 API,它可以以 TensorFlow、CNTK、或者 Theano 做爲後端運行。Keras 的開發重點是支持快速的實驗。可以以最小的時延把你的想法轉換爲實驗結果,是作好研究的關鍵。
Keras 兼容的 Python 版本: Python 2.7-3.6。
Keras 相對於其它深度學習庫很是容易構建:首先它提供一致和簡單的 API;其次,它提供獨立的、徹底可配置的模塊構成序列或圖表以完成模型;最後,做爲新的類和函數,新的模塊很容易擴展。這樣說可能比較抽象,但正如文檔中所描述的,咱們甚至在 30 秒就能快速上手 Keras。因此在坑外徘徊或準備入坑 Keras 的小夥伴能夠開心地開始大家的 30 秒。
快速開始:30 秒上手 Keras
Keras 的核心數據結構是 model,一種組織網絡層的方式。最簡單的模型是 Sequential 模型,它是由多網絡層線性堆疊的棧。對於更復雜的結構,你應該使用 Keras 函數式 API,它容許構建任意的神經網絡圖。
from keras.models import Sequential
model = Sequential()複製代碼
from keras.layers import Dense
model.add(Dense(units=64, activation='relu', input_dim=100))
model.add(Dense(units=10, activation='softmax'))複製代碼
在完成了模型的構建後, 可使用 .compile() 來配置學習過程:
model.compile(loss='categorical_crossentropy',
optimizer='sgd',
metrics=['accuracy'])複製代碼
若是須要,你還能夠進一步地配置優化器。Keras 的一個核心原則是使事情變得至關簡單,同時又容許用戶在須要的時候可以進行徹底的控制(終極的控制是源代碼的易擴展性)。
model.compile(loss=keras.losses.categorical_crossentropy,
optimizer=keras.optimizers.SGD(lr=0.01, momentum=0.9, nesterov=True))複製代碼
model.fit(x_train, y_train, epochs=5, batch_size=32)複製代碼
model.train_on_batch(x_batch, y_batch)複製代碼
loss_and_metrics = model.evaluate(x_test, y_test, batch_size=128)複製代碼
classes = model.predict(x_test, batch_size=128)複製代碼
構建一個問答系統,一個圖像分類模型,一個神經圖靈機,或者其餘的任何模型,就是這麼的快。深度學習背後的思想很簡單,那麼它們的實現又何須要那麼痛苦呢?
使用簡介
Keras 模型的使用通常能夠分爲順序模型(Sequential)和 Keras 函數式 API,順序模型是多個網絡層的線性堆疊,而 Keras 函數式 API 是定義複雜模型(如多輸出模型、有向無環圖,或具備共享層的模型)的方法。如下將簡要介紹兩種模型的使用方法:
你能夠經過將層的列表傳遞給 Sequential 的構造函數,來建立一個 Sequential 模型:
from keras.models import Sequential
from keras.layers import Dense, Activation
model = Sequential([
Dense(32, input_shape=(784,)),
Activation('relu'),
Dense(10),
Activation('softmax'),
])複製代碼
model = Sequential()
model.add(Dense(32, input_dim=784))
model.add(Activation('relu'))複製代碼
以下展現了一個完整的模型,即基於多層感知器 (MLP) 的 softmax 多分類:
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.optimizers import SGD
import numpy as np
x_train = np.random.random((1000, 20))
y_train = keras.utils.to_categorical(np.random.randint(10, size=(1000, 1)), num_classes=10)
x_test = np.random.random((100, 20))
y_test = keras.utils.to_categorical(np.random.randint(10, size=(100, 1)), num_classes=10)
model = Sequential()
model.add(Dense(64, activation='relu', input_dim=20))
model.add(Dropout(0.5))
model.add(Dense(64, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(10, activation='softmax'))
sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='categorical_crossentropy',
optimizer=sgd,
metrics=['accuracy'])
model.fit(x_train, y_train,
epochs=20,
batch_size=128)
score = model.evaluate(x_test, y_test, batch_size=128)複製代碼
利用函數式 API,能夠輕易地重用訓練好的模型:能夠將任何模型看做是一個層,而後經過傳遞一個張量來調用它。注意,在調用模型時,您不只重用模型的結構,還重用了它的權重。
如下是函數式 API 的一個很好的例子:具備多個輸入和輸出的模型。函數式 API 使處理大量交織的數據流變得容易。
來考慮下面的模型。咱們試圖預測 Twitter 上的一條新聞標題有多少轉發和點贊數。模型的主要輸入將是新聞標題自己,即一系列詞語,可是爲了增添趣味,咱們的模型還添加了其餘的輔助輸入來接收額外的數據,例如新聞標題的發佈的時間等。該模型也將經過兩個損失函數進行監督學習。較早地在模型中使用主損失函數,是深度學習模型的一個良好正則方法。
讓咱們用函數式 API 來實現它(詳細解釋請查看中文文檔):
from keras.layers import Input, Embedding, LSTM, Dense
from keras.models import Model
main_input = Input(shape=(100,), dtype='int32', name='main_input')
x = Embedding(output_dim=512, input_dim=10000, input_length=100)(main_input)
lstm_out = LSTM(32)(x)
auxiliary_output = Dense(1, activation='sigmoid', name='aux_output')(lstm_out)
auxiliary_input = Input(shape=(5,), name='aux_input')
x = keras.layers.concatenate([lstm_out, auxiliary_input])
x = Dense(64, activation='relu')(x)
x = Dense(64, activation='relu')(x)
x = Dense(64, activation='relu')(x)
main_output = Dense(1, activation='sigmoid', name='main_output')(x)
model = Model(inputs=[main_input, auxiliary_input], outputs=[main_output, auxiliary_output])
model.compile(optimizer='rmsprop', loss='binary_crossentropy',
loss_weights=[1., 0.2])
model.fit([headline_data, additional_data], [labels, labels],
epochs=50, batch_size=32)
model.compile(optimizer='rmsprop',
loss={'main_output': 'binary_crossentropy', 'aux_output': 'binary_crossentropy'},
loss_weights={'main_output': 1., 'aux_output': 0.2})
model.fit({'main_input': headline_data, 'aux_input': additional_data},
{'main_output': labels, 'aux_output': labels},
epochs=50, batch_size=32)複製代碼
以上只是一個簡單的案例,Keras 函數式 API 還有很是多的應用案例,包括層級共享、有向無環圖和殘差網絡等頂尖視覺模型,讀者能夠繼續閱讀中文文檔瞭解更多。
文檔的後一部分更可能是描述 Keras 中經常使用的函數與 API,包括 Keras 模型、層級函數、預處理過程、損失函數、最優化方法、數據集和可視化等。這些 API 和對應實現的功能其實不少時候能夠在實際使用的時候再查找,固然最基本的 API 咱們仍是須要了解的。如下將簡要介紹 Keras 模型和層級 API,其它的模塊請查閱原中文文檔。
Keras 模型
在 Keras 中有兩類模型,順序模型 和 使用函數式 API 的 Model 類模型。這些模型有許多共同的方法:
config = model.get_config()
model = Model.from_config(config)
model = Sequential.from_config(config)複製代碼
-
model.get_weights(): 返回模型權重的張量列表,類型爲 Numpy array。
-
model.set_weights(weights): 從 Nympy array 中爲模型設置權重。列表中的數組必須與 get_weights() 返回的權重具備相同的尺寸。
-
model.to_json(): 以 JSON 字符串的形式返回模型的表示。請注意,該表示不包括權重,只包含結構。你能夠經過如下代碼,從 JSON 字符串中從新實例化相同的模型(帶有從新初始化的權重):
from keras.models import model_from_json
json_string = model.to_json()
model = model_from_json(json_string)複製代碼
from keras.models import model_from_yaml
yaml_string = model.to_yaml()
model = model_from_yaml(yaml_string)複製代碼
-
model.save_weights(filepath): 將模型權重存儲爲 HDF5 文件。
-
model.load_weights(filepath, by_name=False): 從 HDF5 文件(由 save_weights 建立)中加載權重。默認狀況下,模型的結構應該是不變的。若是想將權重載入不一樣的模型(部分層相同),設置 by_name=True 來載入那些名字相同的層的權重。
Keras 層級
-
layer.get_weights(): 以 Numpy 矩陣的形式返回層的權重。
-
layer.set_weights(weights): 從 Numpy 矩陣中設置層的權重(與 get_weights 的輸出形狀相同)。
-
layer.get_config(): 返回包含層配置的字典。此圖層能夠經過如下方式重置:
layer = Dense(32)
config = layer.get_config()
reconstructed_layer = Dense.from_config(config)複製代碼
若是一個層具備單個節點 (i.e. 若是它不是共享層), 你能夠獲得它的輸入張量,輸出張量,輸入尺寸和輸出尺寸:
-
layer.input
-
layer.output
-
layer.input_shape
-
layer.output_shape
-
layer.get_input_at(node_index)
-
layer.get_output_at(node_index)
-
layer.get_input_shape_at(node_index)
-
layer.get_output_shape_at(node_index)
這些是 Keras 模型與層級基本的函數,文檔的中心內容也是這一部分和下面描述的 API 用途與參數,它包括完整模型所須要的各個模塊,包括數據、預處理、網絡架構、訓練、評估和可視化等。但這一部分咱們並不會介紹,由於不少時候咱們只有在遇到未知的函數時纔會詳細查閱。