PyTorch CUDA安装 PyTorch入门知识和例程

34 篇文章 3 订阅
29 篇文章 2 订阅

https://www.cnblogs.com/moon3/p/12199588.html

查看CUDA版本

john@john-wang:~$ cat /usr/local/cuda/version.txt
CUDA Version 10.0.130
john@john-wang:~$ nvcc -V
nvcc: NVIDIA ® Cuda compiler driver
Copyright © 2005-2017 NVIDIA Corporation
Built on Fri_Nov__3_21:07:56_CDT_2017
Cuda compilation tools, release 9.1, V9.1.85
john@john-wang:~$ cat /usr/include/cudnn.h | grep CUDNN_MAJOR -A 2
#define CUDNN_MAJOR 7
#define CUDNN_MINOR 6
#define CUDNN_PATCHLEVEL 5
#define CUDNN_VERSION (CUDNN_MAJOR * 1000 + CUDNN_MINOR * 100 + CUDNN_PATCHLEVEL)

查看gpu利用率
显示当前gpu利用率、显存和功率等:

nvidia-smi
动态显示,其中1为刷新间隔:
watch -n 1 nvidia-smi

查看cpu利用率
gnome-system-monitor

安装pytorch

安装pytorch的时候,同样需要考虑与cuda版本对应,以下网址中(https://pytorch.org/get-started/previous-versions/)有历史版本的pytorch,选择合适的版本,并执行conda或者pip命令即可。这里选择的是v1.1.0。
https://pytorch.org/get-started/previous-versions/

conda install pytorch1.2.0 torchvision0.4.0 cudatoolkit=10.0 -c pytorch

pip3 install torch1.2.0 torchvision0.4.0
在这里插入图片描述
检查是否安装成功
import torch
print(torch.version)
print(torch.cuda.is_available())

import torch
a = torch.FloatTensor(2,3)
print(a)
tensor([[1.3563e-19, 1.3563e-19, 1.3563e-19],
[2.4754e-12, 2.4756e-12, 7.8447e+17]])

b = torch.FloatTensor([2,3,4,5])
print(b)
tensor([2., 3., 4., 5.])

a = torch.rand(2,3)
print(a)
tensor([[0.3186, 0.3507, 0.7246],
[0.6894, 0.0755, 0.6183]])

a = torch.randn(2,3)
print(a)
tensor([[-0.5512, -1.3734, 0.2870],
[ 1.2101, 1.0504, 0.1602]])

a = torch.range(2,8,1)
main:1: UserWarning: torch.range is deprecated in favor of torch.arange and will be removed in 0.5. Note that arange generates values in [start; end), not [start; end].

print(a)
tensor([2., 3., 4., 5., 6., 7., 8.])

a = torch.arange(2,8,1)
print(a)
tensor([2, 3, 4, 5, 6, 7])
元素相乘
torch.mul(a,b)
矩阵相乘
b = torch.mm(a,b)

torch.mv
   将参数传递到torch.mv后返回输入参数的求积结果作为输出,torch.mv运用矩阵与向量之间的乘法规则进行计算,被传入的参数中的第1个参数代表矩阵,第2个参数代表向量,顺序不能颠倒。
c = torch.mv(a,b)

tensor的t()属性实现转置

import torch
x = torch.Tensor([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
x
1 2 3 4 5
6 7 8 9 10
[torch.FloatTensor of size 2x5]

x.t()
1 6
2 7
3 8
4 9
5 10
[torch.FloatTensor of size 5x2]

PyTorch示例1

深度学习之PyTorch实战(1)——基础学习及搭建环境
https://www.cnblogs.com/wj-1314/p/9830950.html

# coding:utf-8
import torch
 
batch_n = 100
hidden_layer = 100
input_data = 1000
output_data = 10
 
x = torch.randn(batch_n, input_data)
y = torch.randn(batch_n, output_data)
 
w1 = torch.randn(input_data, hidden_layer)
w2 = torch.randn(hidden_layer, output_data)
 
epoch_n = 20
learning_rate = 1e-6
 
for epoch in range(epoch_n):
    h1 = x.mm(w1)  # 100*1000
    h1 = h1.clamp(min=0)
    y_pred = h1.mm(w2)  # 100*10
    # print(y_pred)
 
    loss = (y_pred - y).pow(2).sum()
    print("Epoch:{} , Loss:{:.4f}".format(epoch, loss))
 
    gray_y_pred = 2 * (y_pred - y)
    gray_w2 = h1.t().mm(gray_y_pred)
 
    grad_h = gray_y_pred.clone()
    grad_h = grad_h.mm(w2.t())
    grad_h.clamp_(min=0)
    grad_w1 = x.t().mm(grad_h)
 
    w1 -= learning_rate * grad_w1
    w2 -= learning_rate * gray_w2

在这里插入图片描述
PyTorch示例2

# coding:utf-8
import torch
from torch.autograd import Variable

batch_n = 100
hidden_layer = 100
input_data = 1000
output_data = 10
 
x = Variable(torch.randn(batch_n , input_data) , requires_grad = False)
y = Variable(torch.randn(batch_n , output_data) , requires_grad = False)
 
w1 = Variable(torch.randn(input_data,hidden_layer),requires_grad = True)
w2 = Variable(torch.randn(hidden_layer,output_data),requires_grad = True)

# x = torch.randn(batch_n, input_data)
# y = torch.randn(batch_n, output_data)
 
# w1 = torch.randn(input_data, hidden_layer)
# w2 = torch.randn(hidden_layer, output_data)
 
epoch_n = 20
learning_rate = 1e-6

for epoch in range(epoch_n):
 
    y_pred = x.mm(w1).clamp(min= 0 ).mm(w2)
    loss = (y_pred - y).pow(2).sum()
    print("Epoch:{} , Loss:{:.4f}".format(epoch, loss.data))
 
    loss.backward()
    w1.data -= learning_rate * w1.grad.data
    w2.data -= learning_rate * w2.grad.data
 
    w1.grad.data.zero_()
    w2.grad.data.zero_() 

在这里插入图片描述
PyTorch示例3

# coding:utf-8
import torch
from torch.autograd import Variable

batch_n = 100
hidden_layer = 100
input_data = 1000
output_data = 10
 
x = Variable(torch.randn(batch_n , input_data) , requires_grad = False)
y = Variable(torch.randn(batch_n , output_data) , requires_grad = False)
 
w1 = Variable(torch.randn(input_data,hidden_layer),requires_grad = True)
w2 = Variable(torch.randn(hidden_layer,output_data),requires_grad = True)

# x = torch.randn(batch_n, input_data)
# y = torch.randn(batch_n, output_data)
 
# w1 = torch.randn(input_data, hidden_layer)
# w2 = torch.randn(hidden_layer, output_data)
 
epoch_n = 20
learning_rate = 1e-6

class Model(torch.nn.Module):
    def __init__(self):
        super(Model,self).__init__()
     
    def forward(self,input,w1,w2):
        x = torch.mm(input,w1)
        x = torch.clamp(x,min=0)
        x = torch.mm(x,w2)
        return x
     
    def backward(self):
        pass

model = Model()

for epoch in range(epoch_n):
 
    # y_pred = x.mm(w1).clamp(min= 0 ).mm(w2)
    y_pred = model(x, w1, w2)
    loss = (y_pred - y).pow(2).sum()
    print("Epoch:{} , Loss:{:.4f}".format(epoch, loss.data))
 
    loss.backward()
    w1.data -= learning_rate * w1.grad.data
    w2.data -= learning_rate * w2.grad.data
 
    w1.grad.data.zero_()
    w2.grad.data.zero_() 

在这里插入图片描述

In [15]: x = torch.randn(3, requires_grad=True)

In [16]: y = x * 2

In [17]: y.data
Out[17]: tensor([-1.2510, -0.6302, 1.2898])

In [18]: y.data.norm()
Out[18]: tensor(1.9041)

#computing the norm using elementary operations
In [19]: torch.sqrt(torch.sum(torch.pow(y, 2)))
Out[19]: tensor(1.9041)

对于图像,可以用 Pillow,OpenCV
对于语音,可以用 scipy,librosa
对于文本,可以直接用 Python 或 Cython 基础数据加载模块,或者用 NLTK 和 SpaCy

https://www.jianshu.com/p/45a26d278473

class CNN(nn.Module):
    def __init__(self):
        nn.Model.__init__(self)
 
        self.conv1 = nn.Conv2d(1, 6, 5)  # 输入通道数为1,输出通道数为6
        self.conv2 = nn.Conv2d(6, 16, 5)  # 输入通道数为6,输出通道数为16
        self.fc1 = nn.Linear(5 * 5 * 16, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 10)

    def forward(self,x):
        # 输入x -> conv1 -> relu -> 2x2窗口的最大池化
        x = self.conv1(x)
        x = F.relu(x)
        x = F.max_pool2d(x, 2)
        # 输入x -> conv2 -> relu -> 2x2窗口的最大池化
        x = self.conv2(x)
        x = F.relu(x)
        x = F.max_pool2d(x, 2)
        # view函数将张量x变形成一维向量形式,总特征数不变,为全连接层做准备
        x = x.view(x.size()[0], -1)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x

网络整体结构:[conv + relu + pooling] * 2 + FC * 3
原始输入样本的大小:32 x 32 x 1

第一次卷积:使用6个大小为5 x 5的卷积核,故卷积核的规模为(5 x 5) x 6;卷积操作的stride参数默认值为1 x 1,32 - 5 + 1 = 28,并且使用ReLU对第一次卷积后的结果进行非线性处理,输出大小为28 x 28 x 6;
第一次卷积后池化:kernel_size为2 x 2,输出大小变为14 x 14 x 6;
第二次卷积:使用16个卷积核,故卷积核的规模为(5 x 5 x 6) x 16;使用ReLU对第二次卷积后的结果进行非线性处理,14 - 5 + 1 = 10,故输出大小为10 x 10 x 16;
第二次卷积后池化:kernel_size同样为2 x 2,输出大小变为5 x 5 x 16;
第一次全连接:将上一步得到的结果铺平成一维向量形式,5 x 5 x 16 = 400,即输入大小为400 x 1,W大小为120 x 400,输出大小为120 x 1;
第二次全连接,W大小为84 x 120,输入大小为120 x 1,输出大小为84 x 1;
第三次全连接:W大小为10 x 84,输入大小为84 x 1,输出大小为10 x 1,即分别预测为10类的概率值。

作者:一只椰子啊嘻嘻嘻
链接:https://www.jianshu.com/p/45a26d278473
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
在这里插入图片描述

如何理解 transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])

https://blog.csdn.net/KaelCui/article/details/106175313
GRIT_Kael 2020-05-17 16:04:00 788 收藏 2
分类专栏: 笔记 问题解决 文章标签: 深度学习机器学习python
版权
前面的(0.5,0.5,0.5) 是 R G B 三个通道上的均值, 后面(0.5, 0.5, 0.5)是三个通道的标准差,
Normalize对每个通道执行以下操作:image =(图像-平均值)/ std在您的情况下,参数mean,std分别以0.5和0.5的形式传递。这将使图像在[-1,1]范围内归一化。例如,最小值0将转换为(0-0.5)/0.5=-1,最大值1将转换为…

注意通道顺序是 R G B ,用过opencv的同学应该知道openCV读出来的图像是 BRG顺序。这两个tuple数据是用来对RGB 图像做归一化的,如其名称 Normalize 所示这里都取0.5只是一个近似的操作,实际上其均值和方差并不是这么多,但是就这个示例而言 影响可不计。

精确值是通过分别计算R,G,B三个通道的数据算出来的,
比如你有2张图片,都是100100大小的,那么两图片的像素点共有2100*100 = 20 000 个; 那么这两张图片的

  1. mean求法:
    mean_R: 这20000个像素点的R值加起来,除以像素点的总数,这里是20000;mean_G 和mean_B 两个通道 的计算方法 一样的。

  2. 标准差求法:
    首先标准差就是开了方的方差,所以其实就是求方差,方差公式就是我们数学上的那个求方差的公式:

也是3个通道分开算,
比如算R通道的, 这里X就为20000个像素点 各自的R值,再减去R均值,上面已经算好了;
然后平方;
然后20000个像素点相加,然后求平均除以20000,
得到R的方差,再开方得标准差。
注意!!!
如果你用的是自己创建的数据集,从头训练,那最好还是要自己统计自己数据集的这两个量

你加载的的是pytorch上的预训练模型,自己只是微调模型;
或者你用了常见的数据集比如VOC或者COCO之类的,但是用的是自己的网络结构,即pytorch上没有可选的预训练模型那么可以使用一个pytorch上给的通用的统计值:
mean=[0.485, 0.456, 0.406],std=[0.229, 0.224, 0.225]),即
transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))])

