如何获得二进制双极激活函数以在keras中以+1和-1输出?

时间:2019-01-03 07:20:00

标签: python-3.x machine-learning keras deep-learning anaconda

我想将y_pred输出仅作为+1或-1。它不应具有中间实数值,甚至不能为零。

classifier = Sequential()

#adding layers
# Adding the input layer and the first hidden l`enter code here`ayer
classifier.add(Dense(output_dim = 6, init = 'uniform', activation ='relu', input_shape = (22,)))
# Adding the second hidden layer classifier.add(Dense(output_dim = 6, init = 'uniform', activation = 'relu'))
# Adding the output layer
classifier.add(Dense(output_dim = 1, init = 'uniform', activation = 'tanh'))

# Compiling Neural Network
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])

# Fitting our model 
classifier.fit(x_train, y_train, batch_size = 10, epochs = 100)

# Predicting the Test set results
y_pred = classifier.predict(x_test)

y_pred的输出值在[-1,1]范围内,但我希望这些值只能是1或-1。

2 个答案:

答案 0 :(得分:0)

要正常运行,神经网络需要一个可以获取非整数值的激活函数。如果需要严格的离散输出,则需要自己转换输出值。

答案 1 :(得分:0)

当您在代码中实现binary_crossentropy丢失时,Keras会自动获取输出并将该值应用阈值0.5。这使得大于0.5的值等于1,而小于0.5的值等于0。不幸的是,在keras中,没有简单的方法来更改阈值。您将必须编写自己的损失函数。

Here是Stackoverflow链接,将指导您执行此操作。