天天看點

TensorFlow2.0快速構模組化型簡單堆疊模型函數式構模組化型

TensorFlow2.0快速構模組化型

  • 簡單堆疊模型
  • 函數式構模組化型

主要介紹如何快速建構一個模型并進行訓練,重點在于模型建構流程的講解,其中所用到的API可以通過頭檔案、官網查詢其功能,參數,輸入與輸出資料

簡單堆疊模型

  • model = tf.keras.Sequential(),可了解為執行個體化一個用于構模組化型的類,我們可以通過add()的方式向其内部添加網絡層,這些網絡層就等價于類中的成員與方法
# 執行個體化一個堆疊模型
model = tf.keras.Sequential()
# 構模組化型的網絡層結構
model.add(layers.Dense(32, activation='relu'))
model.add(layers.Dense(32, activation='relu'))
model.add(layers.Dense(10, activation='softmax'))
           
  • 設定訓練流程,調用compile()方法,對優化器,損失函數,性能名額進行配置
model.compile(optimizer=tf.keras.optimizers.Adam(0.001),
             loss=tf.keras.losses.categorical_crossentropy,
             metrics=[tf.keras.metrics.categorical_accuracy])
           
  • 訓練網絡,調用fit()方法,送入資料對模型進行訓練
import numpy as np
import tensorflow as tf
from tensorflow.keras import layers

model = tf.keras.Sequential()
model.add(layers.Dense(32, activation='relu'))
model.add(layers.Dense(32, activation='relu'))
model.add(layers.Dense(10, activation='softmax'))
model.compile(optimizer=tf.keras.optimizers.Adam(0.001),
             loss=tf.keras.losses.categorical_crossentropy,
             metrics=[tf.keras.metrics.categorical_accuracy])

train_x = np.random.random((1000, 72))
train_y = np.random.random((1000, 10))

val_x = np.random.random((200, 72))
val_y = np.random.random((200, 10))

model.fit(train_x, train_y, epochs=1000, batch_size=100,
          validation_data=(val_x, val_y))

           

函數式構模組化型

tf.keras.Sequential()屬于簡單模型的堆疊,無法完成複雜模型的建構(多輸入、多輸出模型、包含共享層的模型、殘差結構的模型),是以通過函數式API構模組化型

  • 定義模型的輸入,網絡中間層,模型的輸出;相比于堆疊模型add()方法的方式,該方式構模組化型更靈活
# 輸入資料的次元需提前指定,并且資料次元需保持與定義一緻
input_x = tf.keras.Input(shape=(72,))
hidden1 = layers.Dense(32, activation="relu")(input_x)
hidden2 = layers.Dense(16, activation="relu")(hidden1)
pred = layers.Dense(10, activation="softmax")(hidden2)
           
  • 調用tf.keras.Model()方法構模組化型,隻需要寫入輸入與輸出
  • 設定訓練流程,訓練網絡與上部分建構堆疊模型一緻
import numpy as np
import tensorflow as tf
from tensorflow.keras import layers

input_x = tf.keras.Input(shape=(72,))
hidden1 = layers.Dense(32, activation="relu")(input_x)
hidden2 = layers.Dense(16, activation="relu")(hidden1)
pred = layers.Dense(10, activation="softmax")(hidden2)

model = tf.keras.Model(inputs=input_x, outputs=pred)
model.compile(optimizer=tf.keras.optimizers.Adam(0.001),
             loss=tf.keras.losses.categorical_crossentropy,
             metrics=['accuracy'])

train_x = np.random.random((1000, 72))
train_y = np.random.random((1000, 10))

val_x = np.random.random((200, 72))
val_y = np.random.random((200, 10))

model.fit(train_x, train_y, epochs=1000, batch_size=100,
          validation_data=(val_x, val_y))
           

繼續閱讀