In this code, we use the torch::tensor function to create a tensor from a nested initializer list of values. The cuda() method is then called on the tensor to move it to the GPU for computation. Finally, we use std::cout to print the tensor to the console, which will display the tensor’s values as well as its shape.
The output of this code will be:
As you can see, the tensor is displayed as a grid of values, with each row representing a row in the tensor, and each column representing a column in the tensor. The values are printed with four decimal places by default, but you can adjust the precision with C++’s std::setprecision function if needed.
Next, let’s explore how to access individual elements of a tensor. We can use square brackets [] to index into the tensor, just like we would with a regular C++ array. For example, to access the item at index 0 in the tensor, we can use the following code:
The output will be:
Note that we used the cuda() method again to move the individual element back to the GPU for printing. You can also access elements of a tensor on the CPU by omitting the cuda() method.
In addition to indexing, PyTorch provides many other operations for manipulating tensors, such as element-wise arithmetic, matrix operations, reshaping, and more. You can find a comprehensive list of tensor operations in the PyTorch documentation.
Finally, it’s worth mentioning that PyTorch tensors are mutable, meaning you can modify their values in place. For example, you can change the value of an element in a tensor by assigning a new value to it using the assignment operator =. Keep in mind that these modifications are done in place and can affect the original tensor.
In conclusion, understanding how to create and manipulate tensors is fundamental to working with PyTorch in C++. In this blog post, we covered how to create a tensor with specified values and move it to the GPU, how to access individual elements of a tensor, and the mutability of tensors. With this knowledge, you can start experimenting with tensors in your own C++ code and unlock the power of PyTorch for deep learning and data science applications. Happy coding!

