pytorch基础2

下面是常见函数的代码例子

  1 import torch
  2 import numpy as np
  3 print("分割线-----------------------------------------")
  4 #加减乘除操作
  5 a = torch.rand(3,4)
  6 b = torch.rand(4)
  7 print(a)
  8 print(b)
  9 print(torch.add(a, b))
 10 print(torch.sub(a, b))
 11 print(torch.mul(a, b))
 12 print(torch.div(a, b))
 13 print(torch.all(torch.eq(a - b,torch.sub(a,b))))#判断torch的减法和python的减法结果是否一致
 14 print("分割线-----------------------------------------")
 15 #矩阵乘法(点乘和叉乘)matmul  mm  @   *
 16 a = torch.ones(2,2)*3
 17 b = torch.ones(2,2)
 18 print(a*b)#点乘积
 19 print(a.matmul(b))#叉乘积
 20 print([email protected])#叉乘积
 21 print(a.mm(b))#叉乘积,相比于前两种,这一种只能适合二维数组的乘积
 22 a = torch.rand(4,3,28,64)
 23 b = torch.rand(4,3,64,32)
 24 #torch.mm(a,b).shape#此时会报错,mm只适合二维
 25 print(torch.matmul(a,b).shape)#torch.Size([4, 3, 28, 32])
 26 b = torch.rand(4,1,64,32)
 27 torch.matmul(a, b).shape #torch.Size([4, 3, 28, 32])
 28 b = torch.rand(4,64,32)
 29 #torch.matmul(a, b).shape ,报错,因为b的4对应a的3无法进行广播,所以报错
 30 print("分割线-----------------------------------------")
 31 #power的使用
 32 a = torch.full([2,2],3)
 33 print(a.pow(2))
 34 print(a**2)
 35 aa = a**2
 36 print(aa.sqrt())
 37 print(aa**(0.5))
 38 print(aa.rsqrt())#开根号后的倒数
 39 print("分割线-----------------------------------------")
 40 #floor(),ceil(),round(),trunc(),frac()的使用
 41 a = torch.tensor(3.14)
 42 print(a.floor(),a.ceil(),a.trunc(),a.frac())#后两个是取整,和取小数
 43 print(a.round()) #四舍五入
 44 print("分割线-----------------------------------------")
 45 #clamp 和 dim,keepdim
 46 grad = torch.rand(2,3)*15
 47 print(grad.max(),grad.median(), grad.min())
 48 print(grad)
 49 print(grad.clamp(10))#小于10的都变成10
 50 print(grad.clamp(3,10))#不在3到10之间的变为3或者10
 51 a = torch.randn(4,10)
 52 print(a.max(dim=1))#返回每一列最大值组成的数组和对应的下标
 53 print(a.argmax(dim = 1))#这个只返回最大值对应的下标
 54 print(a.max(dim=1,keepdim=True))#keepdim的作用是使返回值维度是否仍然为原来的维度不变
 55 print(a.argmax(dim=1,keepdim=True))
 56 print("分割线-----------------------------------------")
 57 #topk和kthvalue
 58 print(a.topk(3,dim=1))#返回每行最大的三个数和下标
 59 print(a.topk(3,dim=1,largest=False))#返回每行最小的三个数和下标
 60 print(a.kthvalue(5,dim=1))#返回每行第五大的数字和对应数字的下标
 61 print("分割线-----------------------------------------")
 62 #矩阵的比较,cat的使用
 63 m = torch.rand(2,2)
 64 n = torch.rand(2,2)
 65 print(m,n)
 66 print(m == n)
 67 print(m.eq(n))
 68 print(m > n)
 69 a =  torch.rand(4,32,8)
 70 b = torch.rand(5,32,8)
 71 print(torch.cat([a,b],dim = 0).shape)#按行进行拼接,torch.Size([9, 32, 8])
 72 #更详细的拼接可以看下面的图
 73 a1 = torch.rand(4,3,32,32)
 74 a2 = torch.rand(4,1,32,32)
 75 #torch.cat([a1,a2],dim = 0).shape#报错原因是如果进行维度0上进行拼接,则要保证其他维度必须一致
 76 a1 = torch.rand(4,3,14,32)
 77 a2 = torch.rand(4,3,14,32)
 78 print(torch.cat([a1,a2],dim=2).shape)#torch.Size([4, 3, 28, 32])
 79 print("分割线-----------------------------------------")
 80 #stack和split的使用
 81 #用来进行维度的扩充,这个就是在dim =2进行扩充
 82 print(torch.stack([a1,a2],dim=2).shape)#torch.Size([4, 3, 2, 14, 32])
 83 aa , bb =a1.split([2,2],dim=0)#拆分成两份每份数目是2,2
 84 print(aa.shape,bb.shape)
 85 aaa,bbb = a1.split(2,dim=0)#每份长度为2
 86 print(aaa.shape,bbb.shape)
 87 aa,bb = a1.chunk(2,dim = 0)#拆成两块,每块一个
 88 print("分割线-----------------------------------------")
 89 #where,gather的使用
 90 cond = torch.rand(2,2)
 91 print(cond)
 92 a = torch.zeros(2,2)
 93 b = torch.ones(2,2)
 94 s = torch.where(cond>0.5,a,b)
 95 print(s)#如果大于0.5对应位置为a的对应位置的值,否则为b的对应位置的值
 96 prob = torch.randn(4,10)
 97 idx = prob.topk(dim =1,k=3)
 98 id = idx[1]
 99 print(id)#索引下标
