深入浅出PaddlePaddle函数——paddle.to_tensor

这篇具有很好参考价值的文章主要介绍了深入浅出PaddlePaddle函数——paddle.to_tensor。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

分类目录:《深入浅出PaddlePaddle函数》总目录
相关文章:
· 深入浅出TensorFlow2函数——tf.constant
· 深入浅出Pytorch函数——torch.tensor
· 深入浅出Pytorch函数——torch.as_tensor
· 深入浅出Pytorch函数——torch.Tensor
· 深入浅出PaddlePaddle函数——paddle.to_tensor
· 深入浅出PaddlePaddle函数——paddle.Tensor


通过已知的data来创建一个Tensor,Tensor类型为paddle.Tensordata可以是scalartuplelistnumpy.ndarraypaddle.Tensor。如果data已经是一个Tensor,且dtypeplace没有发生变化,将不会发生Tensor的拷贝并返回原来的Tensor。 否则会创建一个新的 Tensor,且不保留原来计算图。

语法
paddle.to_tensor(data, dtype=None, place=None, stop_gradient=True)
参数
  • data:[scalar/tuple/list/ndarray/Tensor] 初始化Tensor的数据,可以是scalartuplelistnumpy.ndarraypaddle.Tensor类型。
  • dtype:[可选,str] 创建Tensor的数据类型,可以是boolfloat16float32float64int8int16int32int64uint8complex64complex128。 默认值为None,如果 data为 python 浮点类型,则从get_default_dtype获取类型,如果data为其他类型,则会自动推导类型。
  • place:[可选, CPUPlace/CUDAPinnedPlace/CUDAPlace] 创建Tensor的设备位置,可以是 CPUPlaceCUDAPinnedPlaceCUDAPlace。默认值为None,使用全局的place
  • stop_gradient: [可选,bool] 是否阻断Autograd的梯度传导。默认值为True,此时不进行梯度传传导。
返回值

通过data创建的 Tensor。文章来源地址https://www.toymoban.com/news/detail-472401.html

实例
import paddle

type(paddle.to_tensor(1))
# <class 'paddle.Tensor'>

paddle.to_tensor(1)
# Tensor(shape=[1], dtype=int64, place=CPUPlace, stop_gradient=True,
#        [1])

x = paddle.to_tensor(1, stop_gradient=False)
print(x)
# Tensor(shape=[1], dtype=int64, place=CPUPlace, stop_gradient=False,
#        [1])

paddle.to_tensor(x)  # A new tensor will be created with default stop_gradient=True
# Tensor(shape=[1], dtype=int64, place=CPUPlace, stop_gradient=True,
#        [1])

paddle.to_tensor([[0.1, 0.2], [0.3, 0.4]], place=paddle.CPUPlace(), stop_gradient=False)
# Tensor(shape=[2, 2], dtype=float32, place=CPUPlace, stop_gradient=False,
#        [[0.10000000, 0.20000000],
#         [0.30000001, 0.40000001]])

type(paddle.to_tensor([[1+1j, 2], [3+2j, 4]], dtype='complex64'))
# <class 'paddle.Tensor'>

