PyTorch的基本概念

什么是 pytorch ,为什么选择 pytorch ?

PyTorch是一个开源的Python机器学习库,基于Torch,由Facebook团队开发。
pytorch的特点是变成是动态图的,便于理解。而且现在的性能比tf好。支持GPU加速,以及自动求梯度。

Pytroch的安装

安装:点击https://pytorch.org/,选择版本,操作系统,管理工具,python版本,CUDA版本(版本可通过命令行nvcc --version (win)获取)。
本地cuda版本
复制command到相应的工具即可。在我的电脑上是CUDA10+python3.6+pytorch1.0

配置Python环境

python环境配置,建议使用Anaconda,集成环境以及大量数据科学包。https://www.anaconda.com/
下载好之后一路next,最后将python路径加入系统环境变量之中即可。本文使用python3.6

准备Python管理器

同上使用anaconda来管理环境

通过命令行安装PyTorch

以我为例,命令如下:

conda install pytorch torchvision cudatoolkit=10.0 -c pytorch 

1.0版本需要去之前的版本寻找,推介下载下来本地安装。conda国内镜像现在都不好使了。

PyTorch基础概念通用代码实现流程(实现一个深度学习的代码流程)

举一个线性拟合的例子。
主要使用到pytorch的tensor模块和nn模块。
对于tensor模块可以理解为pytorch里面的numpy。基本操作和nunpy非常接近。
举几个例子:

常用操作

创建几个随机数:

x = torch.rand(5,3)
print(x)
---
tensor([[0.1435, 0.6077, 0.4994],
    [0.4632, 0.8732, 0.8359],
    [0.9913, 0.6121, 0.7297],
    [0.3953, 0.0492, 0.6139],
    [0.2065, 0.3462, 0.3222]])

创建全0数组并指定long类型:

x = torch.zeros(5,3,dtype=torch.long)
print(x)
-----
tensor([[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]])

加法:

y = torch.rand(5, 3)
print(torch.add(x,y))
-----
tensor([[ 0.5214,  2.4466,  2.2532],
        [ 0.4176, -0.4494,  0.5796],
        [ 0.1444,  1.2509,  1.2620],
        [-0.3300,  1.2165,  0.6565],
        [ 2.9908,  1.8187,  0.2060]])

更改shape:

x = torch.randn(4,4)
y = x.view(16)
z = x.view(-1,8)
print(x.size(), y.size(), z.size())
----
torch.Size([4, 4]) torch.Size([16]) torch.Size([2, 8])

numpy和tensor的转换:

# tensor convert to Numpy
a = torch.ones(5)
print(a)
print(type(a.numpy()))
---
tensor([1., 1., 1., 1., 1.])
<class 'numpy.ndarray'>

numpy->tensor

a = np.ones(5)
b = torch.from_numpy(a)
np.add(a,1,out=a)
print(a)
print(b)
------
[2. 2. 2. 2. 2.]
tensor([2., 2., 2., 2., 2.], dtype=torch.float64)

搭建网络模型:
nn模块主要是用于搭建模型。如下是一个简单的线性回归:

class Net(torch.nn.Module):
    def __init__(self, n_feature, n_hidden, n_output):
        super(Net, self).__init__()
        self.hidden = torch.nn.Linear(n_feature, n_hidden)   # hidden layer
        self.predict = torch.nn.Linear(n_hidden, n_output)   # output layer

    def forward(self, x):
        x = F.relu(self.hidden(x))      # activation function for hidden layer
        x = self.predict(x)             # linear output
        return x
    
net = Net(1,10,1)
net

输出结构模型:

Net(
  (hidden): Linear(in_features=1, out_features=10, bias=True)
  (predict): Linear(in_features=10, out_features=1, bias=True)
)

进行训练并且可视化:

optimizer = torch.optim.SGD(net.parameters(), lr=0.3)
loss_func = torch.nn.MSELoss()

for t in range(100):
    prediction = net(x)
    
    loss = loss_func(prediction,y)
    
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
    
    if t%10 ==0 :
        plt.cla()
        plt.scatter(x.data.numpy(),y.data.numpy())
        plt.plot(x.data.numpy(),prediction.data.numpy(),'r-',lw=5)
        plt.text(0.5,0,'Loss = %4f'% loss.data.numpy(),fontdict={'size':20,'color':'red'})
        plt.pause(0.1)
    plt.show()

结果图如下:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值