a.chunk(k)
对张量a进行成k块,但如果指定轴的元素个数被chunks除不尽,最后一块的元素个数会少。
input = torch.randint(0, 8, (5,), dtype=torch.int64)
weights = torch.linspace(0, 1, steps=5)
input, weights
(tensor([4, 3, 6, 3, 4]),
tensor([ 0.0000, 0.2500, 0.5000, 0.7500, 1.0000])
torch.bincount(input)
tensor([0, 0, 0, 2, 2, 0, 1])
input.bincount(weights)
tensor([0.0000, 0.0000, 0.0000, 1.0000, 1.0000, 0.0000, 0.5000])
.item()的用法
.item()用于在只包含一个元素的tensor中提取值,注意是只包含一个元素,否则的话使用.tolist()
x = torch.tensor([1])
print(x.item())
y = torch.tensor([2,3,4,5])
print(y.item())
# 输出结果如下
1
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-16-e884e6ada778> in <module>
2 print(x.item())
3 y = torch.tensor([2,3,4,5])
----> 4 print(y.item())
ValueError: only one element tensors can be converted to Python scalars
torch.clamp(input, min, max, out=None)
作用:限幅。将input的值限制在[min, max]之间,并返回结果。out (Tensor, optional) – 输出张量,一般用不到该参数。
import torch
a = torch.arange(9).reshape(3, 3) # 创建3*3的tensor
b = torch.clamp(a, 3, 6) # 对a的值进行限幅,限制在[3, 6]
print('a:', a)
print('shape of a:', a.shape)
print('b:', b)
print('shape of b:', b.shape)
''' 输出结果 '''
a: tensor([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
shape of a: torch.Size([3, 3])
b: tensor([[3, 3, 3],
[3, 4, 5],
[6, 6, 6]])
shape of b: torch.Size([3, 3])
判断列表为空
list_temp = []
if len(list_temp):
# 存在值即为真
else:
# list_temp是空的
list_temp = []
if list_temp:
# 存在值即为真
else:
# list_temp是空的
第二种优于第一种!