Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

python - convert numpy array to 0 or 1

A = np.array([[0.94366988, 0.86095311, 0.88896715, 0.93630641, 0.74075403, 0.52849619
                  , 0.03094677, 0.85707681, 0.88457925, 0.67279696, 0.26601085, 0.4823794
                  , 0.74741157, 0.78575729, 0.00978911, 0.9203284, 0.02453695, 0.84884703
                  , 0.2050248, 0.03703224, 0.92931392, 0.11930532, 0.01411064, 0.7832698
                  , 0.58188015, 0.66897565, 0.75119007, 0.01323558, 0.03402649, 0.99735115
                  , 0.21031727, 0.78123225, 0.6815842, 0.46647604, 0.66323375, 0.03424828
                  , 0.08031627, 0.76570656, 0.34760863, 0.06177743, 0.6987531, 0.4106426
                  , 0.6648871, 0.02776868, 0.93053125, 0.46395717, 0.23971605, 0.9771735
                  , 0.66202407, 0.10482388]])

Convert the entries of a into 0 (if activation <= 0.5) or 1 (if activation > 0.5)

for i in range(A.shape[1]):
if A[i]>0.5:
    Y_prediction[i] = 1
else:
    Y_prediction[i] = 0

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

And how to use vectorize this thx

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think you need vectorized function np.where:

B = np.where(A > 0.5, 1, 0)
print (B)
[[1 1 1 1 1 1 0 1 1 1 0 0 1 1 0 1 0 1 0 0 1 0 0 1 1 1 1 0 0 1 0 1 1 0 1 0 0
  1 0 0 1 0 1 0 1 0 0 1 1 0]]

B = np.where(A <= 0.5, 0, 1)
print (B)
[[1 1 1 1 1 1 0 1 1 1 0 0 1 1 0 1 0 1 0 0 1 0 0 1 1 1 1 0 0 1 0 1 1 0 1 0 0
  1 0 0 1 0 1 0 1 0 0 1 1 0]]

But better is holdenweb solution if need convert to 0 and 1 only.

np.where is better if need convert to another scalars like 5 and 10 or a and b:

C = np.where(A > 0.5, 5, 10)
print (C)
[[ 5  5  5  5  5  5 10  5  5  5 10 10  5  5 10  5 10  5 10 10  5 10 10  5
   5  5  5 10 10  5 10  5  5 10  5 10 10  5 10 10  5 10  5 10  5 10 10  5
   5 10]]

D = np.where(A > 0.5, 'a', 'b')
print (D)
[['a' 'a' 'a' 'a' 'a' 'a' 'b' 'a' 'a' 'a' 'b' 'b' 'a' 'a' 'b' 'a' 'b' 'a'
  'b' 'b' 'a' 'b' 'b' 'a' 'a' 'a' 'a' 'b' 'b' 'a' 'b' 'a' 'a' 'b' 'a' 'b'
  'b' 'a' 'b' 'b' 'a' 'b' 'a' 'b' 'a' 'b' 'b' 'a' 'a' 'b']]

Timings:

np.random.seed(223)
A = np.random.rand(1,1000000)

#jez
In [64]: %timeit np.where(A > 0.5, 1, 0)
100 loops, best of 3: 7.58 ms per loop

#holdenweb
In [65]: %timeit (A > 0.5).astype(int)
100 loops, best of 3: 3.47 ms per loop

#stamaimer
In [66]: %timeit element_wise_round(A)
1 loop, best of 3: 318 ms per loop

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...