【问题标题】:Check if value is higher than a threshold if it is, replace by检查值是否高于阈值,如果是,则替换为
【发布时间】:2019-07-22 06:49:09
【问题描述】:

我的目标是列出我的清单:

predictions = [0, 0.2, 0.9, 0.7]

如果高于 0.5,如果不是 1,则应该变为 0

我试过了:

predictions = np.where(predictions>=0.5,1, 0).tolist()

但是当取第一个元素时:

[0]

不仅是0

什么是做我想做的最好的方法?

【问题讨论】:

  • 预测 = [0; 0.2; 0.9; 0.7] 这应该用逗号分隔?

标签: python numpy keras


【解决方案1】:

只需使用np.array.round 方法:

>>> predictions = np.array([0, 0.2, 0.9, 0.7])
>>> predictions.round().tolist()
[0, 0, 1, 1]
>>> 

如果您确实需要列表理解,请执行以下操作:

>>> predictions = [0, 0.2, 0.9, 0.7]
>>> [int(i >= 0.5) for i in predictions]
[0, 0, 1, 1]

【讨论】:

    【解决方案2】:

    您可以使用列表理解:

    [0 if i>=0.5 else 1 for i in predictions]
    

    注意:您说如果原始值大于 0.5,您希望条目为零。你确定吗?或者如果低于 0.5 应该为零?

    【讨论】:

      【解决方案3】:

      如果 predictions 是一个列表,那么将其设置为一个 numpy 数组,其中可以工作:

      import numpy as np
      predictions = [0.0, 0.2, 0.9, 0.7] 
      newList = np.where(np.array(predictions) >= 0.5,1, 0).tolist()
      
      print(newList)
      print(newList[0])
      

      输出:

      [0, 0, 1, 1]
      0
      

      【讨论】:

        【解决方案4】:

        您正在尝试导致此错误:TypeError: '>=' not supported between instances of 'list' and 'float'

        此错误是因为您将列表传递给 np.where 函数,而该函数采用 np.array

        使用np.array(predictions) 将列表转换为numpy 数组即可解决问题。

        因此,总而言之,将您的行更改为此,您将获得所需的输出。

        predictions = np.where(np.array(predictions) >= 0.5, 1, 0).tolist()

        【讨论】:

        • 感谢您的建议,我在这里问之前尝试过...但是在错误的地方。我试过np.array(np.where...)
        【解决方案5】:

        假设你的预测是一个 numpy 数组

        threshold = 0.5 
        prediction=np.array([0,0.2,0.9,0.7])
        prediction[prediction<=threshold]=0
        prediction[prediction>threshold]=1
        

        注意 - 根据您的需要更改 > 或 >= 符号

        【讨论】:

          猜你喜欢
          • 2023-01-20
          • 2020-11-23
          • 1970-01-01
          • 2015-08-08
          • 1970-01-01
          • 2019-09-14
          • 2021-09-25
          • 1970-01-01
          • 2018-08-09
          相关资源
          最近更新 更多