张量(Tensor)
张量可以简单理解为多维数组,理论上张量是任意维度。
张量操作基本方法
首先检验一下终端的pytorch是否安装成功: Win + R 打开CMD 命令,输入“ipython”然后构建一个张量并输出
In [1]: import torch
In [2]: torch.Tensor(3,3)
Out[2]:
tensor([[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]])
1.判断一个对象是否为Tensor
import torch
import numpy as np
a = np.arange(1, 10)
b = torch.Tensor(10)
print(a)
print(torch.is_tensor(a))
print(b)
print(torch.is_tensor(b))
[1 2 3 4 5 6 7 8 9]
False
tensor([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
True
(不得不说刚刚犯了一个很蠢的错误,我新建了一个 torch.py 文件来试验这些语句,因为要导入torch模块,然后就把这个文件导入了而没有导入正规的 “torch.py”,所以他一直报错说torch没有 Tensor这个模块,真是被自己蠢到了23333)
2.获取张量中元素个数
In [1]: import torch
In [2]: a=torch.Tensor(3,4)
In [3]: print(torch.numel(a))
12
3.创建单位矩阵
In [4]: torch.eye(3,3)
Out[4]:
tensor([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
4.将Numpy数组转化为Tensor
In [5]: import numpy as np
In [6]: a = np.arange(1,10)
In [7]: b = np.ndarray((2,3))
In [8]: print(torch.from_numpy(a))
tensor([1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=torch.int32)
In [9]: print(torch.from_numpy(b))
tensor([[0., 0., 0.],
[0., 0., 0.]], dtype=torch.float64)
5.构造等差数列
In [26]: print(torch.arange(1,10))
tensor([1, 2, 3, 4, 5, 6, 7, 8, 9])
In [13]: print(torch.linspace(1,8,3))
tensor([1.0000, 4.5000, 8.0000])
In [14]: print(torch.linspace(1,8,4))
tensor([1.0000, 3.3333, 5.6667, 8.0000])
三个参数分别为初始值,终值和元素个数 lin(线性)-space(空间)
类似的还有指数空间 log-space
In [18]: print(torch.logspace(1,5,5))
tensor([1.0000e+01, 1.0000e+02, 1.0000e+03, 1.0000e+04, 1.0000e+05]) # e是乘以10的后面次
6.初始化矩阵
这个和Numpy非常类似
In [19]: print(torch.ones(2,3))
tensor