paddle.to_tensor([[1+1j, 2], [3+2j, 4]], dtype='complex64')
# Tensor(shape=[2, 2], dtype=complex64, place=CPUPlace, stop_gradient=True,
#        [[(1+1j), (2+0j)],
#         [(3+2j), (4+0j)]])
函数实现
def to_tensor(data, dtype=None, place=None, stop_gradient=True):
    r"""
    Constructs a ``paddle.Tensor`` from ``data`` ,
    which can be scalar, tuple, list, numpy\.ndarray, paddle\.Tensor.
    If the ``data`` is already a Tensor, copy will be performed and return a new tensor.
    If you only want to change stop_gradient property, please call ``Tensor.stop_gradient = stop_gradient`` directly.
    Args:
        data(scalar|tuple|list|ndarray|Tensor): Initial data for the tensor.
            Can be a scalar, list, tuple, numpy\.ndarray, paddle\.Tensor.
        dtype(str|np.dtype, optional): The desired data type of returned tensor. Can be 'bool' , 'float16' ,
            'float32' , 'float64' , 'int8' , 'int16' , 'int32' , 'int64' , 'uint8',
            'complex64' , 'complex128'. Default: None, infers dtype from ``data``
            except for python float number which gets dtype from ``get_default_type`` .
        place(CPUPlace|CUDAPinnedPlace|CUDAPlace|str, optional): The place to allocate Tensor. Can be
            CPUPlace, CUDAPinnedPlace, CUDAPlace. Default: None, means global place. If ``place`` is
            string, It can be ``cpu``, ``gpu:x`` and ``gpu_pinned``, where ``x`` is the index of the GPUs.
        stop_gradient(bool, optional): Whether to block the gradient propagation of Autograd. Default: True.
    Returns:
        Tensor: A Tensor constructed from ``data`` .
    Examples:
    .. code-block:: python
        import paddle
        type(paddle.to_tensor(1))
        # <class 'paddle.Tensor'>
        paddle.to_tensor(1)
        # Tensor(shape=[1], dtype=int64, place=CPUPlace, stop_gradient=True,
        #        [1])
        x = paddle.to_tensor(1, stop_gradient=False)
        print(x)
        # Tensor(shape=[1], dtype=int64, place=CPUPlace, stop_gradient=False,
        #        [1])
        paddle.to_tensor(x)  # A new tensor will be created with default stop_gradient=True
        # Tensor(shape=[1], dtype=int64, place=CPUPlace, stop_gradient=True,
        #        [1])
        paddle.to_tensor([[0.1, 0.2], [0.3, 0.4]], place=paddle.CPUPlace(), stop_gradient=False)
        # Tensor(shape=[2, 2], dtype=float32, place=CPUPlace, stop_gradient=False,
        #        [[0.10000000, 0.20000000],
        #         [0.30000001, 0.40000001]])
        type(paddle.to_tensor([[1+1j, 2], [3+2j, 4]], dtype='complex64'))
        # <class 'paddle.Tensor'>
        paddle.to_tensor([[1+1j, 2], [3+2j, 4]], dtype='complex64')
        # Tensor(shape=[2, 2], dtype=complex64, place=CPUPlace, stop_gradient=True,
        #        [[(1+1j), (2+0j)],
        #         [(3+2j), (4+0j)]])
    """
    place = _get_paddle_place(place)
    if place is None:
        place = _current_expected_place()

    if _non_static_mode():
        return _to_tensor_non_static(data, dtype, place, stop_gradient)

    # call assign for static graph
    else:
        re_exp = re.compile(r'[(](.+?)[)]', re.S)
        place_str = re.findall(re_exp, str(place))[0]

        with paddle.static.device_guard(place_str):
            return _to_tensor_static(data, dtype, stop_gradient)


def full_like(x, fill_value, dtype=None, name=None):
    """
    This function creates a tensor filled with ``fill_value`` which has identical shape of ``x`` and ``dtype``.
    If the ``dtype`` is None, the data type of Tensor is same with ``x``.
    Args:
        x(Tensor): The input tensor which specifies shape and data type. The data type can be bool, float16, float32, float64, int32, int64.
        fill_value(bool|float|int): The value to fill the tensor with. Note: this value shouldn't exceed the range of the output data type.
        dtype(np.dtype|str, optional): The data type of output. The data type can be one
            of bool, float16, float32, float64, int32, int64. The default value is None, which means the output
            data type is the same as input.
        name(str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
    Returns:
        Tensor: Tensor which is created according to ``x``, ``fill_value`` and ``dtype``.
    Examples:
        .. code-block:: python
          import paddle
          input = paddle.full(shape=[2, 3], fill_value=0.0, dtype='float32', name='input')
          output = paddle.full_like(input, 2.0)
          # [[2. 2. 2.]
          #  [2. 2. 2.]]
    """

    if dtype is None:
        dtype = x.dtype
    else:
        if not isinstance(dtype, core.VarDesc.VarType):
            dtype = convert_np_dtype_to_dtype_(dtype)

    if in_dygraph_mode():
        return _C_ops.full_like(x, fill_value, dtype, x.place)

    if _in_legacy_dygraph():
        return _legacy_C_ops.fill_any_like(
            x, 'value', fill_value, 'dtype', dtype
        )

    helper = LayerHelper("full_like", **locals())
    check_variable_and_dtype(
        x,
        'x',
        ['bool', 'float16', 'float32', 'float64', 'int16', 'int32', 'int64'],
        'full_like',
    )
    check_dtype(
        dtype,
        'dtype',
        ['bool', 'float16', 'float32', 'float64', 'int16', 'int32', 'int64'],
        'full_like/zeros_like/ones_like',
    )
    out = helper.create_variable_for_type_inference(dtype=dtype)

    helper.append_op(
        type='fill_any_like',
        inputs={'X': [x]},
        attrs={'value': fill_value, "dtype": dtype},
        outputs={'Out': [out]},
    )
    out.stop_gradient = True
    return out

