pytorch学习笔记5--pytorch基本运算

PyTorch学习笔记(一)Tensor运算 PyToch学习笔记,记录了张量的运算和求梯度的方法。 阅读详情

基本运算

add/minus/multiply/divide

matmul

注意:torch.mm:仅适用于2d矩阵相乘,不建议使用,建议使用matmul来计算矩阵乘法

  1. * :表示相同位置上元素相乘
  2. matmul(@):表示矩阵相乘
a = torch.rand(4,3,28,64)
b = torch.rand(4,3,64,32)
torch.matmul(a,b).shape # 只计算最后两维的乘积
:torch.Size([4,3,28,32])

a = torch.rand(4,3,28,64)
b = torch.rand(4,1,64,32)  
torch.matmul(a,b).shape # 有broadcasting 操作
:torch.Size([4,3,28,32])

基本函数

  1. 使用pow,其作用等价于 : a ** num
  2. sqrt等价于pow(a,1/2)
  3. rsqrt是对平方根求导
  4. exp()
  5. log()
  6. tensor.floor():向下取整
  7. tensor.ceil():向上取整
  8. tensor.trunc():把一个浮点数裁剪出整数部分
  9. tensor.frac():把一个浮点数裁剪出小数部分
  10. tensor.round():四舍五入
  11. tensor.clamp():裁剪
    1. tensor.clamp(min):对于小于tensor中的数如果小于min就修改成min
    2. tensor.clamp(min,max):对于tensor中的数值,如果大于max都修改成max

统计属性

norm
  1. norm vs normalize and batch_norm是有区别的:norm是范数的意思,normalize、batch_norm是归一化
  2. matrix norm 和vector norm 是有区别的
a = torch.full([8],1)
b = a.view(2,4)
c = a.view(2,2,2)
a.norm(1) # a tensor 的一范式
: tensor(8.)
b.norm(1)
: tensor(8.)
c.norm(1)
: tensor(8.)

b.norm(2) # b tensor 的二范式 
: tensor(2.8284)
b.norm(1,dim=1)
:tensor(4.,4.)
mean,sum,min,max,prod,

对于argmin,argmax:如果不给出固定的dimension,会把tensor打平成dim=1,然后返回最小、最大的索引。

a = torch.arange(8).view(2,3).float()
: tensor([[0,1,2,3],
            [4,5,6,7]])
a.min(),a.max(),a.mean(),a.prod(),a.sum(),a.argmin(),a.argmax()
:tensor(0.),tensor(7.),tensor(3.5000),tensor(0.),tensor(28.),tensor(0),tensor(7)
argmin,argmax
a = torch.rand(4,10)
: tensor([[0.4992, 0.4095, 0.5239, 0.8184, 0.3184, 0.6433, 0.2028, 0.1133, 0.6991,0.3260],
        [0.1473, 0.2765, 0.1476, 0.2192, 0.8490, 0.7610, 0.0072, 0.6767, 0.1496, 0.2772],
        [0.0691, 0.4229, 0.6794, 0.9665, 0.3935, 0.9259, 0.3509, 0.6875, 0.8682, 0.0592],
        [0.2496, 0.3506, 0.8447, 0.2141, 0.4849, 0.2772, 0.3786, 0.6603, 0.8913, 0.1118]])
     
a.max(dim=1)
:(tensor([0.8184, 0.8490, 0.9665, 0.8913]), tensor([3, 4, 3, 8]))

a.argmax(dim=1)
tensor([3, 4, 3, 8])

a.max(dim=1,keepdim=True) # 希望结果的维度(dim)和a保持一致
:(tensor([[0.8184],
         [0.8490],
         [0.9665],
         [0.8913]]), tensor([[3],
         [4],
         [3],
         [8]]))
         
 a.argmax(dim=1,keepdim=True)
 :tensor([[3],
        [4],
        [3],
        [8]])
kthvalue,topk

kthvalue 第几小的值

