深度学习第一周

F Week

 一:安装好环境:pytorch(由Facebook研发开源的深度学习框架,支持CPU,GPU加速计算)

二,基础语法:

        torch.tensor:是包含单一数据类型元素的多维数组,它是PyTorch中数据存储和运算的基本单元,类似于Numpy.ndarray。两者的函数接口和运算方式几乎一样,实际上PyTorch内部也是把ndarray包装成Tensor

        Tensors中文名为:张量,多维数组,是PyTorch中最基本的数据类型。在数学中,标量是一个只有大小无方向的量如1,2,3等,向量是既有大小也有方向的量(一维数组),如A(x1,x2,x3).矩阵是由多个向量组成的二维数组,实际上标量向量都可以看作做事张量的特例,标量事零维张量,向量是一维张量,矩阵是二维张量。

 numpy与tensor之间的转化:(代码如下)

 运行结果为:

 tensor的创建(五种):   

        第一种:初始化创建:

                

                运行结果:

                

        第二种:未初始化创建:

                

                运行结果:

                 

        第三种:随机生成

                

                运行结果:

                 

        第四种:序列生成

                

                运行结果:

                 

                 第五种:全零,全一,单位矩阵创建

                

                运行结果:

                 

tensorf的属性:

import torch
import numpy as np
print("tensor的属性:")
a = torch.tensor([[1,2,3],[3,4,5]],dtype=torch.float)
print(a.dtype)
print(a.shape)          #tensor的
print(a.size())         #tensor的大小
print(a.size(0))        #tensor第一维的大小
print(a.size(1))        #tensor第二维的大小
print(a.dim())          #tensor 维度的大小
print(a.grad)           #tensor 梯度的大小
print(a.device)         #tensor所在设备

运行结果: 

tensor的变形 

import torch
import numpy as np
a = torch.tensor([[1,2,3],[3,4,5]],dtype=torch.float)
print("a值:",a)
print("a的形状",a.shape)
b = a.flatten()             #flattenn  :拉直
print("b值:",b)
print("b的形状",b.shape)
c = b.reshape(2,3)          #reshape   :改变成自己想的形状
print("c值:",c)
print("c的形状:",c)
d = c.view(1,6)
print("d值:",d)
print("d的形状:",d.shape)
# 在深度学习中,使用Python进行数据预处理和模型构建时,常常需要调整张量(tensor)的形状。view和reshape是两种常用的方法,它们都可以用来改变张量的形状,但它们之间存在一些关键差异。
# view函数:
# view函数要求输入的张量是连续的(contiguous),即逻辑上相邻的元素在内存中也是连续存储的。如果张量不是连续的,view函数会报错,除非在使用view之前使用contiguous()方法将其转换为连续张量123478.
# view函数不会分配新的内存空间,它仅仅是改变了张量的元数据(shape和stride),返回一个指向相同数据的新视图(view)。这意味着修改view后的张量会影响原始张量,因为它们共享相同的存储空间123478.
# reshape函数
# reshape函数比view函数更加灵活,它可以处理非连续的张量,并且在新形状满足一定条件时会共享相同的数据,否则会复制一份新的数据到新的内存空间.
# reshape函数在返回新的张量时,如果新的形状与原张量的元素总数相匹配,并且可以通过调整步幅(stride)来访问,则它会像view一样工作,不分配新的内存。如果新的形状不能通过调整步幅来访问,reshape会分配新的内存空间,并将数据从原张量复制到新张量中
e = torch.squeeze(d)  # 将输入张量形状中的一去除
print('e:', e)
print("e.shape:", e.shape)

f = torch.unsqueeze(e, 0)  # 对输出的既定位置插入 维度一
print('f:', f)
print("f.shape:", f.shape)

f = torch.unsqueeze(e, 1)  # 对输出的既定位置插入维度一
print('f:', f)
print("f.shape:", f.shape)

 运行结果

C:\Users\Ywind\anaconda3\envs\pytorch\python.exe D:\pytorch\pytorch_study\tensro的变形.py 
a值: tensor([[1., 2., 3.],
        [3., 4., 5.]])
a的形状 torch.Size([2, 3])
b值: tensor([1., 2., 3., 3., 4., 5.])
b的形状 torch.Size([6])
c值: tensor([[1., 2., 3.],
        [3., 4., 5.]])