到了这里,关于深入浅出PaddlePaddle函数——paddle.to_tensor的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 深入浅出PaddlePaddle函数——paddle.ones

    分类目录:《深入浅出PaddlePaddle函数》总目录 相关文章: · 深入浅出PaddlePaddle函数——paddle.Tensor · 深入浅出PaddlePaddle函数——paddle.ones · 深入浅出PaddlePaddle函数——paddle.zeros · 深入浅出PaddlePaddle函数——paddle.full · 深入浅出PaddlePaddle函数——paddle.ones_like · 深入浅出Paddl

    2024年02月05日
    浏览(32)
  • 深入浅出PaddlePaddle函数——paddle.zeros

    分类目录:《深入浅出PaddlePaddle函数》总目录 相关文章: · 深入浅出PaddlePaddle函数——paddle.Tensor · 深入浅出PaddlePaddle函数——paddle.ones · 深入浅出PaddlePaddle函数——paddle.zeros · 深入浅出PaddlePaddle函数——paddle.full · 深入浅出PaddlePaddle函数——paddle.ones_like · 深入浅出Paddl

    2024年02月06日
    浏览(27)
  • 深入浅出PaddlePaddle函数——paddle.arange

    分类目录:《深入浅出PaddlePaddle函数》总目录 相关文章: · 深入浅出TensorFlow2函数——tf.range · 深入浅出Pytorch函数——torch.arange · 深入浅出PaddlePaddle函数——paddle.arange 语法 当 dtype 表示浮点类型时,为了避免浮点计算误差,建议给 end 加上一个极小值 epsilon ,使边界可以更

    2024年02月05日
    浏览(58)
  • 深入浅出PaddlePaddle函数——paddle.full_like

    分类目录:《深入浅出PaddlePaddle函数》总目录 相关文章: · 深入浅出PaddlePaddle函数——paddle.Tensor · 深入浅出PaddlePaddle函数——paddle.ones · 深入浅出PaddlePaddle函数——paddle.zeros · 深入浅出PaddlePaddle函数——paddle.full · 深入浅出PaddlePaddle函数——paddle.ones_like · 深入浅出Paddl

    2024年02月05日
    浏览(37)
  • 深入浅出PaddlePaddle函数——paddle.zeros_like

    分类目录:《深入浅出PaddlePaddle函数》总目录 相关文章: · 深入浅出PaddlePaddle函数——paddle.Tensor · 深入浅出PaddlePaddle函数——paddle.ones · 深入浅出PaddlePaddle函数——paddle.zeros · 深入浅出PaddlePaddle函数——paddle.full · 深入浅出PaddlePaddle函数——paddle.ones_like · 深入浅出Paddl

    2024年02月07日
    浏览(28)
  • 深入浅出PaddlePaddle函数——paddle.ones_like

    分类目录:《深入浅出PaddlePaddle函数》总目录 相关文章: · 深入浅出PaddlePaddle函数——paddle.Tensor · 深入浅出PaddlePaddle函数——paddle.ones · 深入浅出PaddlePaddle函数——paddle.zeros · 深入浅出PaddlePaddle函数——paddle.full · 深入浅出PaddlePaddle函数——paddle.ones_like · 深入浅出Paddl

    2024年02月05日
    浏览(29)
  • 深入浅出C语言—【函数】上

       目录 1.函数的概念 2.C语言函数的分类 2.1 库函数 2.1.1 strcpy库函数举例学习方式 2.1.2 库函数扩展知识 2.2 自定义函数 2.2.1求两个整数中的较大值 3. 函数的参数 3.1 实际参数(实参) 3.2 形式参数(形参) 4. 函数的调用 4.1 传值调用 4.2 传址调用 老铁们,网址自取,记得一键

    2024年02月07日
    浏览(27)
  • 深入浅出C语言—【函数】下

    函数和函数之间可以根据实际的需求进行组合的,也就是互相调用的。 注意: 函数可以嵌套调用,但是不能嵌套定义。 把一个函数的返回值作为另外一个函数的参数。 上面的strlen函数是求数组长度的库函数, 特别注意的是,当数组为字符数组时,数组的末尾会自动放一个

    2024年02月17日
    浏览(57)
  • 深入浅出Pytorch函数——torch.zeros

    分类目录:《深入浅出Pytorch函数》总目录 相关文章: · 深入浅出Pytorch函数——torch.Tensor · 深入浅出Pytorch函数——torch.ones · 深入浅出Pytorch函数——torch.zeros · 深入浅出Pytorch函数——torch.full · 深入浅出Pytorch函数——torch.ones_like · 深入浅出Pytorch函数——torch.zeros_like · 深

    2024年02月07日
    浏览(45)
  • 深入浅出Pytorch函数——torch.tensor

    分类目录:《深入浅出Pytorch函数》总目录 相关文章: · 深入浅出TensorFlow2函数——tf.constant · 深入浅出Pytorch函数——torch.tensor · 深入浅出Pytorch函数——torch.as_tensor · 深入浅出Pytorch函数——torch.Tensor · 深入浅出PaddlePaddle函数——paddle.to_tensor 基于 data 构建一个没有梯度历史

    2024年02月04日
    浏览(85)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包