Keras搭建多輸入模型
阿新 • • 發佈:2018-11-16
簡介
當我們的任務涉及到多個維度不同的資料來擬合一個目標時,我們需要構建多輸入模型。
模型構建
假設我們需要搭建如下的模型,輸入資料分別為100維和50維的向量,輸出為0或1:
from keras.layers import Conv1D, Dense, MaxPool1D, concatenate, Flatten from keras import Input, Model from keras.utils import plot_model import numpy as np def multi_input_model(): """構建多輸入模型""" input1_= Input(shape=(100, 1), name='input1') input2_ = Input(shape=(50, 1), name='input2') x1 = Conv1D(16, kernel_size=3, strides=1, activation='relu', padding='same')(input1_) x1 = MaxPool1D(pool_size=10, strides=10)(x1) x2 = Conv1D(16, kernel_size=3, strides=1, activation='relu', padding='same')(input2_) x2 = MaxPool1D(pool_size=5, strides=5)(x2) x = concatenate([x1, x2]) x = Flatten()(x) x = Dense(10, activation='relu')(x) output_ = Dense(1, activation='sigmoid', name='output')(x) model = Model(inputs=[input1_, input2_], outputs=[output_]) model.summary() return model if __name__ == '__main__': # 產生訓練資料 x1 = np.random.rand(100, 100, 1) x2 = np.random.rand(100, 50, 1) # 產生標籤 y = np.random.randint(0, 2, (100,)) model = multi_input_model() # 儲存模型圖 plot_model(model, 'Multi_input_model.png') model.compile(optimizer='adam', loss='binary_crossentropy') model.fit([x1, x2], y, epochs=10, batch_size=10)