深度阅读

How to check the shape of a PyTorch tensor?

作者
作者
2023年08月22日
更新时间
7.61 分钟
阅读时间
0
阅读量

To check the shape of a PyTorch tensor, you can use the .shape or .size() attribute. Here is an example:

import torch

# Create a PyTorch tensor
x = torch.tensor([[1, 2], [3, 4]])

# Get the shape of the tensor using .shape
print(x.shape)

# Get the shape of the tensor using .size()
print(x.size())

In this code, we create a PyTorch tensor x and then use .shape and .size() to get its shape. Both of these attributes return a tuple of integers representing the size of each dimension of the tensor.

Alternatively, you can use the .ndim attribute to get the number of dimensions of the tensor:

# Get the number of dimensions of the tensor
print(x.ndim)

This will output 2, which is the number of dimensions in the tensor.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。