Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrays used as indices must be of integer (or boolean) type

Tags:

Errors are like this:

Traceback (most recent call last):   File "NearestCentroid.py", line 53, in <module>     clf.fit(X_train.todense(),y_train)   File "/usr/local/lib/python2.7/dist-packages/scikit_learn-0.13.1-py2.7-linux-i686.egg/sklearn/neighbors/nearest_centroid.py", line 115, in fit     variance = np.array(np.power(X - self.centroids_[y], 2)) IndexError: arrays used as indices must be of integer (or boolean) type 

Codes are like this:

distancemetric=['euclidean','l2'] for mtrc in distancemetric: for shrkthrshld in [None]: #shrkthrshld=0 #while (shrkthrshld <=1.0):     clf = NearestCentroid(metric=mtrc,shrink_threshold=shrkthrshld)     clf.fit(X_train.todense(),y_train)     y_predicted = clf.predict(X_test.todense()) 

I am using scikit-learn package, X-train, y_train are in LIBSVM format, X is the feature:value pair, y_train is the target/label, X_train is in CSR matric format, the shrink_threshold does not support CSR sparse matrix, so I add .todense() to X_train, then I got this error, could anyone help me fix this? Thanks a lot!

like image 722
user1710418 Avatar asked Jun 30 '13 19:06

user1710418


2 Answers

I had a similar problem using the Pystruct pystruct.learners.OneSlackSSVM.

It occured because my training labels were floats, in stead of integers. In my case, it was because I initialized the labels with np.ones, without specifying dtype=np.int8. Hope it helps.

like image 64
FaXilifresh Avatar answered Sep 23 '22 17:09

FaXilifresh


It happens quite often that an indexing array should be clearly integer type by the way it is created, but in the case of empty list passed, becomes default float, a case which might not be considered by the programmer. For example:

>>> np.array(xrange(1)) >>> array([0])                #integer type as expected >>> np.array(xrange(0)) >>> array([], dtype=float64)  #does not generalize to the empty list 

Therefore, one should always explicitely define the dtype in the array constructor.

like image 33
Radio Controlled Avatar answered Sep 26 '22 17:09

Radio Controlled