使用new_zeros和zeros_like分别返回与输入相同尺寸/类型/device的tensor和ndarray

  • torch.Tensor.new_zeros(size, dtype=None, device=None)

返回尺寸为size的全为0的tensor,默认,返回的tensor与该tensor具有相同的dtype和device,可以用于在模型训练过程中创建新tensor,并保证该tensor在对应的device上

1)size: list或者tuple,定义输出tensor的尺寸

2)dtype:返回tensor的期望类型,默认与输入tensor具有相同的torch.dtype

3)device:返回tensor的期望device,默认与输入tensor具有相同的torch.device

  • 例如:
python 复制代码
tensor = torch.tensor((), dtype=torch.float64)
tensor.new_zeros((2, 3))
# tensor([[ 0.,  0.,  0.],
#         [ 0.,  0.,  0.]], dtype=torch.float64)
  • numpy.zeros_like(a, dtype=None, order='K', subok=True, shape=None)

返回与给定数组具有相同形状和类型的零数组。

a:输入的数组

dtype:输出数组的期望类型,默认与a相同

shape:输出数组的期望尺寸,默认与a相同

  • 例如:
python 复制代码
x = np.arange(6)
x = x.reshape((2, 3))
# x
# array([[0, 1, 2],
#        [3, 4, 5]])
np.zeros_like(x)
# array([[0, 0, 0],
#        [0, 0, 0]])
相关推荐
笨笨聊运维6 小时前
CentOS官方不维护版本,配置python升级方法,无损版
linux·python·centos
Gerardisite6 小时前
如何在微信个人号开发中有效管理API接口?
java·开发语言·python·微信·php
Want5956 小时前
C/C++跳动的爱心①
c语言·开发语言·c++
小毛驴8507 小时前
软件设计模式-装饰器模式
python·设计模式·装饰器模式
coderxiaohan7 小时前
【C++】多态
开发语言·c++
gfdhy7 小时前
【c++】哈希算法深度解析:实现、核心作用与工业级应用
c语言·开发语言·c++·算法·密码学·哈希算法·哈希
闲人编程7 小时前
Python的导入系统:模块查找、加载和缓存机制
java·python·缓存·加载器·codecapsule·查找器
weixin_457760007 小时前
Python 数据结构
数据结构·windows·python
Eiceblue7 小时前
通过 C# 将 HTML 转换为 RTF 富文本格式
开发语言·c#·html