pytorcn-python中的基础

#create tensors of shape(10,3) and (10,2)

x= torch.randn(10,3)

y=torch.randn(10,2)

 

#loading data from numpy

x=np.array([[1,2],[3,4]])

   #convert the numpy arrary to a torch tensor

y = torch.from_numpy(x)

  #convert the torch tensor to a numpy array

z=y.numpy()

 

#OPTIM: torch.optim.lr_scheduler.StepLR(optimizer,step_size,gamma=0.1,last_epoch=-1)

sets the learning rate of each parameter group to the initial lr decayed by gamma every step_size epochs.

Parameters:
  • optimizer (Optimizer) – Wrapped optimizer.
  • step_size (int) – Period of learning rate decay.
  • gamma (float) – Multiplicative factor of learning rate decay. Default: 0.1.
  • last_epoch (int) – The index of last epoch. Default: -1.

 

Example

>>> # Assuming optimizer uses lr = 0.05 for all groups
>>> # lr = 0.05     if epoch < 30
>>> # lr = 0.005    if 30 <= epoch < 60
>>> # lr = 0.0005   if 60 <= epoch < 90
>>> # ...
>>> scheduler = StepLR(optimizer, step_size=30, gamma=0.1)
>>> for epoch in range(100):
>>>     scheduler.step()
>>>     train(...)
>>>     validate(...)

#python-Enumerate()

enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。

语法

以下是 enumerate() 方法的语法:

enumerate(sequence, [start=0])

参数

  • sequence -- 一个序列、迭代器或其他支持迭代对象。
  • start -- 下标起始位置。

返回值

返回 enumerate(枚举) 对象。

实例

以下展示了使用 enumerate() 方法的实例:

>>>seasons = ['Spring', 'Summer', 'Fall', 'Winter']

>>> list(enumerate(seasons))

[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]

>>> list(enumerate(seasons, start=1)) # 下标从 1 开始

[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

普通的 for 循环

>>>i = 0

>>> seq = ['one', 'two', 'three']

>>> for element in seq:

...        print i, seq[i]

...        i +=1

...

0 one

1 two

2 three

for 循环使用 enumerate

>>>seq = ['one', 'two', 'three']

>>> for i, element in enumerate(seq):

...         print i, element

...

0 one

1 two

2 three

 

#pytoch中 torch.nn.DataParallel (DataParallel layers: multi-GPU)

This container parallelizes the application of the given module by splitting the input across the specified devices by chunking in the batch dimension. In the forward pass, the module is replicated on each device, and each replica handles a portion of the input. During the backwards pass, gradients from each replica are summed into the original module.

 

#对于torch.nn和torch.nn.functional的区别

torch.nn.Conv2d
import torch.nn.functional as F
class Conv2d(_ConvNd):

    def __init__(self, in_channels, out_channels, kernel_size, stride=1,
                 padding=0, dilation=1, groups=1, bias=True):
        kernel_size = _pair(kernel_size)
        stride = _pair(stride)
        padding = _pair(padding)
        dilation = _pair(dilation)
        super(Conv2d, self).__init__(in_channels, out_channels, kernel_size, stride, padding, dilation,False, _pair(0), groups, bias)

    def forward(self, input):
        return F.conv2d(input, self.weight, self.bias, self.stride,
                        self.padding, self.dilation, self.groups)
 

torch.nn.functional.conv2d
def conv2d(input, weight, bias=None, stride=1, padding=0, dilation=1,
           groups=1):

    if input is not None and input.dim() != 4:
        raise ValueError("Expected 4D tensor as input, got {}D tensor instead.".format(input.dim()))

    f = _ConvNd(_pair(stride), _pair(padding), _pair(dilation), False,
                _pair(0), groups, torch.backends.cudnn.benchmark,
                torch.backends.cudnn.deterministic, torch.backends.cudnn.enabled)
    return f(input, weight, bias)
所以在定义网络时,如果内层有Variable,那么用nn定义,反之,则用nn.functional定义

 

# class torch.nn.Module

Base class for all neural network modules. Your models should also subclass this class.

# python 中 super() 函数

super()函数是调用父类(超类)的一个方法。super是用来解决多重继承问题的,直接用类名调用父类方法在使用单继承的时候没问题,但是如果使用多继承,会涉及到查找顺序(MRO)、重复调用(钻石继承)等种种问题。

#top K 准确率

top1-----就是你预测的label取最后概率向量里面最大的那一个作为预测结果,如过你的预测结果中概率最大的那个分类正确,则预测正确。否则预测错误

top5-----就是最后概率向量最大的前五名中只要出现了正确概率即为预测正确。否则预测错误。

 

#python-argparse

argparse是python内置的一个用于命令项选项与参数解析的模块,通过程序中定义好我们需要的参数,argparse将会从sys.argv中解析出这些参数,并自动生成帮助和使用信息。

 argparse的使用:

1)创建ArgumentParser()对象

