Reputation: 38
enter image description hereI am writing script to realize a perceptron learning algorithm. However, I am having trouble picking up an element randomly in a numpy array. And I don't know whether there is a built-in function in numpy to do that.
def error_rate(w1, w2):
W = error(w1, w2)
return((W.sum())/W.size)
def error(w1, w2):
W = w1!= w2
#print(W)
return W
#test of the function 'error rate'
a = np.array([0,0,0,0,1])
b = np.array([0,1,0,0,1])
print (error_rate(a, b))
print(np.random.choice(np.nonzero(error(a, b)), 1))
In the code above, I actually want to check whether the number in a
is the same with the number with the same index in b
. And pick up randomly from the index k
which satisfies a[k]!=b[k]
. But it doesn't work.
Upvotes: 1
Views: 280
Reputation: 114599
You can use the more compact
x = np.random.choice(np.where(a != b)[0])
Upvotes: 1
Reputation: 18221
The issue here is that np.nonzero
returns a tuple in which you only need the first element; here,
np.random.choice(np.nonzero(a != b)[0])
would do the job. You can avoid picking that out by using np.flatnonzero
instead; that is, the above is equivalent to
np.random.choice(np.flatnonzero(a != b))
Upvotes: 1