100 label= torch.arange(10)+100
101 d = torch.gather(label.expand(4,10),dim =1,index = id)#获取对应索引下标的值
102 print(d)

运行结果如下

D:\anaconda\anaconda\pythonw.exe D:/Code/Python/龙良曲pytorch学习/高级操作.py
分割线-----------------------------------------
tensor([[0.5581, 0.2369, 0.1379, 0.3702],
        [0.1565, 0.1022, 0.5839, 0.1778],
        [0.0204, 0.1498, 0.5276, 0.4219]])
tensor([0.7969, 0.9313, 0.0608, 0.0245])
tensor([[1.3551, 1.1682, 0.1988, 0.3947],
        [0.9535, 1.0335, 0.6448, 0.2023],
        [0.8173, 1.0811, 0.5884, 0.4464]])
tensor([[-0.2388, -0.6944,  0.0771,  0.3457],
        [-0.6404, -0.8291,  0.5231,  0.1533],
        [-0.7766, -0.7815,  0.4667,  0.3974]])
tensor([[0.4448, 0.2206, 0.0084, 0.0091],
        [0.1247, 0.0952, 0.0355, 0.0044],
        [0.0162, 0.1395, 0.0321, 0.0103]])
tensor([[ 0.7003,  0.2544,  2.2669, 15.1075],
        [ 0.1964,  0.1097,  9.5973,  7.2539],
        [ 0.0255,  0.1609,  8.6706, 17.2148]])
tensor(True)
分割线-----------------------------------------
tensor([[3., 3.],
        [3., 3.]])
tensor([[6., 6.],
        [6., 6.]])
tensor([[6., 6.],
        [6., 6.]])
tensor([[6., 6.],
        [6., 6.]])
torch.Size([4, 3, 28, 32])
分割线-----------------------------------------
tensor([[9., 9.],
        [9., 9.]])
tensor([[9., 9.],
        [9., 9.]])
tensor([[3., 3.],
        [3., 3.]])
tensor([[3., 3.],
        [3., 3.]])
tensor([[0.3333, 0.3333],
        [0.3333, 0.3333]])
分割线-----------------------------------------
tensor(3.) tensor(4.) tensor(3.) tensor(0.1400)
tensor(3.)
分割线-----------------------------------------
tensor(14.8811) tensor(8.5843) tensor(5.4463)
tensor([[10.3914, 14.8811,  8.5843],
        [10.6012,  5.4463,  5.7588]])
