14、分点
用linspace建立分点
a = np.linspace(0, 5, 6)
print(a)
b = torch.linspace(0, 5, 6)
print(b)
结果
[0. 1. 2. 3. 4. 5.]
tensor([0., 1., 2., 3., 4., 5.])
15、单值
用unique消除重复元素
np.unique([1,2,1,3])
torch.unique(torch.Tensor([1,2,1,3]))
结果
[1 2 3]
tensor([1., 2., 3.])
16、切片
冒号表达式做下标
a = np.array([1,2,3,4,5,6])
b = torch.tensor([1,2,3,4,5,6])
print(a[1:3])
print(b[1:3])
结果
[2 3]
tensor([2, 3])
17、过滤
用逻辑下标筛选元素
a = np.array([1,2,3,4,5,6])
b = torch.tensor([1,2,3,4,5,6])
print(a[a > 2])
print(b[b > 2])
结果
[3 4 5 6]
tensor([3, 4, 5, 6])
18、下标
满足条件的元素下标
a = np.array([11,12,13,14,15])
b = torch.tensor([11,12,13,14,15])
print(np.where(a > 13))
print(torch.where(b > 13))
结果
(array([3, 4], dtype=int64),)
(tensor([3, 4]),)
19、转置
代码
a = np.array([[1,2],
[3,4]])
b = torch.tensor([[1,2],
[3,4]])
print(a.T)
print(b.T)
结果
[[1 3]
[2 4]]
tensor([[1, 3],
[2, 4]])
20、排序
代码
a = np.array([2,4,3,5,1])
b = torch.Tensor([2,4,3,5,1])
print(a)
print(b)
结果
[2 4 3 5 1]
tensor([2., 4., 3., 5., 1.])
21、量词
全称量词all、存在量词any
a = np.array([1,2,3,4,5])
b = torch.tensor([1,2,3,4,5])
print(a>2)
print(b>2)
print((a>2).all())
print((b>2).all())
结果
[False False True True True]
tensor([False, False, True, True, True])
False
tensor(False)
22、元素类型
调用构造函数tensor,可指定元素类型,而且不允许修改
a = np.array([1,2,3,4,5],dtype=np.int8)
print(a)
b = torch.tensor([1,2,3,4,5],dtype=torch.int8)
print(b)
结果
[1 2 3 4 5]
tensor([1, 2, 3, 4, 5], dtype=torch.int8)
23、维度
查看数据维度
a = np.arange(24).reshape(2,3,4)
print(a.ndim)
b = torch.arange(24).reshape(2,3,4)
print(b.ndim)
结果
3
3
24、改变元素类型
不要直接修改numpy数组的dtype,而要使用astype
a = np.array([1,2,3,4,5,6,7,8],dtype=np.int8)
print(a.astype(float))
a.dtype = np.float
print(a)
b = torch.tensor([1,2,3,4,5,6],dtype=torch.int8)
print(b.float())
结果
[1. 2. 3. 4. 5. 6. 7. 8.]
[5.44760372e-270]
tensor([1., 2., 3., 4., 5., 6., 7., 8.])
25、全1
类似有zeros
a = np.ones((2,2))
b = torch.ones((2,2))
print(a)
print(b)
结果
[[1. 1.]
[1. 1.]]
tensor([[1., 1.],
[1., 1.]])
26、同形
建立相同形状的数据对象,默认元素类型不同
c = np.array([[0,1,2],[3,4,5]])
a = np.empty_like(c)
print(a)
print(a.dtype)
c = torch.Tensor([[0,1,2],[3,4,5]])
b = torch.empty_like(c)
print(b)
print(b.dtype)
结果
[[1 2 3]
[4 5 6]]
int32
tensor([[0, 0, 0],
[0, 0, 0]], dtype=torch.int32)
torch.int32