初识pytorch
PyTorch是一个开源的Python机器学习库,基于Torch,用于自然语言处理等应用程序,是目前最火热的深度学习框架之一(此外还有Tensorflow、Apache SystemML等)。
一、环境配置
我使用的是谷歌的 Colab,它是一个 Jupyter 笔记本环境,已经默认安装好 pytorch,不需要进行任何设置就可以使用,并且完全在云端运行。使用方法可以参考 Rogan 的博客:https://www.cnblogs.com/lfri/p/10471852.html
二、PyTorch 之 tensor(张量)理解
个人理解是,PyTorch框架下,所有的数据都以tensor作为单位(容器)来存储和和运算,而PyTorch相较于Tensorflow或其它框架的特点和优势也是以tensor为基本单位,再泛化(不知道这样讲对不对,我是这样理解的)到variable和nn.Module这些层次,三个抽象之间联系紧密,可以同时进行修改和操作。
tensor的基础练习
import torch
#创建一个3*2的随机矩阵
x = torch.rand(3,2)
print(x)
tensor([[0.8513, 0.7758],
[0.2938, 0.2522],
[0.3958, 0.5396]])
#x置零,并用x新建张量y,如果这里不指定类型,y会继承x的类型
x = torch.zeros(3,2, dtype = torch.long)
y = x.new_ones(3,2, dtype = torch.double)
print(y)
tensor([[1., 1.],
[1., 1.],
[1., 1.]], dtype=torch.float64)
#张量的简单运算与使用
z = x + y
print(z)
z = z + 1
print(z)
tensor([[1., 1.],
[1., 1.],
[1., 1.]], dtype=torch.float64)
tensor([[2., 2.],
[2., 2.],
[2., 2.]], dtype=torch.float64)
#直接从数据构造张量
x = torch.tensor([1, 1.2])
print(x)
tensor([1.0000, 1.2000])
#访问方式,下标访问和索引
x = torch.rand(5,5)
print(x)
print(x[1,3])
print(x[:,1])
ensor([[0.0236, 0.8149, 0.5428, 0.1930, 0.9221],
[0.5929, 0.2634, 0.7653, 0.0631, 0.5798],
[0.8886, 0.9409, 0.6921, 0.1759, 0.2561],
[0.9100, 0.5099, 0.0211, 0.7106, 0.7640],
[0.0055, 0.5049, 0.4479, 0.0751, 0.2313]])
tensor(0.0631)
tensor([0.8149, 0.2634, 0.9409, 0.5099, 0.5049])
参考博客
https://blog.csdn.net/believe448/article/details/89059412
https://blog.csdn.net/bestrivern/article/details/89433023