xtensor-stack / xtensor

C++ tensors with broadcasting and lazy computing
BSD 3-Clause "New" or "Revised" License
3.33k stars 398 forks source link

how to convert this numpy code to xtensor #2369

Open thancaocuong opened 3 years ago

thancaocuong commented 3 years ago

Hi. could you help me to convert this numpy code to xtensor. I've try many times, but problem is that from indices, I cannot get the value from numpy array

import numpy as np
np.random.seed(42)
a = np.random.randint(0, 5, (3, 2, 2)) 
b = a[:, a[0] > 2] # 
print(b.shape) # the shape of b should be 3xN
zhujun98 commented 3 years ago

This is my solution:

#include <iostream>
#include <xtensor/xtensor.hpp>
#include <xtensor/xrandom.hpp>
#include <xtensor/xio.hpp>
#include <xtensor/xview.hpp>
#include <xtensor/xbroadcast.hpp>
#include <xtensor/xadapt.hpp>

int main()
{
  xt::random::seed(42);
  xt::xtensor<int, 3> a = xt::random::randint<int>({3, 2, 2}, 0, 5);
  auto flt = xt::view(a, 0) > 2;
  std::vector<int> shape = {int(a.shape(0)), xt::sum(flt)()};
  xt::xtensor<int, 2> b = xt::reshape_view(xt::filter(a, xt::broadcast(flt, a.shape())), shape);
  std::cout << xt::adapt(b.shape());
  return 0;
}

In Python, b = a[:, a[0] > 2] is called advanced slicing, which will make a copy of the data instead of a view. In my code, I figure out the shape of the output manually. Maybe others can come up with a better solution.

thancaocuong commented 3 years ago

@zhujun98 thanks. I have the same solution as yours. But I think some one could give me better solution.