注:本系列全部博客將持續更新併發布在github上,您能夠經過github下載本系列全部文章筆記文件。javascript
Keras是一個基於Python編寫的高層神經網絡API,憑藉用戶友好性、模塊化以及易擴展等有點大受好評,考慮到Keras的優良特性以及它的受歡迎程度,TensorFlow2.0中將Keras的代碼吸取了進來,化身爲tf.keras模塊供用戶使用。css
使用tf.keras提供的高層API,能夠輕鬆得完成建模三部曲——模型構建、訓練、評估等工做。下面咱們分別來講說如何使用tf.keras完成這三部曲。html
咱們知道,神經網絡模型就是層的堆疊,tf.keras提供的Sequential類對象就是層容器,能夠輕鬆實現對層的堆疊,建立網絡模型。用Sequential建立一個全鏈接網絡模型:html5
import tensorflow as tf from tensorflow import keras # 爲方便使用,keras通常單獨導入 from tensorflow.keras import layers
model = tf.keras.Sequential() # 往模型中添加一個有64個神經元組成的層,激活函數爲relu: model.add(layers.Dense(64, activation='relu')) # 再添加一個: model.add(layers.Dense(64, activation='relu')) # 添加一個有10個神經元的softmax層做爲輸出層: model.add(layers.Dense(10, activation='softmax'))
也能夠在使用Sequential實例化模型時,經過傳入由層組成的列表來添加層。咱們換一種方式實現上面的模型構建過程,兩種方式是徹底等效的:java
model = tf.keras.Sequential([ layers.Dense(64, activation='relu'), layers.Dense(64, activation='relu'), layers.Dense(10, activation='softmax')] )
你看,用tf.keras建立一個模型,就是這麼簡單,只須要往Sequential中傳入一個個tf.keras.layers定義的層就行了。進一步的,咱們研究一下tf.keras.layers怎麼個性化地建立層。node
定義神經網絡層經過tf.keras.layers模塊中的Dense類實現,Dense類構造參數以下:python
# 有64個神經元,激活函數爲sigmoid的層 layers.Dense(64, activation='sigmoid') # 或者: layers.Dense(64, activation=tf.keras.activations.sigmoid) # 對權值矩陣進行正則化: layers.Dense(64, kernel_regularizer=tf.keras.regularizers.l1(0.01)) # 對偏置向量進行正則化: layers.Dense(64, bias_regularizer=tf.keras.regularizers.l2(0.01)) # 指定權值隨機正交初始化: layers.Dense(64, kernel_initializer='orthogonal') # 指定偏置爲常數: layers.Dense(64, bias_initializer=tf.keras.initializers.Constant(2.0))
<tensorflow.python.keras.layers.core.Dense at 0x7f486247abd0>
創建好模型以後,接下來固然是要進行訓練模型了。不過,在訓練前還須要作一些配置工做,例如指定優化器、損失函數、評估指標等,這些配置參數的過程通常經過tf.keras.Model.compile方法進行,先來熟悉一下tf.keras.Model.compile方法的三個經常使用參數:jquery
在知道怎麼配置模型訓練參數後,就能夠根據實際應用狀況合理選擇優化器、損失函數、評估方法等:linux
# 迴歸模型 model.compile(optimizer=tf.keras.optimizers.Adam(0.01), # 指定優化器,學習率爲0.01 loss='mse', # 指定均方差做爲損失函數 metrics=['mae']) # 添加絕對值偏差做爲評估方法 # 分類模型 model.compile(optimizer=tf.keras.optimizers.RMSprop(0.01), loss=tf.keras.losses.CategoricalCrossentropy(), # 分類模型多用交叉熵做爲損失函數 metrics=[tf.keras.metrics.CategoricalAccuracy()])
經過compile()配置好模型後,就能夠開始訓練了。tf.keras中提供了fit()方法對模型進行訓練,先來看看fit()方法的主要參數:android
下面分別說說如何使用fit()方法結合numpy數據和tf.data.Dataset數據進行模型訓練。
import numpy as np data = np.random.random((1000, 32)) labels = np.random.random((1000, 10)) model.fit(data, labels, epochs=10, batch_size=32)
Train on 1000 samples Epoch 1/10 1000/1000 [==============================] - 1s 554us/sample - loss: 206.2688 - categorical_accuracy: 0.1050 Epoch 2/10 1000/1000 [==============================] - 0s 34us/sample - loss: 911.8347 - categorical_accuracy: 0.0990 Epoch 3/10 1000/1000 [==============================] - 0s 30us/sample - loss: 1879.7505 - categorical_accuracy: 0.0980 Epoch 4/10 1000/1000 [==============================] - 0s 28us/sample - loss: 3141.3959 - categorical_accuracy: 0.0940 Epoch 5/10 1000/1000 [==============================] - 0s 36us/sample - loss: 4673.7791 - categorical_accuracy: 0.1010 Epoch 6/10 1000/1000 [==============================] - 0s 36us/sample - loss: 6526.8757 - categorical_accuracy: 0.0960 Epoch 7/10 1000/1000 [==============================] - 0s 31us/sample - loss: 8571.8533 - categorical_accuracy: 0.1020 Epoch 8/10 1000/1000 [==============================] - 0s 33us/sample - loss: 11070.1039 - categorical_accuracy: 0.0970 Epoch 9/10 1000/1000 [==============================] - 0s 36us/sample - loss: 13533.4661 - categorical_accuracy: 0.1050 Epoch 10/10 1000/1000 [==============================] - 0s 25us/sample - loss: 17259.2291 - categorical_accuracy: 0.1000
<tensorflow.python.keras.callbacks.History at 0x7f74a4755650>
如何使用驗證數據集的話,能夠這樣:
import numpy as np data = np.random.random((1000, 32)) labels = np.random.random((1000, 10)) val_data = np.random.random((100, 32)) val_labels = np.random.random((100, 10)) model.fit(data, labels, epochs=10, batch_size=32, validation_data=(val_data, val_labels)) # 驗證數據集以元組的形式傳入
Train on 1000 samples, validate on 100 samples Epoch 1/10 1000/1000 [==============================] - 0s 34us/sample - loss: 67219.8359 - categorical_accuracy: 0.0960 - val_loss: 55306.6777 - val_categorical_accuracy: 0.1000 Epoch 2/10 1000/1000 [==============================] - 0s 32us/sample - loss: 73732.5724 - categorical_accuracy: 0.0920 - val_loss: 89920.2088 - val_categorical_accuracy: 0.1100 Epoch 3/10 1000/1000 [==============================] - 0s 50us/sample - loss: 79956.1480 - categorical_accuracy: 0.1020 - val_loss: 101092.6750 - val_categorical_accuracy: 0.1000 Epoch 4/10 1000/1000 [==============================] - 0s 36us/sample - loss: 84322.9844 - categorical_accuracy: 0.0970 - val_loss: 117610.5700 - val_categorical_accuracy: 0.1000 Epoch 5/10 1000/1000 [==============================] - 0s 38us/sample - loss: 91992.0751 - categorical_accuracy: 0.1130 - val_loss: 94200.0838 - val_categorical_accuracy: 0.1000 Epoch 6/10 1000/1000 [==============================] - 0s 38us/sample - loss: 97189.2044 - categorical_accuracy: 0.0910 - val_loss: 89020.5294 - val_categorical_accuracy: 0.1100 Epoch 7/10 1000/1000 [==============================] - 0s 33us/sample - loss: 107109.9905 - categorical_accuracy: 0.0930 - val_loss: 102350.4259 - val_categorical_accuracy: 0.1200 Epoch 8/10 1000/1000 [==============================] - 0s 41us/sample - loss: 114450.2496 - categorical_accuracy: 0.1010 - val_loss: 102719.3653 - val_categorical_accuracy: 0.1100 Epoch 9/10 1000/1000 [==============================] - 0s 41us/sample - loss: 124694.8415 - categorical_accuracy: 0.0950 - val_loss: 142269.8362 - val_categorical_accuracy: 0.1100 Epoch 10/10 1000/1000 [==============================] - 0s 44us/sample - loss: 131952.7791 - categorical_accuracy: 0.0800 - val_loss: 158925.8294 - val_categorical_accuracy: 0.0900
<tensorflow.python.keras.callbacks.History at 0x7f749c548810>
是騾子是馬,拉出來溜溜就知道了,訓練好的模型性能如何,評估測試一下就知道了。可使用模型自帶的evaluate()方法和predict()方法對模型進行評估和預測。
# 若是是numpy數據,能夠這麼使用 data = np.random.random((1000, 32)) labels = np.random.random((1000, 10)) model.evaluate(data, labels, batch_size=32)
1000/1 [=================================================] - 0s 17us/sample - loss: 161163.7180 - categorical_accuracy: 0.0930
[153591.27975, 0.093]
# 若是數Dataset對象,能夠這麼使用 dataset = tf.data.Dataset.from_tensor_slices((data, labels)) dataset = dataset.batch(32) model.evaluate(dataset)
32/32 [==============================] - 0s 579us/step - loss: 153946.2378 - categorical_accuracy: 0.0930
[153946.23779296875, 0.093]
使用predict()方法進行預測:
# numpy數據 result = model.predict(data, batch_size=32) print(result.shape)
(1000, 10)
# dataset數據 result = model.predict(dataset) print(result.shape)