Help on indexing a tuple in libtorch please

Hi, All,

I would like to convert the following from pytorch to libtorch. The pytorch code is
acc = torch.mean((output_label.max(1)[1] == y).float())

I convert it as:
float acc = torch::mean((output_label.max(1)[1] == y));

The building error is:
error: no match for ‘operator[]’ (operand types are ‘std::tuple<at::Tensor, at::Tensor>’ and ‘int’)

Any suggestions to correct it please ?

Much appreciated

Try to use std::get<1>(output_label.max(1)).

Thanks a lot.
auto acc = torch::mean(get<1>(output_label.max(1))== y); works

But
float acc = torch::mean(get<1>(output_label.max(1))== y); doesnot work

How shall I convert acc from tensor to float in this case please ?

Thanks.

I guess .item<float>() should work.

Thanks, yep it works.

Another inquiry is that in the return,

I would like to return
Loas.data.cpu() and acc

So I write

return{loss.dats.cpu(), acc}

It says “ no matching constructor for initialization of std::vectortorch::Tensor

Any suggestions to solve that please .

Much appreciated

Don’t use the .data attribute, as it might yield unwanted side effects, and try to push the tensor to the device with tensor.to(at::kCPU);.

Thanks,

Do you mean to use return{loss.to(at::kCPU), acc1},

I think the main difficulty is that the first return argument is tensor while the second return argument is float.

So just wonder if there is a way to return two arguements with different types or I need to convert them to be in the same type.

Thanks.

I find this is no error
return{loss, acc};

I am tring to include data into the return.
Thanks,

Actually, it is not C++ syntax. It is recommended to return a struct instead.