使用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]])
相关推荐
_一条咸鱼_1 小时前
Python 名称空间与作用域深度剖析(二十七)
人工智能·python·面试
_一条咸鱼_1 小时前
Python之函数对象+函数嵌套(二十六)
人工智能·python·面试
_一条咸鱼_1 小时前
Python 文件操作之修改(二十二)
人工智能·python·面试
_一条咸鱼_1 小时前
Python 闭包函数:原理、应用与深度解析(二十八)
人工智能·python·面试
_一条咸鱼_1 小时前
Python 之文件处理编码字符(二十)
人工智能·python·面试
_一条咸鱼_1 小时前
Python 装饰器:代码功能的优雅增强(二十九)
人工智能·python·面试
_一条咸鱼_1 小时前
Python 文件处理(二十一)
人工智能·python·面试
_一条咸鱼_1 小时前
Python函数的基本使用(二十三)
人工智能·python·面试
_一条咸鱼_1 小时前
Python 之函数 Type - hinting(二十四)
人工智能·python·面试
_一条咸鱼_1 小时前
Python 之函数的参数(二十五)
人工智能·python·面试