Eli Borodach Eli Borodach - 8 months ago 41
Python Question

Why Do I get: TypeError: choice() takes 2 positional arguments but 4 were given?

I have a problem with random.choice which I can't understand. I pass 3 arguments to the function which is allowed to have 4 (http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.random.choice.html), but it writes I am allowed to give only 2 and 4 were given.

def load_data():
dataset = load_boston()
num_samples = size(dataset.data, 0)
test_set_sz = int(1.0 * num_samples / 10)
tst_sub_inds = random.choice(range(num_samples), test_set_sz, False)
data_test, label_test = dataset.data[tst_sub_inds, :], dataset.target[tst_sub_inds]
trn_sub_inds = list(set(range(num_samples)) - set(tst_sub_inds))
data_train, label_train = dataset.data[trn_sub_inds, :], dataset.target[trn_sub_inds]
return ((data_train, label_train), (data_test, label_test))

The Error:

tst_sub_inds = random.choice(range(num_samples), test_set_sz, False)
TypeError: choice() takes 2 positional arguments but 4 were given

What is the problem? Maybe it due to an old version of python?



As you clarified in the comments, you are using import random which imports Python's random library.

You should use from numpy import random, which will import Numpy's random.choice which is the one that you expect.