PyTorch中的torch.linspace
torch.linspace(start, end, steps=100, out=None, dtype=None,layout=torch.strided, device=None, requires_grad=False)
start: 开始值
end:结束值
steps:分割的点数,默认为100
import torchdrop_path_rate = 0.1depths = [2, 2, 2]dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] print(dpr)输出:[0.0, 0.019999999552965164, 0.03999999910593033, 0.06000000238418579, 0.07999999821186066, 0.10000000149011612]
上例中涉及到x.item()方法
从item()方法中可以看出,item()是将一个张量的值,以一个python数字形式返回,但该方法只能包含一个元素的张量,对于包含多个元素的张量,可以考虑tolist()方法。
该操作是不能微分的;即不可求导,不能调用backward()方法进行反向传播。
import tensora = torch.Tensor([8.0])print(a)print(type(a))b = a.item()print(b)print(type(b))输出:
tensor([8.])
<class 'torch.Tensor'>
8.0
<class 'float'>
多个张量转化方法tensor.tolist()
import tensorc = torch.Tensor([6.0, 7.0,8.0])print(c)print(type(c))d = c.tolist()print('d', d, type(d))输出:
tensor([6., 7., 8.])
<class 'torch.Tensor'>
d [6.0, 7.0, 8.0] <class 'list'>