tensor([[10.3914, 14.8811, 10.0000],
        [10.6012, 10.0000, 10.0000]])
tensor([[10.0000, 10.0000,  8.5843],
        [10.0000,  5.4463,  5.7588]])
torch.return_types.max(
values=tensor([1.1859, 0.7394, 1.2261, 0.5407]),
indices=tensor([5, 1, 2, 4]))
tensor([5, 1, 2, 4])
torch.return_types.max(
values=tensor([[1.1859],
        [0.7394],
        [1.2261],
        [0.5407]]),
indices=tensor([[5],
        [1],
        [2],
        [4]]))
tensor([[5],
        [1],
        [2],
        [4]])
分割线-----------------------------------------
torch.return_types.topk(
values=tensor([[ 1.1859,  0.8406,  0.7883],
        [ 0.7394,  0.4172,  0.2871],
        [ 1.2261,  0.9851,  0.9759],
        [ 0.5407,  0.1773, -0.2789]]),
indices=tensor([[5, 4, 7],
        [1, 2, 4],
        [2, 8, 4],
        [4, 1, 8]]))
torch.return_types.topk(
values=tensor([[-1.7351, -0.3469, -0.3116],
        [-1.8399, -1.1521, -0.3790],
        [-1.3753, -0.6663, -0.2762],
        [-1.6875, -1.5461, -0.9697]]),
indices=tensor([[0, 8, 6],
        [3, 5, 0],
        [7, 1, 5],
        [0, 2, 3]]))
torch.return_types.kthvalue(
values=tensor([-0.1758,  0.0470, -0.2039, -0.6223]),
indices=tensor([2, 9, 3, 6]))
分割线-----------------------------------------
tensor([[0.9107, 0.4905],
        [0.6499, 0.3425]]) tensor([[0.6911, 0.9619],
        [0.1428, 0.5437]])
tensor([[False, False],
        [False, False]])
tensor([[False, False],
        [False, False]])
tensor([[ True, False],
        [ True, False]])
torch.Size([9, 32, 8])
torch.Size([4, 3, 28, 32])
分割线-----------------------------------------
torch.Size([4, 3, 2, 14, 32])
torch.Size([2, 3, 14, 32]) torch.Size([2, 3, 14, 32])
torch.Size([2, 3, 14, 32]) torch.Size([2, 3, 14, 32])
分割线-----------------------------------------
tensor([[0.7541, 0.3861],
        [0.9605, 0.7175]])
tensor([[0., 1.],
        [0., 0.]])
tensor([[5, 4, 6],
        [8, 2, 3],
        [8, 6, 4],
        [6, 2, 1]])
tensor([[105, 104, 106],
        [108, 102, 103],
        [108, 106, 104],
        [106, 102, 101]])

Process finished with exit code 0

  

原文地址:https://www.cnblogs.com/henuliulei/p/11823620.html

时间: 2024-08-30 18:20:02

pytorch基础2的相关文章

Pytorch基础的基本概念