a = torch.rand(4,10)
: tensor([[0.4992, 0.4095, 0.5239, 0.8184, 0.3184, 0.6433, 0.2028, 0.1133, 0.6991,0.3260],
        [0.1473, 0.2765, 0.1476, 0.2192, 0.8490, 0.7610, 0.0072, 0.6767, 0.1496, 0.2772],
        [0.0691, 0.4229, 0.6794, 0.9665, 0.3935, 0.9259, 0.3509, 0.6875, 0.8682, 0.0592],
        [0.2496, 0.3506, 0.8447, 0.2141, 0.4849, 0.2772, 0.3786, 0.6603, 0.8913, 0.1118]])

a.topk(3,dim=1)
:(tensor([[0.8184, 0.6991, 0.6433],
         [0.8490, 0.7610, 0.6767],
         [0.9665, 0.9259, 0.8682],
         [0.8913, 0.8447, 0.6603]]), tensor([[3, 8, 5],
         [4, 5, 7],
         [3, 5, 8],
         [8, 2, 7]]))

a.topk(3,dim=1,largest=False):概率最小的几个
:(tensor([[0.1133, 0.2028, 0.3184],
         [0.0072, 0.1473, 0.1476],
         [0.0592, 0.0691, 0.3509],
         [0.1118, 0.2141, 0.2496]]), tensor([[7, 6, 4],
         [6, 0, 2],
         [9, 0, 6],
         [9, 3, 0]]))
         
a.kthvalue(8,dim=1)# 第八小的值,在这里就是第三大的值
:(tensor([0.6433, 0.6767, 0.8682, 0.6603]), tensor([5, 7, 8, 7]))

a.kthvalue(8)
:(tensor([0.6433, 0.6767, 0.8682, 0.6603]), tensor([5, 7, 8, 7]))
>,>=,<,<=,!=,==
  1. a>0 返回的是对应的mask
  2. a>0 等价于torch.ge(a,0)
  3. torch.eq(a,b),比较a,b中的每个元素的值,返回一个mask
  4. torch.equal(a,b) 比较a,b中每个值,返回True or False

高阶操作(GPU)

where

torch.where(condition,a,b)->tensor c:c中数值的来源于:a,b

cond = torch.rand(2,2)
:tensor([[0.9019, 0.2225],
        [0.4002, 0.4745]])
        
a = torch.zeros(2,2)
:tensor([[0., 0.],
        [0., 0.]])

b = torch.ones(2,2)
:tensor([[1., 1.],
        [1., 1.]])
        
torch.where(cond>0.5,a,b)# 免去了for循环的嵌套,可以在gpu上运行
:tensor([[0., 1.],
        [1., 1.]])
Gather

torch.gather(input,dim,index,out=None) -> Tensor
input:表示要查的表
dim:对input查找的维度
index:查找的索引值

prob = torch.randn(4,10)
idx = prob.topk(dim=1,k=3)
:(tensor([[1.3720, 1.0751, 1.0114],
         [2.3205, 0.9811, 0.5586],
         [1.1462, 0.9951, 0.9102],
         [1.9489, 0.9159, 0.7970]]), tensor([[9, 3, 2],
         [9, 4, 5],
         [0, 2, 9],
         [3, 8, 6]]))
 
 label = torch.arange(10)+100
 :tensor([100, 101, 102, 103, 104, 105, 106, 107, 108, 109])
 
 idx = idx[1]
 :tensor([[9, 3, 2],
        [9, 4, 5],
        [0, 2, 9],
        [3, 8, 6]])

torch.gather(label.expand(4,10),dim=1,index=idx.long())
:tensor([[109, 103, 102],
        [109, 104, 105],
        [100, 102, 109],
        [103, 108, 106]])

梯度

