使用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]])
相关推荐
winfredzhang4 分钟前
用 Python + wxPython 做一个个人健康饮食管理工具:从记录三餐到综合生活建议
python·wxpython·deepseek·生活习惯管理
夕除6 分钟前
shizhan--10
java·开发语言
Zhang~Ling9 分钟前
C++ 红黑树封装:myset和mymap的底层实现
开发语言·数据结构·c++·算法
原来是猿11 分钟前
为什么 C++ 需要区分左值和右值?
开发语言·c++
xier_ran14 分钟前
【infra之路】PagedAttention
java·开发语言
Irissgwe15 分钟前
十、LangGraph能力详解:工作流的常见模式
python·langchain·ai编程·工作流·langgraph
Merlyn1026 分钟前
【栈】155. 最小栈
python·算法
SilentSamsara29 分钟前
NumPy 进阶:广播机制、ufunc 与向量化计算的工程实践
开发语言·python·青少年编程·性能优化·numpy
林爷万福37 分钟前
机器学习在光谱分析中的应用:Python实现
人工智能·python·机器学习
珊瑚里的鱼37 分钟前
C++的强制类型转换
android·开发语言·c++