覆盖keras预测功能

时间:2017-05-20 13:04:16

标签: python numpy keras

我有Keras模型接受具有4D形状的输入(n,高度,宽度,通道)。

但是,我的数据生成器正在生成二维数组(n,width * height)。因此,Keras的预测函数期望输入为4D。我没有机会更改数据生成器,因为该模型将由其他人测试。那么,有没有办法覆盖Keras的预测函数。

我的模型结构

a = Input(shape=(width*height,))

d1 = 16  # depth of filter kernel each layer
d2 = 16
d3 = 64
d4 = 128
d5 = 256

drop_out = 0.25
patch_size = (3, 3)
k_size = (2, 2)

reshape = Reshape((height, width, 1))(a)

conv1 = Conv2D(filters=d1, kernel_size=patch_size, padding='same', activation='relu')(reshape)
conv1 = MaxPooling2D(pool_size=k_size, padding='same')(conv1)

conv2 = Convolution2D(filters=d2, kernel_size=patch_size, padding='same', activation='relu')(conv1)
conv2 = MaxPooling2D(pool_size=k_size, padding='same')(conv2)

conv3 = Convolution2D(filters=d3, kernel_size=patch_size, padding='same', activation='relu')(conv2)
conv3 = MaxPooling2D(pool_size=k_size, padding='same')(conv3)

conv4 = Convolution2D(filters=d4, kernel_size=patch_size, padding='same', activation='relu')(conv3)
conv4 = MaxPooling2D(pool_size=k_size, padding='same')(conv4)

conv5 = Convolution2D(filters=d5, kernel_size=patch_size, padding='same', activation='relu')(conv4)
conv5 = MaxPooling2D(pool_size=k_size, padding='same')(conv5)

x = Flatten()(conv5)

x = Dropout(drop_out)(x)
node = 32

x_1 = Dense(node, activation='relu')(x)  # connect the flatten layer to five classifier,each one comes to a digit.
x_2 = Dense(node, activation='relu')(x)
x_3 = Dense(node, activation='relu')(x)
x_4 = Dense(node, activation='relu')(x)
x_5 = Dense(node, activation='relu')(x)

d1 = Dense(n_class, activation='softmax')(x_1)
d2 = Dense(n_class, activation='softmax')(x_2)
d3 = Dense(n_class, activation='softmax')(x_3)
d4 = Dense(n_class, activation='softmax')(x_4)
d5 = Dense(n_class, activation='softmax')(x_5)

outputs = [d1, d2, d3, d4, d5]

model = Model(a, outputs)
model.compile(loss='categorical_crossentropy', optimizer='adadelta', metrics=['accuracy'])

model.fit(raw_train_data, raw_train_target, batch_size=200, epochs=5, validation_split=0.2)

1 个答案:

答案 0 :(得分:0)

您不会覆盖预测,只需在模型的开头添加Reshape图层即可。

使用功能API:

from keras.layers import *

inp = Input((width*heigth,))
first = Reshape((width,height,1))(inp)

..... other layers.....

model = Model(inp, outputFromTheLastLayer)    

使用顺序模型:

model = Sequential()    
model.add(Reshape((width,height,1), input_shape = (width*height,)))
model.add(otherlayers)   

关于输出形状。

由于您有5个输出,因此您需要将目标数组作为五个数组的列表:

raw_train_target = [target1,target2,target3,target4,target5]

如果你不能这样做,并且raw_train_target是一个单一的arary,目标都在一个序列之后,你可以尝试在最后使用一个连接层:

output = Concatenate()(outputs)