torch.tensor 和 torch.Tensor 有什么区别? [英] What is the difference between torch.tensor and torch.Tensor?

查看:42
本文介绍了torch.tensor 和 torch.Tensor 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从 0.4.0 版本开始,可以使用 torch.tensortorch.Tensor

有什么区别?提供这两个非常相似且令人困惑的替代方案的原因是什么?

解决方案

在 PyTorch 中 torch.Tensor 是主要的张量类.所以所有的张量都只是 torch.Tensor 的实例.

当你调用 torch.Tensor() 时,你会得到一个没有任何 data 的空张量.

相比之下 torch.tensor 是一个返回张量的函数.在 文档 中,它说:

<块引用>

torch.tensor(data, dtype=None, device=None, requires_grad=False) → Tensor

data构造一个张量.

<小时>这也解释了为什么通过调用创建一个没有 `data` 的 `torch.Tensor` 的空张量实例是没有问题的:

tensor_without_data = torch.Tensor()

但另一方面:

tensor_without_data = torch.tensor()

会导致错误:

---------------------------------------------------------------------------TypeError Traceback(最近一次调用最后一次)<ipython-input-12-ebc3ceaa76d2>在 <module>()---->1 火炬张量()类型错误:tensor() 缺少 1 个必需的位置参数:数据";

<小时>但总的来说,没有理由选择 `torch.Tensor` 而不是 `torch.tensor`.`torch.Tensor` 也缺少文档字符串.

在没有 data 的情况下创建张量的类似行为,例如:torch.Tensor() 可以使用:

torch.tensor(())

输出:

张量([])

Since version 0.4.0, it is possible to use torch.tensor and torch.Tensor

What is the difference? What was the reasoning for providing these two very similar and confusing alternatives?

解决方案

In PyTorch torch.Tensor is the main tensor class. So all tensors are just instances of torch.Tensor.

When you call torch.Tensor() you will get an empty tensor without any data.

In contrast torch.tensor is a function which returns a tensor. In the documentation it says:

torch.tensor(data, dtype=None, device=None, requires_grad=False) → Tensor

Constructs a tensor with data.


This also also explains why it is no problem creating an empty tensor instance of `torch.Tensor` without `data` by calling:

tensor_without_data = torch.Tensor()

But on the other side:

tensor_without_data = torch.tensor()

Will lead to an error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-12-ebc3ceaa76d2> in <module>()
----> 1 torch.tensor()

TypeError: tensor() missing 1 required positional arguments: "data"


But in general there is no reason to choose `torch.Tensor` over `torch.tensor`. Also `torch.Tensor` lacks a docstring.

Similar behaviour for creating a tensor without data like with: torch.Tensor() can be achieved using:

torch.tensor(())

Output:

tensor([])

这篇关于torch.tensor 和 torch.Tensor 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