0

I'm trying out opencv samples from https://github.com/Itseez/opencv/blob/master/samples/python2/letter_recog.py and I need help deciphering this code..

new_samples = np.zeros((sample_n * self.class_n, var_n+1), np.float32)
new_samples[:,:-1] = np.repeat(samples, self.class_n, axis=0)
new_samples[:,-1] = np.tile(np.arange(self.class_n), sample_n)

I know what np.repeat and np.tile are, but I'm not sure what new_samples[:,:-1] or new_samples[:,-1] are supposed to do, with the -1 index. I know how numpy array indexing works, but have not seen this case. I could not find solutions from searching.

1 Answer 1

3

Python slicing and numpy slicing are slightly different. But in general -1 in arrays or lists means counting backwards (from last item). It is mentioned in the Information Introduction for strings as:

>>> word = 'Python'
>>> word[-1]  #last character 
'n'

And for lists as:

>>> squares = [1, 4, 9, 16, 25]
>>> squares
[1, 4, 9, 16, 25]
>>> squares[-1]
25

This can be also expanded to numpy array indexing as in your example.

new_samples[:,:-1] means all rows except the last columns

new_samples[:,-1] means all rows and last column only

Sign up to request clarification or add additional context in comments.

2 Comments

"Python slicing and numpy slicing are different." That's a potentially misleading statement to begin your answer, because while there are differences, I wouldn't say the use of -1 (which is the subject of the question) is one of them. Python lists can be indexed with negative values (including -1) and sliced with, for example :-1 to get all but the last element.
@WarrenWeckesser, I edited the answer to remove possible confusion for future readers.

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.