2017-03-31 95 views
3

我目前正在尋找一種方法,可以將多個模型的輸出合併到一個模型中,我需要創建一個可以進行分類的CNN網絡。將多個模型的輸出合併爲一個模型

enter image description here

的圖像被分成切片(由顏色所看到),每個部分被給定爲輸入到一定模型(1,2,3,4),每個模型的結構是相同的,但每個部分都會分配給一個單獨的模型,以確保在整個圖像上不會應用相同的重量 - 我嘗試避免完全分配重量,並保持本地重量共享。然後每個模型執行卷積和最大池化,並生成某種輸出,該輸出必須輸入一個密集層,該層從先前模型(模型1,2,3,4)中獲得輸出並執行分類。

我在這裏的問題是有可能創建模型1,2,3,4並將其連接到完全連接的層並訓練給定輸入部分和輸出類的所有模型 - 而無需定義輸出keras中的卷積和合並層?

回答

3

是的,您可以使用多輸入和多輸出模型創建此類模型,有關更多詳細信息,請參閱keras documentation。在這裏,我分享代碼示例,希望這可以幫助

import numpy as np 
import keras 
from keras.optimizers import SGD 
from keras.models import Sequential, Model 
from keras.layers import Activation, Dense, Dropout, Flatten, Input, Merge, Convolution2D, MaxPooling2D 

# Generate dummy data 
train1 = np.random.random((100, 100, 100, 3)) 
train2 = np.random.random((100, 100, 100, 3)) 
train3 = np.random.random((100, 100, 100, 3)) 
train4 = np.random.random((100, 100, 100, 3)) 

y_train = keras.utils.to_categorical(np.random.randint(10, size=(100, 1)), num_classes=10) 

#parallel ip for different sections of image 
inp1 = Input(shape=train1.shape[1:]) 
inp2 = Input(shape=train2.shape[1:]) 
inp3 = Input(shape=train3.shape[1:]) 
inp4 = Input(shape=train4.shape[1:]) 

# paralle conv and pool layer which process each section of input independently 
conv1 = Conv2D(64, (3, 3), activation='relu')(inp1) 
conv2 = Conv2D(64, (3, 3), activation='relu')(inp2) 
conv3 = Conv2D(64, (3, 3), activation='relu')(inp3) 
conv4 = Conv2D(64, (3, 3), activation='relu')(inp4) 

maxp1 = MaxPooling2D((3, 3))(conv1) 
maxp2 =MaxPooling2D((3, 3))(conv2) 
maxp3 =MaxPooling2D((3, 3))(conv3) 
maxp4 =MaxPooling2D((3, 3))(conv4) 

# can add multiple parallel conv, pool layes to reduce size 

flt1 = Flatten()(maxp1) 
flt2 = Flatten()(maxp2) 
flt3 = Flatten()(maxp3) 
flt4 = Flatten()(maxp4) 

mrg = Merge(mode='concat')([flt1,flt2,flt3,flt4]) 

dense = Dense(256, activation='relu')(mrg) 

op = Dense(10, activation='softmax')(dense) 

model = Model(input=[inp1, inp2, inp3, inp4], output=op) 
model.compile(optimizer='rmsprop', 
       loss='categorical_crossentropy', 
       metrics=['accuracy']) 
model.fit([train1,train2,train3,train4], y_train, 
      nb_epoch=10, batch_size=28) 
相關問題