寒假PyTorch工具第一天

课程记录

张量创建, 变换和运算


课程代码

1. create_tensor

import torch
import numpy as np 

a = np.ones((3, 3))
print(a, id(a))

b = torch.tensor(a)
print(b, id(b), b.device)

# b_gpu = torch.tensor(a, device = 'cuda')
b_gpu = torch.tensor(a, device = 'cpu')
print(b_gpu, id(b_gpu), b_gpu.device)

c = torch.from_numpy(a)
print(c, id(c))
a[0, 0] = 2
print(a, c)
c[0, 1] = 3
print(a, c)

d = torch.zeros((3, 3, 3))
print(d, d.dtype, d.shape)

dd = torch.zeros_like(d)
print(d, d.type, d.shape)

e = torch.full((2, 2), 233)
print(e, e.dtype)

ee = torch.full((2, 2), 233.)
print(ee, ee.dtype)

f = torch.arange(1, 5)
print(f, f.dtype)

ff = torch.arange(1., 5.1)
print(ff, ff.dtype)

g = torch.linspace(1, 6, 6)
print(g, g.dtype)

h = torch.normal(0, 1, (3, 3))
print(h, h.dtype)

hh = torch.randn((3, 3))
print(hh, hh.dtype)

i = torch.rand((2, 2))
print(i)

ii = torch.randint(1, 5, (2, 2))
print(ii)

j = torch.randperm(20)
print(j, j.dtype)

2. reshape_tensor

import torch 
import numpy as np 

a = torch.arange(0, 10, dtype = torch.int64)

b = torch.reshape(a, (2, 5))
print(b)

b_T = torch.t(b)
print(b_T, b_T.shape)

c = torch.reshape(torch.arange(0, 24, dtype = torch.int64), (2, 3, 4))
print(c)
d = torch.transpose(c, 0, 1)
print(d)

e = torch.tensor([1])
print(e, e.shape)
f = torch.squeeze(e)
print(f, f.shape)
f = f * 2
print(f, e)
ee = torch.unsqueeze(f, dim = 0)
print(ee)

3. concat_split_tensor

import torch 
import numpy as np 

t1 = torch.ones((2, 2))
t2 = torch.zeros((2, 2))

a = torch.cat([t1, t2], dim = 0)
print(a, a.shape)

b = torch.stack([t1, t2], dim = 0)
print(b, b.shape)
print(b[0], b[1])

x = torch.split(b, [1, 1], dim = 0)
print(type(x))
c, d = x
print(c, d)

e = torch.index_select(a, dim = 0, index = torch.tensor([0, 2]))
print(e)

mask = a.ge(1)
f = torch.masked_select(a, mask)
print(mask, f)

4. tensor_operator

# 通过一元线性回归, 来熟悉和展示常用的tensor的运算操作
import torch 
import numpy as np


torch.manual_seed(10)


# data
x = torch.rand((20, 1)) * 10
y = 2 * x + 5 + torch.randn(20, 1)


# model
w = torch.tensor(np.asarray([0.3]), requires_grad=True)
b = torch.tensor(np.asarray([0.]), requires_grad=True)
print(w, b)


# iteration
for _ in range(1000):
    # flow
    y_pre = w * x + b
    loss = ( 0.5 * (y_pre - y) ** 2 ).mean()


    # backwords
    loss.backward()
    w.data.sub_(0.05 * w.grad)
    b.data.sub_(0.05 * b.grad)

    w.grad.zero_()
    b.grad.zero_()


    # show
    if _ % 100 == 0:
        print(str(_) + ' loss is', loss.data.numpy())
        if loss.data.numpy() < 0.47:
            break



print('finish...')

作业

1.   安装anaconda,pycharm, CUDA+CuDNN(可选),虚拟环境,pytorch,并实现hello pytorch查看pytorch的版本

2.   张量与矩阵、向量、标量的关系是怎么样的?

3.   Variable“赋予”张量什么功能?

4.   采用torch.from_numpy创建张量,并打印查看ndarray和张量数据的地址;

5.   实现torch.normal()创建张量的四种模式。

1. 装环境

  1. conda create -n torch_p36 python=3.6.5
  2. conda activate torch_p36
  3. pip install torch==1.7.1+cu110 torchvision==0.8.2+cu110 torchaudio===0.7.2 -f https://download.pytorch.org/whl/torch_stable.html

2. 概念解释

标量(scalar)
​一个标量表示一个单独的数,它不同于线性代数中研究的其他大部分对象

向量(vector)
​一个向量表示一组有序排列的数。通过次序中的索引,我们可以确定每个单独的数

矩阵(matrix)
​矩阵是具有相同特征和纬度的对象的集合,表现为一张二维数据表。其意义是一个对象表示为矩阵中的一行,一个特征表示为矩阵中的一列,每个特征都有数值型的取值

张量(tensor)
​在某些情况下,我们会讨论坐标超过两维的数组。一般地,一个数组中的元素分布在若干维坐标的规则网格中,我们将其称之为张量

3. Variable“赋予”张量功能

Variable是torch.autograd中的数据类型,主要用于封装Tensor,使得tensor可以进行自动求导
主要有五个属性
1.data:被包装的Tensor
2.grad:data的梯度
3.grad_fn:创建Tensor的Function(创建张量所用到的方法,如加法或乘法),是自动求导的关键
4.requires.grad:指示张量是否需要梯度,不需要梯度的张量可以设置为false
5.is_leaf:指示张量在计算图中是否是叶子结点。

现在variable不需要出现在代码中了, 并入到了tensor

Tensor

dtype

shape

device

4. 创建张量

import torch
import numpy as np 

a = np.ones((3, 3))
print(a, id(a))

b = torch.tensor(a)
print(b, id(b), b.device)

# b_gpu = torch.tensor(a, device = 'cuda')
b_gpu = torch.tensor(a, device = 'cpu')
print(b_gpu, id(b_gpu), b_gpu.device)

c = torch.from_numpy(a)
print(c, id(c))
a[0, 0] = 2
print(a, c)
c[0, 1] = 3
print(a, c)

d = torch.zeros((3, 3, 3))
print(d, d.dtype, d.shape)

dd = torch.zeros_like(d)
print(d, d.type, d.shape)

e = torch.full((2, 2), 233)
print(e, e.dtype)

ee = torch.full((2, 2), 233.)
print(ee, ee.dtype)

f = torch.arange(1, 5)
print(f, f.dtype)

ff = torch.arange(1., 5.1)
print(ff, ff.dtype)

g = torch.linspace(1, 6, 6)
print(g, g.dtype)

h = torch.normal(0, 1, (3, 3))
print(h, h.dtype)

hh = torch.randn((3, 3))
print(hh, hh.dtype)

i = torch.rand((2, 2))
print(i)

ii = torch.randint(1, 5, (2, 2))
print(ii)

j = torch.randperm(20)
print(j, j.dtype)

猜你喜欢

转载自blog.csdn.net/u013625492/article/details/113884210