c的形状: tensor([[1., 2., 3.],
        [3., 4., 5.]])
d值: tensor([[1., 2., 3., 3., 4., 5.]])
d的形状: torch.Size([1, 6])
e: tensor([1., 2., 3., 3., 4., 5.])
e.shape: torch.Size([6])
f: tensor([[1., 2., 3., 3., 4., 5.]])
f.shape: torch.Size([1, 6])
f: tensor([[[1., 2., 3., 3., 4., 5.]]])
f.shape: torch.Size([1, 1, 6])

进程已结束,退出代码为 0

tensor的索引和切片 :

import torch
import numpy as np
a = torch.tensor([[1,2,3],[4,5,6],[7,8,9]],dtype=float)
b = torch.tensor([[5,5,5],[5,5,5],[5,5,5]],dtype=float)
print("a的值:",a)
#索引
print("a[1,2]的值:",a[1,2])
print("a[-1,-1]的值:",a[-1,-1])
print("a的第一行,第一列和第三列的值",a[0,[0,2]])
print("a大于四的索引:",a>4)               #bool
print("a大于四的值:",a[a>4])
print("如果a的元素大于5输出a,否则输出b",torch.where(a>5,a,b))
#切片
print("a的值:",a)
print("a的第一列",a[:,0])
print("a的第三列",a[:,2])
print("a的第三列",a[:,-1])
print("a的二到三列",a[:,1:3])
print("a的第一行",a[0,:])
print("a的第二行",a[1,:])
print("a的第二行",a[-2,:])
print("a的间隔行值",a[::2,::2])


运行结果:

C:\Users\Ywind\anaconda3\envs\pytorch\python.exe D:\pytorch\pytorch_study\tensor的索引与切片.py 
a的值: tensor([[1., 2., 3.],
        [4., 5., 6.],
        [7., 8., 9.]], dtype=torch.float64)
a[1,2]的值: tensor(6., dtype=torch.float64)
a[-1,-1]的值: tensor(9., dtype=torch.float64)
a的第一行,第一列和第三列的值 tensor([1., 3.], dtype=torch.float64)
a大于四的索引: tensor([[False, False, False],
        [False,  True,  True],
        [ True,  True,  True]])
a大于四的值: tensor([5., 6., 7., 8., 9.], dtype=torch.float64)
如果a的元素大于5输出a,否则输出b tensor([[5., 5., 5.],
        [5., 5., 6.],
        [7., 8., 9.]], dtype=torch.float64)
a的值: tensor([[1., 2., 3.],
        [4., 5., 6.],
        [7., 8., 9.]], dtype=torch.float64)
a的第一列 tensor([1., 4., 7.], dtype=torch.float64)
a的第三列 tensor([3., 6., 9.], dtype=torch.float64)
a的第三列 tensor([3., 6., 9.], dtype=torch.float64)
a的二到三列 tensor([[2., 3.],
        [5., 6.],
        [8., 9.]], dtype=torch.float64)
a的第一行 tensor([1., 2., 3.], dtype=torch.float64)
a的第二行 tensor([4., 5., 6.], dtype=torch.float64)
a的第二行 tensor([4., 5., 6.], dtype=torch.float64)
a的间隔行值 tensor([[1., 3.],
        [7., 9.]], dtype=torch.float64)

进程已结束,退出代码为 0

 tensor的拆分和链接

import torch
import numpy as np
a = torch.tensor([[1,2,3],[4,5,6],[7,8,9]],dtype=float)
b = torch.tensor([[5,5,5],[5,5,5],[5,5,5]],dtype=float)
print("a的值:",a)
print("b的值:",b)
print("a,b按行进行拼接",torch.cat((a,b),dim=0))    #给定维度上对输入的张量进行链接操作
print("a,b按行进行拼接",torch.cat((a,b),dim=0).shape)
print("a,b按列进行拼接",torch.cat((a,b),dim=1))    #给定维度上对输入的张量进行链接操作
print("a,b按列进行拼接",torch.cat((a,b),dim=1).shape)

print("a,b按行进行拼接",torch.stack((a,b),dim=0))    #沿着一个新的维度对输入张量进行链接,在新的维度拼接张量 将原始数据维度扩展一维
print("a,b按行进行拼接",torch.stack((a,b),dim=0).shape)
print("a,b按列进行拼接",torch.stack((a,b),dim=1))    #沿着一个新的维度对输入张量进行链接,在新的维度拼接张量 将原始数据维度扩展一维
print("a,b按列进行拼接",torch.stack((a,b),dim=1).shape)

