終於!Keras官方中文版文檔正式發佈了

今年 1 月 12 日,Keras 做者 François Chollet‏ 在推特上表示由於中文讀者的普遍關注,他已經在 GitHub 上展開了一個 Keras 中文文檔項目。而昨日,François Chollet‏ 再一次在推特上表示 Keras 官方文檔已經基本完成!他很是感謝翻譯和校對人員兩個多月的不懈努力,也但願 Keras 中文使用者能繼續幫助提高文檔質量。
這一次發佈的是 Keras 官方中文文檔,它獲得了嚴謹的校對而提高了總體質量。但該項目還在進行中,雖然目前已經上線了不少 API 文檔和使用教程,但仍然有一部份內容沒有完成。其實早在官方中文文檔出現之前,就有開發者構建了 Keras 的中文文檔,並且不少讀者都在使用 MoyanZitto 等人構建的中文文檔。
  • Keras 官方文檔:https://keras.io/zh/
  • Keras 第三方文檔:http://keras-cn.readthedocs.io/en/latest/
如下咱們將簡要介紹此次官方發佈的 Keras 文檔。
Keras 是一個用 Python 編寫的高級神經網絡 API,它可以以 TensorFlow、CNTK、或者 Theano 做爲後端運行。Keras 的開發重點是支持快速的實驗。可以以最小的時延把你的想法轉換爲實驗結果,是作好研究的關鍵。

若是你有以下需求,請選擇 Keras:
  • 容許簡單而快速的原型設計(用戶友好,高度模塊化,可擴展性)。
  • 同時支持卷積神經網絡和循環神經網絡,以及二者的組合。
  • 在 CPU 和 GPU 上無縫運行與切換。
Keras 兼容的 Python 版本: Python 2.7-3.6。
Keras 相對於其它深度學習庫很是容易構建:首先它提供一致和簡單的 API;其次,它提供獨立的、徹底可配置的模塊構成序列或圖表以完成模型;最後,做爲新的類和函數,新的模塊很容易擴展。這樣說可能比較抽象,但正如文檔中所描述的,咱們甚至在 30 秒就能快速上手 Keras。因此在坑外徘徊或準備入坑 Keras 的小夥伴能夠開心地開始大家的 30 秒。

快速開始:30 秒上手 Keras

Keras 的核心數據結構是 model,一種組織網絡層的方式。最簡單的模型是 Sequential 模型,它是由多網絡層線性堆疊的棧。對於更復雜的結構,你應該使用 Keras 函數式 API,它容許構建任意的神經網絡圖。
Sequential 模型以下所示:
from keras.models import Sequential

model = Sequential()複製代碼
能夠簡單地使用 .add() 來堆疊模型:
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))複製代碼
如今,你能夠批量地在訓練數據上進行迭代了:
# x_train and y_train are Numpy arrays --just like in the Scikit-Learn API.
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 是定義複雜模型(如多輸出模型、有向無環圖,或具備共享層的模型)的方法。如下將簡要介紹兩種模型的使用方法:

1.Keras 順序模型
你能夠經過將層的列表傳遞給 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'),
])複製代碼
也可使用 .add() 方法將各層添加到模型中:
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()
# Dense(64) 是一個具備 64 個隱藏神經元的全鏈接層。
# 在第一層必須指定所指望的輸入數據尺寸,在這裏是一個 20 維的向量。
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)複製代碼

2. Keras 函數式 API
利用函數式 API,能夠輕易地重用訓練好的模型:能夠將任何模型看做是一個層,而後經過傳遞一個張量來調用它。注意,在調用模型時,您不只重用模型的結構,還重用了它的權重。
如下是函數式 API 的一個很好的例子:具備多個輸入和輸出的模型。函數式 API 使處理大量交織的數據流變得容易。
來考慮下面的模型。咱們試圖預測 Twitter 上的一條新聞標題有多少轉發和點贊數。模型的主要輸入將是新聞標題自己,即一系列詞語,可是爲了增添趣味,咱們的模型還添加了其餘的輔助輸入來接收額外的數據,例如新聞標題的發佈的時間等。該模型也將經過兩個損失函數進行監督學習。較早地在模型中使用主損失函數,是深度學習模型的一個良好正則方法。
模型結構以下圖所示:
讓咱們用函數式 API 來實現它(詳細解釋請查看中文文檔):
from keras.layers import Input, Embedding, LSTM, Dense
from keras.models import Model

# 標題輸入:接收一個含有 100 個整數的序列,每一個整數在 1 到 10000 之間。
# 注意咱們能夠經過傳遞一個 `name` 參數來命名任何層。
main_input = Input(shape=(100,), dtype='int32', name='main_input')

# Embedding 層將輸入序列編碼爲一個稠密向量的序列,每一個向量維度爲 512。
x = Embedding(output_dim=512, input_dim=10000, input_length=100)(main_input)

# LSTM 層把向量序列轉換成單個向量,它包含整個序列的上下文信息
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 類模型。這些模型有許多共同的方法:
  • model.summary(): 打印出模型概述信息。它是 utils.print_summary 的簡捷調用。
  • model.get_config(): 返回包含模型配置信息的字典。經過如下代碼,就能夠根據這些配置信息從新實例化模型:
config = model.get_config()
model = Model.from_config(config)
# or, for Sequential:
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)複製代碼
  • model.to_yaml(): 以 YAML 字符串的形式返回模型的表示。請注意,該表示不包括權重,只包含結構。你能夠經過如下代碼,從 YAML 字符串中從新實例化相同的模型(帶有從新初始化的權重):
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 層級

全部 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 用途與參數,它包括完整模型所須要的各個模塊,包括數據、預處理、網絡架構、訓練、評估和可視化等。但這一部分咱們並不會介紹,由於不少時候咱們只有在遇到未知的函數時纔會詳細查閱。
Keras 官方中文文檔,歡迎各位徘徊者入坑。
相關文章
相關標籤/搜索