Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/284.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 检查值是否高于阈值如果高于阈值,则替换为_Python_Numpy_Keras - Fatal编程技术网

Python 检查值是否高于阈值如果高于阈值,则替换为

Python 检查值是否高于阈值如果高于阈值,则替换为,python,numpy,keras,Python,Numpy,Keras,我的目标是列出我的: 预测=[0,0.2,0.9,0.7] 如果高于0.5,如果不是1,则应变为0 我试过: predictions = np.where(predictions>=0.5,1, 0).tolist() 但当采用第一种元素时,它是: [0] 而且不仅仅是0 做我想做的事情的最佳方法是什么?只需使用np.array.round方法: >>> predictions = np.array([0, 0.2, 0.9, 0.7]) >>> pr

我的目标是列出我的:

预测=[0,0.2,0.9,0.7]

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

我试过:

predictions = np.where(predictions>=0.5,1, 0).tolist()
但当采用第一种元素时,它是:

[0]

而且不仅仅是
0


做我想做的事情的最佳方法是什么?

只需使用
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]

假设预测是一个numpy数组

threshold = 0.5 
prediction=np.array([0,0.2,0.9,0.7])
prediction[prediction<=threshold]=0
prediction[prediction>threshold]=1
阈值=0.5
预测=np.数组([0,0.2,0.9,0.7])
预测[预测阈值]=1

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

您可以使用列表:

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

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

如果预测是一个列表,则将其作为一个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

您正在尝试的操作会导致此错误:
TypeError:“>=”在“list”和“float”实例之间不受支持。

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

使用
np将列表转换为numpy数组。数组(预测)
解决了这个问题

总之,将您的行更改为该行,您将获得所需的输出


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

predictions=[0;0.2;0.9;0.7]这应该是逗号分隔的?谢谢你的建议,我在询问之前已经试过了。。。但是在错误的地方。我尝试了
np.array(np.where…