2)调用add_argument()方法添加参数

3)使用parse_args()解析添加的参数

# 定位参数:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("square",help="display a square of a given number", type=int)
args = parser.parse_args()
print(args.square**2)

使用:

$ python argparse_usage.py 9
81
 

# 可选参数:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("--square", help="display a square of a given number", type=int)
parser.add_argument("--cubic", help="display a cubic of a given number", type=int)

args=parser.parse_args()

if args.square:
    print(args.square**2)
if args.cubic:
    print(args.cubic**3)

使用:

$ python argparse_usage.py --h

usage: argparse_usage.py [-h] [--square SQUARE] [--cubic CUBIC]

optional arguments:

-h, --help show this help message and exit

--square SQUARE display a square of a given number

--cubic CUBIC display a cubic of a given number

 

$ python argparse_usage.py --square 8

64

 

$ python argparse_usage.py --cubic 8

512

#混合使用

import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument("integers", metavar='N',type=int,nargs='+',help="an integer for the accumulator")
parser.add_argument("--sum",dest='accumulate',action='store_const',const=sum, default=max,
                        help="sum the integers (default: find the max)")

args=parser.parse_args()
print(args.accumulate(args.integers))

使用:

F:\Code\test>python test1.py -h
usage: test1.py [-h] [--sum] N [N ...]

Process some integers.

positional arguments:
  N           an integer for the accumulator

optional arguments:
  -h, --help  show this help message and exit
  --sum       sum the integers (default: find the max)

F:\Code\test>python test1.py 1 2 3 4
4

F:\Code\test>python test1.py 1 2 3 4 --sum
10

#python中的shape, size, len,count

len(): 返回对象的长度。

  len([1,2,3]),返回值为3

  len([[1,2,3],[3,4,5]]),返回值2

count(): 计算包含对象个数

  [1,1,1,2].count(1),返回值为3

  ‘asddf’.count('d'),返回值为2

size()和shape()是numpy模块中才有的函数:

 size():计算数值和矩阵所有数据的个数

  a=np.arrary([[1,2,3],[4,5,6]])

  np.size(a),返回值为6

  np.size(a,1),返回值为3

shape(): 得到矩阵每维的大小

  np.shape(a),返回值(2,3)

 

#numpy.ndarray.astype:

ndarray.astype(dtype, order='K', casting='unsafe',subok=True, copy=True)

    copy of the array, cast to a specified type

#yaml

YAML是专门用来写配置文件的语言。

#easydict

easydict的作用:可以使得以属性的方式去访问字典的值

>>> from easydict import EasyDict as edict
>>> d = edict({'foo':3, 'bar':{'x':1, 'y':2}})
>>> d.foo
3
>>> d.bar.x
1
 
>>> d = edict(foo=3)
>>> d.foo
3
#保存和加载模型

   #保存和加载整个模型

    torch.save(model_object, 'model.pkl')

    model = torch.load('model.pkl')

   #仅保存和加载模型参数

     torch.save(model_object.state_dict(), 'params.pkl')

     model_object.load_state_dict(torch.load('params.pkl'))

 

#torch.Tensor.view(*shape) ---> Tensor

Parameters: shape(torch.Size or int..) -- the desired size

Returns a new tensor with the same data as the self tensor but of a different shape. The returned tensor shares the same data and must have the same number of elements, but may have a different size.

