Eka
Eka

Reputation: 15002

How is the numpy way to binarize arrays with a threshold value?

How to binarize an numpy array to its corresponding maximum value in a row above a threshold value. if the arrays row maximum value is lesser than the threshold value then column 1 should be equal to one.

a=np.array([[ 0.01,  0.3 ,  0.6 ],                                                                                                                      
            [ 0.2 ,  0.1 ,  0.4 ],                                                                                                                      
            [ 0.7 ,  0.1 ,  0.3 ],                                                                                                                      
            [ 0.2 ,  0.3 ,  0.5 ],                                                                                                                      
            [ 0.1 ,  0.7 ,  0.3 ],                                                                                                                      
            [ 0.1 ,  0.5 ,  0.8 ]])      


#required output with thresold row.max>=0.6 else column 1 should be 1
  np.array([[ 0.0 ,  0.0 ,  1.0 ],                                                                                                                      
            [ 0.0 ,  1.0 ,  0.0 ],                                                                                                                      
            [ 1.0 ,  0.0 ,  0.0 ],                                                                                                                      
            [ 0.0 ,  1.0 ,  0.0 ],                                                                                                                      
            [ 0.0 ,  1.0 ,  0.0 ],                                                                                                                      
            [ 0.0 ,  0.0 ,  1.0 ]])      

Upvotes: 0

Views: 1295

Answers (1)

Paul Panzer
Paul Panzer

Reputation: 53089

One solution: use argmax and advanced indexing

am = a.argmax(axis=-1)
am[a[np.arange(len(a)), am] < 0.6] = 1
out = np.zeros_like(a)
out[np.arange(len(a)), am] = 1
out
array([[ 0.,  0.,  1.],
       [ 0.,  1.,  0.],
       [ 1.,  0.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  0.,  1.]])

Upvotes: 1

Related Questions