梯度是一个向量
在这里插入图片描述

  1. how to search for minima?
    θ t + 1 = θ t − α t ∗ Δ ∗ f ( θ t ) \theta_{t+1} = \theta_t - \alpha_t * \Delta * f(\theta_t) θt+1​=θt​−αt​∗Δ∗f(θt​)
    function:
    J ( θ 1 , θ 2 ) = θ 1 2 + θ 2 2 J(\theta_1,\theta_2)=\theta_1^2+\theta_2^2 J(θ1​,θ2​)=θ12​+θ22​
    objective:
    m i n θ 1 , θ 2 J ( θ 1 , θ 2 ) min_{\theta_1,\theta_2}J(\theta_1,\theta_2) minθ1​,θ2​​J(θ1​,θ2​)
    Update rules:
    θ 1 : = θ 1 − α d d θ 1 J ( θ 1 , θ 2 ) \theta_1 := \theta_1 - \alpha \frac{d}{d \theta_1}J(\theta_1,\theta_2) θ1​:=θ1​−αdθ1​d​J(θ1​,θ2​)
    θ 2 : = θ 2 − α d d θ 2 J ( θ 1 , θ 2 ) \theta_2 := \theta_2 - \alpha \frac{d}{d \theta_2}J(\theta_1,\theta_2) θ2​:=θ2​−αdθ2​d​J(θ1​,θ2​)
    derivatives:
    d d θ 1 J ( θ 1 , θ 2 ) = d d θ 1 θ 1 2 + d d θ 1 θ 2 2 = 2 θ 1 \frac{d}{d \theta_1}J(\theta_1,\theta_2)=\frac{d}{d \theta_1}\theta_1^2+\frac{d}{d \theta_1}\theta_2^2=2\theta_1 dθ1​d​J(θ1​,θ2​)=dθ1​d​θ12​+dθ1​d​θ22​=2θ1​
    d d θ 2 J ( θ 1 , θ 2 ) = d d θ 2 θ 1 2 + d d θ 2 θ 2 2 = 2 θ 2 \frac{d}{d \theta_2}J(\theta_1,\theta_2)=\frac{d}{d \theta_2}\theta_1^2+\frac{d}{d \theta_2}\theta_2^2=2\theta_2 dθ2​d​J(θ1​,θ2​)=dθ2​d​θ12​+dθ2​d​θ22​=2θ2​

  2. 鞍点和局部极小值会影响到搜索最小值

  3. optimizer

    1. initialization status
      在这里插入图片描述

    2. learning rate (stepLR)
      在这里插入图片描述

    3. momentum
      在这里插入图片描述

    4. etc

loss

Mean Squared Error(MSE):
1. MSE:$loss = \sum(y-y^-)^2$
2. L2_norm = $||y-y^-||_2$ : $\sqrt{\sum{(y-y^-)}^2}$,注意有一个开根号的过程
3. torch.norm((y-pred),2),是开过根号的
自动求导:torch.autograd.grad[loss,[w1,w2,…]]和loss.backward()
x = torch.ones(1)
w = torch.full([1],2)
w.required_grad_()# 设置w可以求导
mse = F.mse_loss(torch.ones(1),x * w)
torch.auto.grad.grad(mse,[w])# mse 代表损失,[w]表示哪些参数要求导数。
:(tensor([2.]))

mse.backward() # 也可以这样计算导数,因为网络图已经记住计算导数的路径了,并且该函数把计算出来的导数保存到对应需要梯度的变量上,通过tensor.grad 来获取导数值
w.grad
:tensor([2.])
Cross Entropy Loss

注意:softmax可以让所有变量的概率和为1

sigmoid : S ( x ) = 1 1 + e − x S(x) = \frac{1}{1+e^{-x}} S(x)=1+e−x1​
softmax : S ( y i ) = e y i ∑ j e y j S(y_i) = \frac{e^{y_i}}{\sum_j{e^{y_j}}} S(yi​)=∑j​eyj​eyi​​
logits scores:[2.0,1.0,0.1],需要经过softmax函数,转变成概率值[0.7,0.2,0.1]
对softmax函数求导: p i p_i pi​是对应概率值, a j a_j aj​是参数
在这里插入图片描述

