Imperator123
Imperator123

Reputation: 609

How do we index a tensor in python?

I'm trying to understand the following code.

content_array[:, :, :, 0] -= 103.939
content_array[:, :, :, 1] -= 116.779
content_array[:, :, :, 2] -= 123.68
content_array = content_array[:, :, :, ::-1]

style_array[:, :, :, 0] -= 103.939
style_array[:, :, :, 1] -= 116.779
style_array[:, :, :, 2] -= 123.68
style_array = style_array[:, :, :, ::-1]

content_array and style_array are arrays with dimensions of (1, 512, 512, 3) respectively.

What i don't really understand is the indexing([:, :, :, 0], [:, :, :, 1], [:, :, :, 2]). Does this means we are indexing each dimension? and why do we use ':'?

Upvotes: 0

Views: 4360

Answers (1)

Anis
Anis

Reputation: 3094

One of numpy's most interesting indexing features, is the ability to index slices. Slices are subarrays in a given dimensions, they are written in the form of i:j:k where i is the starting index, j the ending (not included), and k the step. Specifying all 3 parameters would be tedious most of the time, that's why they all have default values. i=0, j=n where n is the length of the array, k=1. Therefore selecting all the elements along a dimension would come down to writting array[::] for which a syntactic sugar is array[:].

Therefore content_array[:, :, :, 0] is an array of dimension (1, 512, 512). And writing content_array[:, :, :, 0] -= 103.939 means set all the values of the array taken by selecting all the elements such that they have index 0 on last dimension, and decrement all these elements by 103.939.

I would recommend that you read https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html.

Upvotes: 2

Related Questions