深入浅出PaddlePaddle函数——paddle.to_tensor
创始人
2024-05-30 04:28:04
0

分类目录:《深入浅出PaddlePaddle函数》总目录
相关文章:
· 深入浅出PaddlePaddle函数——paddle.Tensor
· 深入浅出PaddlePaddle函数——paddle.to_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。

实例

import paddletype(paddle.to_tensor(1))
# 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'))
# 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 beCPUPlace, CUDAPinnedPlace, CUDAPlace. Default: None, means global place. If ``place`` isstring, 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:: pythonimport paddletype(paddle.to_tensor(1))# 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'))# 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 graphelse: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 oneof bool, float16, float32, float64, int32, int64. The default value is None, which means the outputdata 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:: pythonimport paddleinput = 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.dtypeelse: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 = Truereturn out

相关内容

热门资讯

因存在安全隐患,福特公司召回约... 央视记者当地时间5月14日获悉,福特汽车公司宣布,由于存在可能导致车辆在行驶过程中丧失制动功能、增加...
“土原料”变“潮产品” 青海兄弟乳业生物科技有限公司张成龙获“2025 IMW世界甜品巧克力&手工冰淇淋大赛暨2025意大利...
顺我者富 逆我者贫——解读特朗...   美国众议院共和党提出的新税收法案草案中,富人和企业投资者明显受益,而移民、顶尖私校等被特朗普长期...
青稞“链”上黄金道 产业升级加... 5月13日,海东市互助土族自治县青稞产业园内,青稞香飘满链。生产线轰鸣声中,金黄青稞粒经低温烘焙化作...
青海多措并举维护广告市场良好秩... 本报讯 (记者 董洁) 5月14日,记者从青海省市场监督管理局获悉,为切实维护全省广告市场秩序,保障...
厦门钨业股份有限公司关于向控股... 证券代码:600549 证券简称:厦门钨业 公告编号:临-2025-046厦门钨业股份有限公司关于...
安徽古麒绒材股份有限公司首次公... 安徽古麒绒材股份有限公司(以下简称“发行人”)首次公开发行不超过5,000万股人民币普通股(A股)(...
中蒙第二条跨境铁路开工 新华社呼和浩特5月14日电(记者 赵泽辉) 14日,中蒙两国能源合作重要通道——中蒙甘其毛都至嘎...
匠心与创新 本报记者 谭梅 刘珂瑜在青海兄弟乳业生物科技有限公司的生产车间里,看着张成龙专注调试冰淇淋配方的身影...
持续推动优质医疗资源扩容下沉 本报乌鲁木齐讯(全媒体记者 郑娅莉) 记者从自治区人民政府新闻办公室5月13日召开的新闻发布会上...
芜湖三联锻造股份有限公司关于投... 证券代码:001282 证券简称:三联锻造 公告编号:2025-031芜湖三联锻造股份有限公司关于...
国内首套氧化铝焙烧智能系统投运 原标题:国内首套氧化铝焙烧智能系统投运(记者滕继濮 实习记者夏天一 通讯员王晶)记者14日从中铝国际...
“头雁”竞飞强交流 经验互学促... “我常常在想,作为当代年轻人该如何实现自己的价值?到村任职的大半年时间,让我找到了答案——将个人理想...
《国务院2025年度立法工作计... 新华社北京5月14日电 经党中央、国务院同意,国务院办公厅日前印发《国务院2025年度立法工作计划...
我省举办《信访工作条例》集中宣... 本报讯 (记者 张晓英) 5月14日,省信访工作联席会议办公室、省信访局联合西宁市县两级信访部门在西...
冠城大通新材料股份有限公司关于... 证券代码:600067 证券简称:冠城新材 公告编号:临2025-018冠城大通新材料股份有限公司...
“20分钟城郊经济圈” 催生... 本报双河讯(全媒体记者 刘美惠子 纪晓贞 通讯员 吕羡林) 5月13日,在位于五师八十六团...
接力传情暖桑榆 十三师红星二场康健养老院内,陈许聪(左)陪老人玩套圈游戏(摄于4月22日)。 兵团日报常驻记者...
新大陆数字技术股份有限公司关于... 证券代码:000997 证券简称:新大陆 公告编号:2025-034新大陆数字技术股份有限公司关于召...
美国财政部对伊朗相关个人和实体... △美国财政部(资料图)当地时间5月14日,美国财政部外国资产控制办公室(OFAC)发布声明,宣布对6...