print(a)
print(torch.split(a,[1,2],dim=0))#按块大小拆分张量   除不尽的取余数  返回一个元组tutle
print(torch.split(a,1,dim=0))
print(torch.split(a,1,dim=1))
print("按块进行拆分张量")
print(torch.chunk(a,2,dim=0)) #按块进行拆分张量
print(torch.chunk(a,2,dim=1))

 在拆分中split相对与chunk会更加精确,可以自己指定要切成的块的大小,chunk则是平均大小,除不尽取余数

运行结果

C:\Users\Ywind\anaconda3\envs\pytorch\python.exe D:\pytorch\pytorch_study\tensor的链接和拆分.py 
a的值: tensor([[1., 2., 3.],
        [4., 5., 6.],
        [7., 8., 9.]], dtype=torch.float64)
b的值: tensor([[5., 5., 5.],
        [5., 5., 5.],
        [5., 5., 5.]], dtype=torch.float64)
a,b按行进行拼接 tensor([[1., 2., 3.],
        [4., 5., 6.],
        [7., 8., 9.],
        [5., 5., 5.],
        [5., 5., 5.],
        [5., 5., 5.]], dtype=torch.float64)
a,b按行进行拼接 torch.Size([6, 3])
a,b按列进行拼接 tensor([[1., 2., 3., 5., 5., 5.],
        [4., 5., 6., 5., 5., 5.],
        [7., 8., 9., 5., 5., 5.]], dtype=torch.float64)
a,b按列进行拼接 torch.Size([3, 6])
a,b按行进行拼接 tensor([[[1., 2., 3.],
         [4., 5., 6.],
         [7., 8., 9.]],

        [[5., 5., 5.],
         [5., 5., 5.],
         [5., 5., 5.]]], dtype=torch.float64)
a,b按行进行拼接 torch.Size([2, 3, 3])
a,b按列进行拼接 tensor([[[1., 2., 3.],
         [5., 5., 5.]],

        [[4., 5., 6.],
         [5., 5., 5.]],

        [[7., 8., 9.],
         [5., 5., 5.]]], dtype=torch.float64)
a,b按列进行拼接 torch.Size([3, 2, 3])
tensor([[1., 2., 3.],
        [4., 5., 6.],
        [7., 8., 9.]], dtype=torch.float64)
(tensor([[1., 2., 3.]], dtype=torch.float64), tensor([[4., 5., 6.],
        [7., 8., 9.]], dtype=torch.float64))
(tensor([[1., 2., 3.]], dtype=torch.float64), tensor([[4., 5., 6.]], dtype=torch.float64), tensor([[7., 8., 9.]], dtype=torch.float64))
(tensor([[1.],
        [4.],
        [7.]], dtype=torch.float64), tensor([[2.],
        [5.],
        [8.]], dtype=torch.float64), tensor([[3.],
        [6.],
        [9.]], dtype=torch.float64))
按块进行拆分张量
(tensor([[1., 2., 3.],
        [4., 5., 6.]], dtype=torch.float64), tensor([[7., 8., 9.]], dtype=torch.float64))
(tensor([[1., 2.],
        [4., 5.],
        [7., 8.]], dtype=torch.float64), tensor([[3.],
        [6.],
        [9.]], dtype=torch.float64))

进程已结束,退出代码为 0

 tensor的置换或换位:

import torch
import numpy as np
a = torch.tensor([[1,2,3],[4,5,6],[7,8,9]],dtype=float)
print(a)
print(a.T)                  #只接受二维,将一维和二维进行置换
print(torch.t(a))           #只接受二维,将一维和二维进行置换
print(torch.transpose(a,1,0))   #只接受二维,将一维和二维进行置换

print("a.permute(1,0)   将张量a的一维和二维进行置换")
print(a.permute(1,0))           #接受多维


print("创建一个三维的张量:c")
c = torch.unsqueeze(a,0)
print(c)
print(c.shape)
print(c.permute(1,2,0).shape)

 运行结果:

