1

Let price be a PyTorch tensor with shape (num_days, num_products).

Let purchased_product_by_day be an integer tensor with shape (num_days,), with values in range(num_products).

Intuitively, price lists the price, for each day, of each product, and purchased_product_by_day are the indices of purchased products, one per day.

To obtain a tensor containing the expense per day, I can write

price[list(range(num_days)), purchased_product_by_day]

but this iterates over days at the Python level. I would like to obtain the same tensor on the C level.

I tried

price[:, purchased_product_by_day]

but that does not work, being equivalent to indexing each row by purchased_product_by_day for each day and stacking the results.

Is there a way to do that without iteration at the Python level?

1 Answer 1

2

Based on Row-wise Element Indexing in PyTorch for C++, the solution in Python is

price.gather(1, purchased_product_by_day.unsqueeze(1)).squeeze()

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

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.