keras 入門

Keras 的核心數據結構是模型。模型是用來組織網絡層的方式。模型有兩種,一種叫
Sequential 模型,另一種叫Model 模型。Sequential 模型是一系列網絡層按順序構成的棧,是單
輸入和單輸出的,層與層之間只有相鄰關係,是最簡單的一種模型。(直接就add完事了,和pytorch裏面的seqeuntial一樣)
Model 模型是用來建立更
複雜的模型的。
這裏先介紹簡單的Sequential 模型的使用(後面將會以一個示例來介紹Model 模型)。首先
是加載數據,這裏我們假設數據已經加載完畢,是X_train, Y_train 和X_test, Y_test。然後構建模型:

from keras.models import Sequential 
from keras.layers import Dense, Activation 
model = Sequential() 
model.add(Dense(output_dim=64, input_dim=100)) 
model.add(Activation(“relu”)) 
model.add(Dense(output_dim=10)) 
model.add(Activation(“softmax”)) 

然後,編譯模型,同時指明損失函數和優化器:

model.compile(loss=’categorical_crossentropy’, optimizer=’sgd’, metrics=[‘accuracy’]) 

注意這裏,有個model.compile,直接把損失,優化器,評價(分類問題最典型就是acc)
最後,訓練模型和評估模型:

model.fit(X_train, Y_train, nb_epoch=5, batch_size=32) 
loss_and_metrics = model.evaluate(X_test, Y_test, batch_size=32) 

model.fit就是生成訓練日誌,返回一個History的對象,其History.history屬性記錄了損失函數和其他指標的數值隨epoch變化的情況,如果有驗證集的話,也包含了驗證集的這些指標變化情況
實際上就是相當於pytorch不斷向list依次加入層,然後sequential構成
這就是一個最簡單的模型的使用。如果要搭建複雜的網絡,可以使用Keras 的Model 模型,
它能定義多輸出模型、含有共享層的模型、共享視覺模型、圖片問答模型、視覺問答模型等。

還有就是用model進行直接構建

import tensorflow as tf

inputs = tf.keras.Input(shape=(3,))
x = tf.keras.layers.Dense(4, activation=tf.nn.relu)(inputs)
outputs = tf.keras.layers.Dense(5, activation=tf.nn.softmax)(x)
model = tf.keras.Model(inputs=inputs, outputs=outputs)

就相當於是嵌套式組成 輸出作爲輸入

最最常用的實際上就是定義一個class(和pytorch一樣)

class MyModel(tf.keras.Model):

  def __init__(self):
    super(MyModel, self).__init__()
    self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu)
    self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax)

  def call(self, inputs):
    x = self.dense1(inputs)
    return self.dense2(x)

model = MyModel()

同樣的是繼承keras.Model(pytorch是繼承的nn.Module),同樣在這裏定義的是call作爲前向函數,pytorch是forward作爲前向函數
在MyModel類__init__函數中初始化需要的網絡層,然後實現一個前向傳播函數,來定義傳播方式

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章