使用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]])
相关推荐
淘气的小猴子3 分钟前
Python 魔术方法入门
python
我要见SA姐112 分钟前
DeepSeek Harness 开源贡献手记:从 Issue 到 Merge 的完整旅程
ide·vscode·python·自动化·编辑器
Tairitsu_H40 分钟前
[C++] 拷贝构造还是赋值重载?类默认成员函数细节详解
开发语言·c++·类和对象
沉下心来学鲁班1 小时前
初识DeepAgents搭建第一个智能体
人工智能·python·langchain
goodlook01231 小时前
opencode调用本地模型一(1.18.30版本安装)
开发语言
菜鸟~noob2331 小时前
【电子战】第14篇:TOA 定位——圆交汇与到达时间【含matlab代码】
开发语言·matlab
ctlover1 小时前
数据结构:树
数据结构·python
itmigrate2 小时前
Redis 开发高频隐形踩坑记录
开发语言·java-ee
白远山2 小时前
本地游戏代练源码开发实战:架构设计与核心功能实现指南
java·开发语言·架构·需求分析
触底反弹2 小时前
🐍 Python 语法全景图:一个 print() 引发的深度探索
python