All Courses

# How can I convert a NumPy array of tensors to a tensor of tensors?

##### By Pp5344229@gmail.com, a month ago

How can I convert a NumPy array of tensors to a tensor of tensors?

Numpy array
Numpy
Array
Tensor of tensors
##### Goutamp777

Assuming that you have a NumPy array of tensors where each element of the array is a tensor of the same shape, you can use the `torch.stack()` function from the PyTorch library to convert the NumPy array of tensors to a tensor of tensors. Here's how:

First, you'll need to import the PyTorch library:

```import torch
```

Then, assuming that your NumPy array of tensors is named numpy_array, you can convert it to a tensor of tensors using the torch.stack() function:

```tensor_of_tensors = torch.stack([torch.from_numpy(tensor) for tensor in numpy_array])
```

Here, torch.from_numpy() is used to convert each NumPy array element to a PyTorch tensor. The resulting tensors are then stacked along a new dimension, which is created by default as the first dimension.

The resulting tensor_of_tensors will be a PyTorch tensor with one additional dimension compared to the input NumPy array. For example, if your input NumPy array had shape (N, H, W), where N is the number of tensors in the array and H and W is the height and width of each tensor, the resulting tensor_of_tensors would have shape (N, H, W).

#### How To Land a Job in Data Science? Apr 6th (7:00 PM) 190 Registered
More webinars

#### Related Discussions

Running random forest algorithm with one variable

View More