我有下面这个数组:
a=np.array([0.1, 0.2, 0.3, 0.7, 0.8, 0.9])
我想要的是将这个向量根据阈值转换成二元向量。
以阈值为0.5为例,大于0.5的元素转换为1,否则为0。
输出向量应该如下所示:
a_output = [0, 0, 0, 1, 1, 1]
我该如何做到这一点?
np.where
np.where(a > 0.5, 1, 0)
# array([0, 0, 0, 1, 1, 1])
astype
进行布尔值转换(a > .5).astype(int)
# array([0, 0, 0, 1, 1, 1])
np.select
np.select([a <= .5, a>.5], [np.zeros_like(a), np.ones_like(a)])
# array([ 0., 0., 0., 1., 1., 1.])
np.round
如果你的数组值是介于0和1之间的浮点数,并且你的阈值为0.5,那么这是最佳解决方案。
a.round()
# array([0., 0., 0., 1., 1., 1.])
np.select
方法默认返回'uint8',但看起来更加复杂。 - user3613932a>0.5
将为您提供该数组。 - user3613932from sklearn.preprocessing import binarize
a = np.array([0.1, 0.2, 0.3, 0.7, 0.8, 0.9]).reshape(1,-1)
x = binarize(a)
a_output = np.ravel(x)
print(a_output)
#everything together
a_output = np.ravel(binarize(a.reshape(1,-1), 0.5))