C:\Users\Ywind\anaconda3\envs\pytorch\python.exe D:\pytorch\pytorch_study\tensor的换位或置换.py 
tensor([[1., 2., 3.],
        [4., 5., 6.],
        [7., 8., 9.]], dtype=torch.float64)
tensor([[1., 4., 7.],
        [2., 5., 8.],
        [3., 6., 9.]], dtype=torch.float64)
tensor([[1., 4., 7.],
        [2., 5., 8.],
        [3., 6., 9.]], dtype=torch.float64)
tensor([[1., 4., 7.],
        [2., 5., 8.],
        [3., 6., 9.]], dtype=torch.float64)
a.permute(1,0)   将张量a的一维和二维进行置换
tensor([[1., 4., 7.],
        [2., 5., 8.],
        [3., 6., 9.]], dtype=torch.float64)
创建一个三维的张量:c
tensor([[[1., 2., 3.],
         [4., 5., 6.],
         [7., 8., 9.]]], dtype=torch.float64)
torch.Size([1, 3, 3])
torch.Size([3, 3, 1])

进程已结束,退出代码为 0

tensor的运算 

 

import torch
import numpy as np
a = torch.tensor([[1,2,3],[4,5,6],[7,8,9]],dtype=float)
b = torch.tensor([[10,10,10],[10,10,10],[10,10,10]],dtype=float)
print("a的值:",a)
print("b的值:",b)

print(a+100)                  #点加
print(a + b)
print(a.add(b))

print(a*b)                    #点乘

print(a @ b)                  #矩阵相乘
print(a.matmul(b))            #矩阵相乘
print(torch.mm(a,b))          #矩阵相乘

运行结果

C:\Users\Ywind\anaconda3\envs\pytorch\python.exe D:\pytorch\pytorch_study\tensor的运算.py 
a的值: tensor([[1., 2., 3.],
        [4., 5., 6.],
        [7., 8., 9.]], dtype=torch.float64)
b的值: tensor([[10., 10., 10.],
        [10., 10., 10.],
        [10., 10., 10.]], dtype=torch.float64)
tensor([[101., 102., 103.],
        [104., 105., 106.],
        [107., 108., 109.]], dtype=torch.float64)
tensor([[11., 12., 13.],
        [14., 15., 16.],
        [17., 18., 19.]], dtype=torch.float64)
tensor([[11., 12., 13.],
        [14., 15., 16.],
        [17., 18., 19.]], dtype=torch.float64)
tensor([[10., 20., 30.],
        [40., 50., 60.],
        [70., 80., 90.]], dtype=torch.float64)
tensor([[ 60.,  60.,  60.],
        [150., 150., 150.],
        [240., 240., 240.]], dtype=torch.float64)
tensor([[ 60.,  60.,  60.],
        [150., 150., 150.],
        [240., 240., 240.]], dtype=torch.float64)
tensor([[ 60.,  60.,  60.],
        [150., 150., 150.],
        [240., 240., 240.]], dtype=torch.float64)

进程已结束,退出代码为 0

tensor的微分计算: 

 

import torch
import numpy as np
x =torch.tensor([1.0,2.0,3.0,4.0,5.0],requires_grad=True, dtype=torch.float32)#requires_grad默认会是false
print("检验requires_grad:\n",x.requires_grad)
print("X的梯度:\n",x.grad)
print("目标函数的方法:\n",x.grad_fn)

print("y = torch.sum(x**2):")
y = torch.sum(x**2)
print(y)
print("y的计算值(item):",y.item())
print("y的计算方法(grand_fn):",y.grad_fn)

print("x的梯度",x.grad)

y.backward()    #利用自动微分计算微分
print('shape:{0};x的梯度:{1}'.format(x.grad.size(),x.grad))

运行结果:

C:\Users\Ywind\anaconda3\envs\pytorch\python.exe D:\pytorch\pytorch_study\tensor的微分计算.py 
检验requires_grad:
 True
X的梯度:
 None
目标函数的方法:
 None
y = torch.sum(x**2):
tensor(55., grad_fn=<SumBackward0>)
y的计算值(item): 55.0
y的计算方法(grand_fn): <SumBackward0 object at 0x0000021BC398BAC8>
x的梯度 None
shape:torch.Size([5]);x的梯度:tensor([ 2.,  4.,  6.,  8., 10.])

进程已结束,退出代码为 0

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值