const at::Tensor Matrix = torch::tensor({ { 68.56, 98.98 }, { 65.01, 98.05 } }).cuda();
std::cout << "Matrix: \n" << Matrix << std::endl;
std::cout << "Matrix Dimension: " << Matrix.ndimension() << std::endl;
std::cout << "Matrix item at index 0: " << Matrix[0].cuda() << std::endl;
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.
const at::Tensor Matrix = torch::tensor({ { 68.56, 98.98 }, { 65.01, 98.05 } }).cuda();
The output of this code will be:
Matrix:
68.5600 98.9800
65.0100 98.0500
[ CUDAFloatTensor{2,2} ]
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:
std::cout << "Matrix item at index 0: " << Matrix[0].cuda() << std::endl;
The output will be:
Matrix item at index 0: 68.56
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!