使用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 小时前
数据库实战:FastAPI + SQLAlchemy 2.0 + Alembic 从零搭建,踩坑实录
python·fastapi·web·sqlalchemy·db·asyncio·alembic
用户8356290780516 小时前
Python 实现 PowerPoint 形状动画设置
后端·python
ponponon7 小时前
时代的眼泪,nameko 和 eventlet 停止维护后的项目自救,升级和替代之路
python
Flittly7 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(5)Skills (技能加载)
python·agent
敏编程7 小时前
一天一个Python库:pyarrow - 大规模数据处理的利器
python
Flittly9 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(4)Subagents (子智能体)
python·agent
明月_清风16 小时前
Python 装饰器前传:如果不懂“闭包”,你只是在复刻代码
后端·python
明月_清风16 小时前
打破“死亡环联”:深挖 Python 分代回收与垃圾回收(GC)机制
后端·python
ZhengEnCi1 天前
08c. 检索算法与策略-混合检索
后端·python·算法
明月_清风2 天前
Python 内存手术刀:sys.getrefcount 与引用计数的生死时速
后端·python