[英]Classification and regression using the same Neural Network using Keras
I would like to build a Neural Network that at the same time output a label for classification and a value for regression. 我想建立一个神经网络,同时输出用于分类的标签和用于回归的值。 I would like to do that using Keras.
我想使用Keras做到这一点。 Right now my code is only for classification:
现在,我的代码仅用于分类:
mdl = Sequential()
mdl.add(Dense(100, activation='relu', input_dim=X_train.shape[1]))
mdl.add(Dense(200, activation='relu'))
mdl.add(Dense(100, activation='relu'))
mdl.add(Dense(6, activation='softmax'))
mdl.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])
# early stopping implementation
filepath="weights.best.hdf5"
checkpoint = ModelCheckpoint(filepath, monitor='val_acc', verbose=1,
save_best_only=True, mode='max')
early_stop = EarlyStopping(monitor='val_acc', patience=100, mode='max')
callbacks_list = [checkpoint, early_stop]
# fit network
history = mdl.fit(X_train, y_train, epochs=2000, batch_size=32,
validation_split=0.2, verbose=2, shuffle=True, callbacks=callbacks_list)
So right now I have a softmax activation function on the output layer that correspond to the probability that I use for classification. 因此,现在我在输出层上具有softmax激活函数,该函数与我用于分类的概率相对应。 How can I modify this code to output also a continuos value that will represent my regression problem.
我如何修改此代码以输出也代表我的回归问题的continuos值。 I know that Keras Functional API allow to specify multi input and multi output network.
我知道Keras Functional API允许指定多输入和多输出网络。 Anyone that have an idea on how can I do that?
有人对我该怎么做有想法吗?
There's a straightforward transformation of your code to the Keras Functional API as illustrated in their documentation . 如他们的文档所示,您的代码可以直接转换为Keras Functional API。 You'd need to change your Sequential declaration
您需要更改顺序声明
mdl = Sequential()
mdl.add(Dense(100, activation='relu', input_dim=X_train.shape[1]))
mdl.add(Dense(200, activation='relu'))
mdl.add(Dense(100, activation='relu'))
mdl.add(Dense(6, activation='softmax'))
to its Functional equivalent: 与其功能等效:
inputs = Input(shape=(X_train.shape[1],))
layer1 = Dense(100, activation='relu')(inputs)
layer2 = Dense(200, activation='relu')(layer1)
layer3 = Dense(100, activation='relu')(layer2)
classifier = Dense(6, activation='softmax')(layer3)
mdl = Model(inputs=inputs, outputs=classifier)
(often people just re-use the same variable for all the intermediate layers, it's even done in the documentation samples but this IMHO is a bit clearer). (通常人们只是对所有中间层重复使用相同的变量,甚至在文档样本中也是如此,但是此恕我直言有点清晰)。
Once you've done that, you can add another output layer that "branches" from the last Dense layer layer3
, and set that your model has two outputs, for example: 完成此操作后,您可以添加另一个输出层,该输出层从最后一个Dense层
layer3
“分支”,并设置模型具有两个输出,例如:
regression = Dense(1, activation='linear')(layer3)
mdl = Model(inputs=inputs, outputs=[classifier, regression])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.