1.什么是Pytorch,为什么选择Pytroch? 2.Pytroch的安装 3.配置Python环境 4.准备Python管理器 5.通过命令行安装PyTorch 6.PyTorch基础概念 GPU云服务器默认提供了pytorch的环境, 7.通用代码实现流程(实现一个深度学习的代码流程) import torch import torch.nn as nn import torch.nn.functional as F class Net(nn.Module): def __init__(

PyTorch基础——词向量(Word Vector)技术

一.介绍 内容 将接触现代 NLP 技术的基础:词向量技术. 第一个是构建一个简单的 N-Gram 语言模型,它可以根据 N 个历史词汇预测下一个单词,从而得到每一个单词的向量表示. 第二个将接触到现代词向量技术常用的模型 Word2Vec.在实验中将以小说<三体>为例,展示了小语料在 Word2Vec 模型中能够取得的效果. 在最后一个将加载已经训练好的一个大规模词向量,并利用这些词向量来做一些简单的运算和测试,以探索词向量中包含的语义信息. 知识点 N-Gram(NPLM) 语言模型 Wo

Pytorch基础重新巩固

首先是pytorch的机制: Torch 自称为神经网络界的 Numpy, 因为他能将 torch 产生的 tensor 放在 GPU 中加速运算 最常用的数据形式是tensor   ,      torch中的tensor类似tensorflow中的tensor; 在编写代码的时候,注意把自己的数据转为tensor,然后如果需要梯度计算类似的操作再转为variable:若需要cuda运算,再加上cuda 其次是pytorch用于存储不断变化的量的variable: variable计算的时候,

pytorch基础问题

本文将自己在pytorch学习中遇见的各种问题整理起来,并且持续更新. 1:torch.Tensor和torch.tensor的区别 开始使用torch.tensor和torch.Tensor的时候发现结果都是一样的.都能生成新的张量.但根源上是有差别的. import torch n=torch.tensor([[3,4],[1,2]]) x=torch.Tensor([[3,4],[1,2]]) print(n,'|||',x) print(n.shape,'|||',x.shape) pr

PyTorch基础-torch

一.张量数据类型 1.1 pytorch与python数据类型对比 python pytorch Int IntTensor of size() float FloatTensor of size() Int array IntTensor of size [d1,d2,-] Float array FloatTensor of size [d1,d2,-] string ont-hot or Embedding(Word2Vec,glove) 由于PyTorch不是一个完备的语言库,它是面向数

PyTorch基础——预测共享单车的使用量

预处理实验数据 读取数据 # 下载并解压数据集 !wget http://labfile.oss.aliyuncs.com/courses/1073/bike-sharing-dataset.zip !unzip bike-sharing-dataset.zip #导入需要使用的库 import numpy as np import pandas as pd #读取csv文件的库 import matplotlib.pyplot as plt import torch from torch.au

PyTorch基础——使用神经网络识别文字中的情感信息

一.介绍 知识点 使用 Python 从网络上爬取信息的基本方法 处理语料"洗数据"的基本方法 词袋模型搭建方法 简单 RNN 的搭建方法 简单 LSTM 的搭建方法 二.从网络中抓取并处理数据 引入相关包 下载所需数据并解压 链接:https://pan.baidu.com/s/1Jg5NPxc9L-M8Tdgh70Tvig 提取码:dpqq # 导入程序所需要的程序包 #PyTorch用的包 import torch import torch.nn as nn import tor

Pytorch基础——使用 RNN 生成简单序列

一.介绍 内容 使用 RNN 进行序列预测 今天我们就从一个基本的使用 RNN 生成简单序列的例子中,来窥探神经网络生成符号序列的秘密. 我们首先让神经网络模型学习形如 0^n 1^n 形式的上下文无关语法.然后再让模型尝试去生成这样的字符串.在流程中将演示 RNN 及 LSTM 相关函数的使用方法. 实验知识点 什么是上下文无关文法 使用 RNN 或 LSTM 模型生成简单序列的方法 探究 RNN 记忆功能的内部原理 二.什么是上下文无关语法 上下文无关语法 首先让我们观察以下序列: 01 0

PyTorch基础——机器翻译的神经网络实现

一.介绍 内容 "基于神经网络的机器翻译"出现了"编码器+解码器+注意力"的构架,让机器翻译的准确度达到了一个新的高度.所以本次主题就是"基于深度神经网络的机器翻译技术". 我们首先会尝试使用"编码器+简单解码器"的构架,来观察普通编码器-解码器构架能够取得的效果.然后会尝试"编码器+带有注意力机制的解码器"构架,看看加上注意力能让模型获得怎样的提高. 实验知识点 机器翻译"平行语料"的