>>> x=torch.randn(4,4)
>>> x.size()
torch.Size([4, 4])
>>> y=x.view(16)
>>> y.size()
torch.Size([16])
>>> z=x.view(-1,8)  ##尺寸[-1,8]和原数据大小不一致,修改-1为2可以满足
>>> z.size()
torch.Size([2, 8])

 

#permute以及contiguous

In [86]: test = torch.arange(0,6)

In [87]: test
Out[87]: tensor([0, 1, 2, 3, 4, 5])

In [88]: test=test.view(2,3)

In [89]: test
Out[89]:
tensor([[0, 1, 2],
        [3, 4, 5]])

In [90]: perm=test.permute(1,0)
tensor([[0, 3],
        [1, 4],
        [2, 5]])

In [92]: perm.view(2,3)
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-92-d359b0bdcdb9> in <module>()
----> 1 perm.view(2,3)

In [93]: print(perm.contiguous().view(2,3))
tensor([[0, 3, 1],
        [4, 2, 5]])

#cupy

CuPy 是實做 numpy 界面的子集、背後是利用 GPU 運算 。

cupy.ndarray 類是其核心,它是 numpy.ndarray 的兼容GPU替代方案

cupy.asarray 能將 numpy.array 、 list 及 物件傳送到 device。

cupy.asnumpy 將 GPU 上的資料,傳回 CPU 。

#isinstance

用isinstacne方法检查一个对象是否是一个类的实例

#torch.Tensor.data_ptr()

data_ptr() --->int : returns the address of the first element of self tensor

#torch.numel(input)--->int

returns the total number of elements in the input tensor

#glob.glob

函数功能:匹配所有的符合条件的文件,并将其以List的形式返回

#torch.nn.Sequential(*args)

a sequential container. Modules will be added to it in the order they are passed in the constructor. Alternatively, an ordered dict of modules can also be passed in.

   #example

model = nn.Sequential(nn.Conv2d(1,20,5), nn.ReLU(), nn.Conv2d(20,64,5), nn.ReLU)

model = nn.Sequential(OrderedDict([('conv1', nn.Conv2d(1,20,5)),

                                                           ('relu1', nn.ReLU()),

                                                           ('conv2', nn.Conv2d(20,64,5)),

                                                           ('relu2', nn.ReLU())

                                                       ]))

#python eval()

eval(expression, globals=None, locals=None) : 将字符串str当成有效当表达式来求值并返回计算结果。

#os

 #os.path.abspath("__file__") # 获取当前文件的绝对路径

 

 #os.path.splitext 分离文件名和扩展名;

import os
path_01='D:/User/wgy/workplace/data/notMNIST_large.tar.gar'
path_02='D:/User/wgy/workplace/data/notMNIST_large'
root_01=os.path.splitext(path_01)
root_02=os.path.splitext(path_02)
print(root_01)
print(root_02)
 

结果:
('D:/User/wgy/workplace/data/notMNIST_large.tar', '.gar')
('D:/User/wgy/workplace/data/notMNIST_large', '')
 

 #os.path.basename返回最后的文件名

path='D:\CSDN'

os.path.basename(path)=CSDN

 

#交叉熵的原理(转载于https://blog.csdn.net/zwqjoy/article/details/78952087

交叉熵刻画的是实际输出(概率)与期望输出(概率)的距离,也就是交叉熵的值越小,两个概率分布就越接近。假设概率分布p为期望输出,概率分布q为实际输出,H(p,q)为交叉熵,则:

假设N=3,期望输出为p=(1,0,0),实际输出q1=(0.5,0.2,0.3),q2=(0.8,0.1,0.1),那么:

在pytorch中的 torch.nn.functional.cross_entropy(input,target)已经结合了log_softmax 和nll_loss 函数,所以输入的input是卷积神经网络最后一层的原始输出(而不是经过softmax回归处理后的值)。

 Softmax回归处理:

卷积神经网络的原始输出不是一个概率值,实质是输入数值做了复杂加权和非线性处理之后的一个值,而通过softmax处理后,输出就变为概率分布了。softmax回归处理后的输出为:

单个结点的输出变成一个概率值,经过softmax处理后结果作为神经网络最后的输出。 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值