a = torch.rand(3)
a.requires_grad_()
p = F.softmax(a,dim=0)
# p.backward()# 如果后面还需要在使用torch.backward(),需要设置retain_graph=True
torch.autograd.grad(p[1],[a],retain_graph=True)
:(tensor([-0.1143,  0.2311, -0.1168]),)
1. binary
2. multi-class
3. +softmax
4. leave it to Logistic Regression Part
c语言【分糖果】2023蓝桥杯4124(枚举,递归,dfs) 但是这是不符合我们糖果刚好分完的条件的,我们应该往回退到上一层,也就是孩子6这层,然后j+1=3,孩子7分到3个第二种糖果,这也不符合我们糖果刚好分完的条件,然后就会再次回退到孩子6这里,然后j+1=4,让我们的孩子7获得5块第二种糖果,然后还是不符合糖果刚分完的条件,于是再一次退回到孩子6这里,然后就会有外循环i+1=1,j=1,孩子7分到1块第一种糖果1块第二块糖果......然后就是这样的不停地回溯,试探,直到把整棵树遍历一遍,并且记录所有的满足条件的组合。先放一下我的代码,我的代码超时啦救命! 阅读详情

相关推荐

【通信协议】I2C总线(一主多从)

I2C总线(一主多从)之软件模拟代码详解

m0_75090944的博客 9844

trunc python_Python torch.trunc方法代码示例

# 需要导入模块: import torch [as 别名]# 或者: from torch import trunc [as 别名]def modf(x, out=None):"""Return the fractional and integral parts of a tensor, element-wise.The fractional and integral parts are neg...

weixin_39534780的博客 386

详解GPU显存和batch size的关系

GPU显存、规格指标;神经网络训练,显存占用

orangerfun的博客 6212

Pytorch之torch.trunc()语法、参数和实际应用案例

`torch.tanh()` 是双曲正切激活函数,将输入值压缩到 `(-1, 1)` 区间,具有平滑的S形曲线。常用于神经网络中引入非线性特性,或处理需要对称输出范围的数据。

王国平的博客 472

Simulink仿真模块 - Data Type Conversion

Data Type Conversion将输入信号转换为指定的数据类型 在仿真库中的位置为: Simulink / 常用模块 Simulink / Signal Attributes 模型为: 说明 DataTypeConversion模块可将任何 Simulink®数据类型的输入信号转换为您指定的数据类型。 注意 要通过指定模块参数来控制输出数据类型,或者要从下游模块继承数据类型,使用DataTypeConversion模块。要...

jk_101的博客 2521

Lammps实现甲烷与水的竞争吸附-循环不同气体分子

Lammps实现甲烷与水的竞争吸附

Rockyoung 5375

[PyTroch系列-8]:PyTorch基础 - 张量的取整运算

第3部分舍入函数 2.1 四舍五入的函数:torch.around() torch.around() 函数返回指定数字的四舍五入值。 torch.around(a,decimals) 参数说明: a: 数组 decimals: 舍入后小数点的位数。 默认值为0,转换为整数。 如果为负,整数将四舍五入到小数点左侧的位置 #实例 a = torch.Tensor([1.0,5.55, 123, 0.567, 25.532]) print ('原数组:') print (a) p...

文火冰糖(王文兵)的博客 1万+

ardupilot如何让官网支持自己的硬件方案

本节主要记录ardupilot中如何让官网支持自己的硬件方案。参考1参考2。

陌城烟雨 159

人工智能深度学习-Torch框架-数学运算

统计从小到大(默认0,1,2,3,4,5,6,7)的元素出现的次数,没有的元素记作0。13.torch.mode():众数,返回一个众数,以及其原本虽在视图的索引。返回值为一个排序好的张量列表,以及一个对应索引位置的视图。3.round:四舍五入,这里的四舍五入还要看前面整数的奇偶性,基进偶不进。计算正余弦值:torch.sin(input,out=None)计算正切函数:torch.tan(input,out=None)计算余弦值:torch.cos(input,out=None)返回张量中的唯一值。

dgsiwbe的博客 1154

手把手教你学SIMULINK模块库文件专栏--Scope 模块详解

模块是 Simulink 中的一个信号接收模块,用于实时显示信号波形。该模块可以捕捉并可视化仿真过程中信号的变化,帮助用户直观地分析系统的动态行为。模块都能提供强有力的支持。通过深入了解其参数的影响及结合 MATLAB 脚本的应用,读者可以更加有效地利用这一模块进行仿真和研究。此外,通过实际应用场景的扩展以及常见问题解答部分的帮助,能够更好地掌握。模块是一个非常实用的工具,适用于需要实时显示信号波形的各种场景。模块的参数,可以进一步增强学习体验。模块参数的影响,下面我们将详细探讨每个参数如何影响波形显示。