class Net(nn.Module):
def init(self):
super(Net, self).init()
类Net先找到父类nn.Module,然后将类Net的对象self转换成父类nn.Module的对象,被转换的类nn.Module对象调用自己的方法 init()

子类继承了父类的所有属性和方法,父类属性自然会用父类方法来进行初始化。

当然,如果初始化的逻辑与父类的不同,不使用父类的方法,自己重新初始化也是可以的。比如:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
 
class Person(object):
    def __init__(self,name,gender,age):
        self.name = name
        self.gender = gender
        self.age = age
 
class Student(Person):
    def __init__(self,name,gender,age,school,score):
        #super(Student,self).__init__(name,gender,age)
        self.name = name.upper()  
        self.gender = gender.upper()
        self.school = school
        self.score = score
 
s = Student('Alice','female',18,'Middle school',87)
print s.school
print s.name

上面例子,父类对name和gender的初始化只是简单的赋值,但子类要求字母全部大写。

来源:https://blog.csdn.net/wltsysterm/article/details/104440387

pytorch中,.item()方法 是得到一个元素张量里面的元素值
具体就是 用于将一个零维张量转换成浮点数,比如计算loss,accuracy的值
就比如:
loss = (y_pred - y).pow(2).sum()
print(loss.item())

pytorch criterion踩坑小结
https://blog.csdn.net/sjtuxx_lee/article/details/83112144

*args表示任何多个无名参数,它是一个tuple

**kwargs表示关键字参数,它是一个dict

测试代专码如下:
def foo(args,**kwargs):
print ‘args=’,args
print ‘kwargs=’,kwargs
print '
*********************’
if name==‘main’:
foo(1,2,3)
foo(a=1,b=2,c=3)
foo(1,2,3,a=1,b=2,c=3)
foo(1,‘b’,‘c’,a=1,b=‘b’,c=‘c’)

执行结果如下:
args= (1, 2, 3)
kwargs= {}


args= ()
kwargs= {‘a’: 1, ‘c’: 3, ‘b’: 2}


args= (1, 2, 3)
kwargs= {‘a’: 1, ‘c’: 3, ‘b’: 2}


args= (1, ‘b’, ‘c’)
kwargs= {‘a’: 1, ‘c’: ‘c’}

torch.max()使用讲解
在分类问题中,通常需要使用max()函数对softmax函数的输出值进行操作,求出预测值索引。下面讲解一下torch.max()函数的输入及输出值都是什么。

torch.max(input, dim) 函数
output = torch.max(input, dim)

输入input是softmax函数输出的一个tensor
dim是max函数索引的维度0/1,0是每列的最大值,1是每行的最大值

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值