深入浅出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

相关内容

热门资讯

用这些词语写一段话,描写月夜的... 用这些词语写一段话,描写月夜的优美景色中秋之夜,坐在湖心亭品茶赏月,月光似水般倾泻于树影婆娑之中,并...
南笙在《楚乔传》中饰演谁? 南笙在《楚乔传》中饰演谁?《楚乔传》中南笙饰演的角色:兰淑仪
迪拜的机场的名称是什么 迪拜的机场的名称是什么  迪拜机场即迪拜国际机场,是阿拉伯联合酋长国迪拜的主要机场,也是阿联酋航空公...
C视频丨“机器人总动员”来啦!... 转自:四川在线 四川在线记者 薛维睿 成都观察 王翱化身...
广州多浦乐:5%以上股东减持股... 广州多浦乐电子科技股份有限公司于2025年4月23日在巨潮资讯网披露《关于持股5%以上股东减持股份的...
山羊为什么长胡子? 山羊为什么长胡子?山羊长期生长在山区,经常在树林、杂草、灌木等环境中觅食,为了保护下颚皮肤就进化出了...
“生态警务5.0”升级,崇明今... 转自:上观新闻上海市公安局崇明分局以枫桥式派出所创建为目标,持续升级“生态警务5.0”,将“全生态警...
飙涨超249%!全国第一!“西... 转自:央视财经挖掘机是基础设施建设的“标配”,是反映基础设施建设、观察固定资产投资等经济变化的风向标...
怎样概括文章主旨 怎样概括文章主旨如果想表达内容的主旨可以从文章的题目也可以成为文章的内容也可以从人物形象来判断、从文...
上海龙宇数据股份回购近5000... 上海龙宇数据股份有限公司于2025年6月17日发布关于股份回购进展公告,披露了公司在退市整理期内的股...
辞职写“因个人原因”,还能拿经... 转自:北京日报客户端“如果辞职申请上写了‘因个人原因’,是不是就再也拿不到经济补偿金了?”这是不少打...
英伟达加速布局欧洲,黄仁勋力推...   炒股就看金麒麟分析师研报,权威,专业,及时,全面,助您挖掘潜力主题机会! 21世纪经济报道记者...
在希望篮途计划里,你能看见中国... 姚明希望更多人能够关心和重视青少年体育,特别是乡村的青少年体育教育。“用网络的上话说,乡村老师们也不...
中国纸本艺术国际巡展在保加利亚... 转自:经济日报当地时间6月15日,“纸语千年 艺韵华章——中国当代纸本艺术国际巡展”首展在保加利亚索...
巴奴国际控股有限公司向港交所提... 6月16日,据港交所文件,巴奴国际控股有限公司向港交所提交上市申请书,联席保荐人为中金公司、招银国际...
内蒙古新能源装机规模突破1.4... 来源:中国新闻网 中新社呼和浩特6月16日电 (记者 李爱平)内蒙古自治区能源局16日消息,今年截至...
尺素金声丨工业企业效益恢复向好... 转自:上观新闻增长加快!日前,国家统计局数据显示:4月份,全国规模以上工业企业利润同比增长3.0%,...
英国向中东增派战机,英财政大臣... 来源:环球网 【环球网报道 记者 李梓瑜】据英国《独立报》当地时间15日报道,尽管英国皇家空军在伊朗...
痛心!湖南烟花爆炸事故已致1死... 转自:中华人民共和国应急管理部央视新闻客户端报道,据湖南临澧县委宣传部消息,6月16日8时23分许,...
国信证券-人形机器人行业周报(... (转自:研报虎)  市场表现:本周(6.9-6.13)我们构建的国信人形机器人指数下跌2.34%,弱...