MHD0815的博客 312

英伟达 Jetson AGX Thor 官方入门教程(二)CUDA、Docker、JetPack 设置

本文详细介绍了NVIDIA Jetson AGX Thor开发套件的安装与配置流程。主要内容包括:1) BSP安装的三种方法(Jetson ISO、SDK Manager和Linux刷写脚本)及其适用场景;2) Docker环境的完整配置步骤及测试方法;3) CUDA工具包的两种安装方式(容器化和原生安装)及其性能对比;4) JetPack SDK的安装选项。文章提供了详细的命令行操作指南和故障排除建议,帮助开发者快速搭建AI开发环境,充分发挥Jetson平台的硬件性能优势。

机器人控制与仿真应用 1737

Pytorch学习之torch----数学操作(三)

1. torch.reciprocal(input, out=None) 说明:返回一个新张量,包含输入input张量每个元素的倒数。 参数: input(Tensor) -- 输入张量 out(Tensor, 可选) -- 输出张量 >>> a = torch.randn(5) >>> a tensor([ 0.6535, 1.3616, -1....

励志的小胡子 1万+

如何实现在Go语言中替换程序自身

总结起来,我们可以通过将新的程序二进制文件写入磁盘,并在运行时启动这个新的程序来实现在Go语言中替换程序自身。在Go语言中,有时候我们需要在程序运行时替换程序自身,例如更新程序版本或者进行热重启。本文将介绍一种正确的方式来实现在Go语言中替换程序自身的方法,并提供相应的源代码示例。此外,替换程序自身可能会导致正在运行的程序产生意外行为或终止,请谨慎使用,并确保在合适的时机进行替换操作。实现替换程序自身的关键是将新的程序二进制文件写入到磁盘,并在运行时启动这个新的程序。函数启动新的可执行文件,并在后台运行。

HoUnix的博客 289

pytorch学习笔记5--pytorch基本运算2

文章目录感知机的梯度推导单输出单层感知机多输出感知机梯度推导链式法则多层感知机反向传播Logistic regressionQ1: why not maximize accuracy?Q2 : why call logistic regressionsoftmax交叉熵EntropyCross Entropy对于分类问题为什么不用MSEsoftmax 和 sigmoid?多分类全连接层nn.ReL...

code_fighter 博客 1172

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Pytorch笔记目录 --持续更新中

Pytorch笔记目录 --持续更新中 为了更好的掌握Pytorch,准备用博客来记录一些Pytorch的知识点以及一些网络结构 Pytorch版本:1.5 Pytorch笔记【1】–导入Pytorch及判断torch基本的属性 ...

python_LC_nohtyp的博客 555

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

Pytorch Tensor基本数学运算

1. 加法运算 示例代码: import torch # 这两个Tensor加减乘除会对b自动进行Broadcasting a = torch.rand(3, 4) b = torch.rand(4) c1 = a + b c2 = torch.add(a, b) print(c1.shape, c2.shape) print(torch.all(torch.eq(c1, c2))) ...

洪流之源 5万+

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

pytorch基本运算-范数

本文介绍了PyTorch中L1和L2范数的计算方法。L2范数计算向量元素平方和的平方根,而L1范数则是向量元素绝对值的总和。文章通过代码示例展示了如何用torch.norm()计算L2范数,用torch.abs().sum()计算L1范数,并扩展到矩阵范数计算。在5×5全1矩阵的案例中验证了计算结果,其中L2范数的平方等于矩阵所有元素平方和,L1范数等于所有元素绝对值之和。这些范数计算在深度学习中具有重要意义。

专注python+工程实践的热心婶子 1328

深度学习|pytorch基本运算

本文介绍了PyTorch的基本运算操作,包括随机张量生成(torch.randn)、多维张量创建(torch.tensor)、张量变形(reshape)、加减运算以及广播机制。文章着重说明各函数的常用参数和使用方法,并通过具体代码示例演示运算效果。作为PyTorch入门指南,本文旨在帮助初学者快速掌握张量基础操作,同时推荐读者参考官方文档深入学习。所有示例代码均附有运行结果截图,直观展示不同运算的实际效果。

专注python+工程实践的热心婶子 1040

pytorch入门--矩阵基本运算

本篇pytorch的矩阵基本运算进行展示,包含: add/subtract/multiply/divide matmul pow 次方 sqrt/rsqrt 次方根 近似运算 上下界操作 使用方法和含义均在代码的批注中给出,因为有较多的输出,所以设置输出内容的第一个值为当前print()方法所在的行 矩阵基本运算 import torch import numpy as np import sys loc = sys._getframe() _ = '\n' ''' add/subtract/m

qq_43923588的博客 4536

pytorch 基本数学运算

pytorch中的运算遵循其Broadcasting规则,这里不详细解释。 目录 1. 矩阵对应位置加减乘除 2. 矩阵相乘 3. 幂运算 3. 指数与对数运算 4. 近似取值(向上取整,向下取整,四舍五入,取小数等) 5. clamp 1. 矩阵对应位置加减乘除 包括add(加),sub(减),mul(乘),div(除),pytorch中重载了加减乘除的运算符...

Defiler_Lee的博客 3258

Pytorch学习笔记【6】---基本运算

Pytorch学习笔记【6】—基本运算 Pytorch笔记目录:点击进入 文章目录Pytorch学习笔记【6】---基本运算1. Add2. Sub3. mul and div4. matmul5. pow and sqrt6. Exp and log7. Approximation8. round9. clamp 1. Add tensor相加有两种方法效果基本一样 # Add a = torch.rand(3,4) b = torch.rand(4) print(a+b) # or the result

python_LC_nohtyp的博客 1012

Pytorch学习(3):Tensor合并、分割与基本运算

文章目录前言一、合并Cat/Stack1.Cat2.Stack二、分割Split/Chunk1.Split2.Chunk三、基本运算1.加减乘除2.矩阵乘法mm/@/matmul3.幂运算**4.指数exp/对数log5.近似floor/ceil/round/trunc/frac6.裁剪(归化)clamp总结 前言 Pytorch学习笔记第三篇,关于Tensor的合并(cat/stack)、分割(split/chunk)与基本运算。 一、合并Cat/Stack 1.Cat Tensor中cat是co..

Leafing_的博客 6214

PyTorch张量运算

本文介绍PyTorch张量运算

诸神缄默不语的博客 1803

【Pytorch基础】Pytorch的基本运算操作

  Pytorch跟Python一样都是一种编程语言,只不过Pytorch可以在GPU中进行计算。简单理解的话,就是这个区别吧。至于如何学习Pytorch,个人 觉得完全可以类比,Python两者语法跟用法没有太大差异。再者,为什么学习Pytorch基本计算,而不是用Python基本计算代替再转成tensor格式。个人在代码实现中的体会是:太麻烦,因为Pytorch默认创建变量的类型是float32,使用Python的数据类型如array是float64,如果进行tensor的转换后在计算会报错,变量类型不

sxl的博客 2080

什么是Pytorch?掌握Pytorch的基本元素操作、运算操作

创建矩阵的操作 创建一个没有初始化的矩阵: 对比有无初始化的矩阵: 当声明一个未初始化的矩阵时, 它本身不包含任何确切的值. 当创建一个未初始化的矩阵时, 分配给矩阵的内存中有什么数值就赋值给了这个矩阵, 本质上是毫无意义的数据. 注意: torch.Size函数本质上返回的是一个tuple, 因此它支持一切元组的操作. 三、Pytorch的基本运算操作

黑马程序员官方博客 515

PyTorch入门2——张量数值运算

梳理介绍张量的各类数值运算,包括:基本运算、点积运算/矩阵乘法、比较运算、逻辑运算、初等函数运算、统计运算以及指定运算设备方法。

1379号程序员的博客 1290
上一篇: pytorch学习笔记4--pytorch数据类型
下一篇: Git & Github
jeffery0628
博客等级 码龄11年 39粉丝 112原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值