1

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.

6
  • I did not understand what do you want ??? please ellaborate with an example Commented Mar 25, 2018 at 10:31
  • for example y_predict is [5,4,3,2,1] y_real is [1,2,3,4,5] and you can see that there is 4 wrong predictions in y_predict. Each index(1,2,3,4,5) corresponds to a training example. Now I want to pick up an example which is not correctly predicted randomly to update the parameters in the prediction function..... Commented Mar 25, 2018 at 10:49
  • I am going to write a program which implements perceptron learning algorithm. For example, we have 5 training examples.....The prediction given by the current weight vector is [5,4,3,2,1] and the right answer is [1,2,3,4,5]. As you can see, there are 4 examples which is not correctly predicted. And now I want to pick up one example randomly to update the weight vector w...... Commented Mar 25, 2018 at 10:55
  • Without knowing the details of your model, explicitly fixing mispredictions sounds like it would be unnecessary as those should already be punished by whatever objective function you are optimizing during parameter estimation. Commented Mar 25, 2018 at 11:15
  • initialize pocket weights W For t = 0, 1, · · · 1 find a (random) mistake of wt called (xn(t) , yn(t) ) 2 (try to) correct the mistake by w(t+1) ← w(t) + yn(t)xn(t) 3 if w(t+1) makes fewer mistakes than W, replace W by w(t+1) ...until enough iterations return W as g Commented Mar 25, 2018 at 11:22

2 Answers 2

1

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))
Sign up to request clarification or add additional context in comments.

Comments

1

You can use the more compact

x = np.random.choice(np.where(a != b)[0])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.