Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ssis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在模型内部改变Keras模型的输出阈值?_Python_Tensorflow_Keras_Neural Network_Predict - Fatal编程技术网

Python 如何在模型内部改变Keras模型的输出阈值?

Python 如何在模型内部改变Keras模型的输出阈值?,python,tensorflow,keras,neural-network,predict,Python,Tensorflow,Keras,Neural Network,Predict,我正在构建一个Keras模型,以便: Y = 1 for X >= 0.5 Y = 0 for X < 0.5 创建模型后,我将权重设置为[1],将偏差设置为[-0.5] 现在,我获得了很高的精度,但以下输入的输出错误: [[0.50000006] [0.5 ] [0.50000001] [0.50000002] [0.50000007] [0.50000004] [0.50000001] [0.50000004] [0.50000004] [0.50

我正在构建一个Keras模型,以便:

Y = 1 for X >= 0.5
Y = 0 for X < 0.5
创建模型后,我将权重设置为[1],将偏差设置为[-0.5] 现在,我获得了很高的精度,但以下输入的输出错误:

[[0.50000006]
 [0.5       ]
 [0.50000001]
 [0.50000002]
 [0.50000007]
 [0.50000004]
 [0.50000001]
 [0.50000004]
 [0.50000004]
 [0.50000001]
 [0.50000003]
 [0.50000007]
 [0.50000008]
 [0.50000008]
 [0.50000004]
 [0.50000002]
 [0.50000006]
 [0.50000006]
 [0.5000001 ]
 [0.50000008]
 [0.50000002]
 [0.50000004]
 [0.50000006]
 [0.50000004]
 [0.5       ]
 [0.50000005]
 [0.50000003]
 [0.50000007]
 [0.50000004]
etc.
因此,模型已经了解到,
Y=1仅用于X>0.5
,但我需要
Y=1用于X>=0.5


我知道这可以通过
pred=model.predict(X)
获取输出,然后手动比较来实现。但我希望这是在模型内部完成的<代码>模型。预测类应具有阈值。我想更改此阈值。我该怎么做?

预测类不允许我们更改阈值。keras就是这样实现的

def predict_classes(self, x, batch_size=32, verbose=0):
    proba = self.predict(x, batch_size=batch_size, verbose=verbose)
    if proba.shape[-1] > 1:
      return proba.argmax(axis=-1)
    else:
      return (proba > 0.5).astype('int32')
如果您想拥有自己的阈值,则必须重载该方法

代码
predict\u classes
不允许我们更改阈值。keras就是这样实现的

def predict_classes(self, x, batch_size=32, verbose=0):
    proba = self.predict(x, batch_size=batch_size, verbose=verbose)
    if proba.shape[-1] > 1:
      return proba.argmax(axis=-1)
    else:
      return (proba > 0.5).astype('int32')
如果您想拥有自己的阈值,则必须重载该方法

代码
class MySequential(keras.models.Sequential):
  def __init__(self, **kwargs):
    super(MySequential, self).__init__(**kwargs)

  def predict_classes(self, x, batch_size=32, verbose=0):
    proba = self.predict(x, batch_size=batch_size, verbose=verbose)
    return (proba >= 0.6).astype('int32')

def define_model():
    model = MySequential()
    model.add(keras.layers.Dense(1, activation = 'sigmoid', input_shape=(None, 1)))

    opt = keras.optimizers.SGD(learning_rate = 0.01, momentum = 0.99)
    model.compile(loss='binary_crossentropy', optimizer=opt, metrics=['accuracy'])
    
    return model

# Test

model = define_model()
x = np.random.randn(5)
print (model.predict(x))
print (model.predict_classes(x))