keras + tensorflow —— 函式式 API程式設計
阿新 • • 發佈:2018-12-19
1. 實現簡單的邏輯迴歸
from keras import Input
from keras import layers
from keras.models import Model
x = Input(shape=(32, ))
# TensorShape([Dimension(None), Dimension(32)])
y = layers.Dense(16, activation='softmax')(x)
model = Model(x, y)
# model.output_shape
# model.summary()
2. 函數語言程式設計的模型構建
-
序列化模型構建
seq_model = Sequential() seq_model.add(layers.Dense(32, activation='relu', input_shape=(64, ))) # 首層必須指定 input_shape 或 batch_input_shape seq_model.add(layers.Dense(32, activation='relu')) seq_model.add(layers.Dense(10, activation='softmax'))
-
函式式API 下的模型構建
input_tensor = Input(shape=(64, )) z = layers.Dense(32, activation='relu')(input_tensor) z = layers.Dense(32, activation='relu')(z) y = layers.Dense(10, activation='softmax')(z) from keras.models import Model model = Model(input_tensor, y)
-
兩種方式對比:
seq_model.summary() model.summary()
3. layers.concatenate 與 layers.add
-
layers.add:執行 tensor 的相加操作,要求輸入必須同維度(或者經過 broadcast 之後是同維度);
x_1 = Input(shape=(32, )) x_2 = Input(shape=(32, )) >> layers.add([x_1, x_2]) <tf.Tensor 'add_3/add:0' shape=(?, 32) dtype=float32> x_1 = Input(shape=(32, 64)) x_2 = Input(shape=(64,)) >> layers.add([x_1, x_2]) <tf.Tensor 'add_4/add:0' shape=(?, 32, 64) dtype=float32>
-
layers.concatente:執行的是 tensor 的拼接操作(維度會拉長)
x_1 = Input(shape=(32, )) x_2 = Input(shape=(64, )) >> layers.concatenate([x_1, x_2]) <tf.Tensor 'concatenate_3/concat:0' shape=(?, 96) dtype=float32>