今天我在理解一个例子的时候,我使用了一下torch.zeros却莫名秒的报错
1.原始code
batch_size=64,
dim=4
def a(batch_size,dim):
out = torch.zeros(batch_size, dim)
print(out)
out[np.arange(64), 2] = 1
print(out)
a(batch_size,dim)
2.error:
TypeError: zeros(): argument 'size' (position 1) must be tuple of ints, not tuple
3.原因分析:
如果直接使用torch.zeros((64,2))这是没有问题的,但是传递参数给它就爆错。
因此参数肯定有问题:
torch.zeros的参数需要是tensor类型的
3.1 修改code
import torch
import numpy as np
batch_size=64,
dim=4
==========(将其转换为torch.tensor)
batch_size=torch.tensor(batch_size)
dim=torch.tensor(dim)
def a(batch_size,dim):
out = torch.zeros((batch_size, dim))
print(out)
out[np.arange(64), 2] = 1
print(out)
a(batch_size,dim)