pytorch学习笔记 1. pytorch基础 tensor运算

PyTorch教程-1:PyTorch中的Tensor基础 PyTorch 教程系列:https://blog.csdn.net/qq_38962621/category_10652223.html PyTorch教程-1:PyTorch中的Tensor基础 首先,引入PyTorch的模块: import torch 设置运算资源 使用 torch.cuda.is_avaliable() 来判断设备上的GPU是否可用,如果可用则返回True,使用 torch.device() 则可以参数指定计算资源: 参数为"cpu"表示使用CPU计算 参数为"cuda" 阅读详情

pytorch与tensorflow是两个近些年来使用最为广泛的机器学习模块。开个新坑记录博主学习pytorch模块的过程,不定期更新学习进程。 文章较为适合初学者,欢迎对代码和理解指点讨论,下面进入正题。

import torch
import numpy as np

t1 = torch.tensor([1,2,3,4],dtype=torch.float64)
print(t1)
print(type(t1))
print(t1.size())

在这里插入图片描述

与numpy基本一致,tensor可以用于创建多维的array(张量)。

c = t1[0] + t1[1]
print(c)

在这里插入图片描述

对单元素进行加减乘除运算,得到的结果仍然是一个tensor。

x = torch.tensor(3.)
w = torch.tensor(4.,requires_grad=True) # only calculate the deriative when necessary
b = torch.tensor(5., requires_grad=True)

y = w * x + b # 正向传播过程

y.backward() # 反向传播,计算梯度的过程
print("dy/dx : "x.grad)
print("dy/dw : ",w.grad)
print("dy/db :"b.grad)

在这里插入图片描述
只有requires_grad属性为真的张量,在反向传播的过程中会计算梯度。

与numpy数组之间的转换

因为很多通常使用的数据,使用的是numpy矩阵的形式,pytorch也提供了一些函数用于将numpy数组转换为张量。
一般而言,将numpy ndarray转换为tensor的方法有以下三种 :

np_matrix = np.array([1,3,5,7,9])
test1 = torch.tensor(np_matrix)
test2 = torch.from_numpy(np_matrix)
test3 = torch.as_tensor(np_matrix)

实际测试中会发现,直接使用tensor构建的实例会新分配一个内存,而使用from_numpy与as_tensor两个方法与之前的矩阵是统一个内存,不会重新分配内存。因此在优化内存方面可以优先使用后两个函数。(tips : 在将numpy数组转换为tensor时需要注意精度问题,pytorch一般使用float32)

tensor的数据类型转换

使用 long float short int 等等方法,可以改变张量的数据类型,numpy方法可以将tensor转回numpy矩阵。

pyTorch中tensor运算 文章目录PyTorch的简介PyTorch中主要的包PyTorch的安装使用GPU的原因使数据在GPU上运行什么使Tensor(张量)一些术语介绍Tensor的属性介绍(Rank,axis,shape)RankAxis(轴)shape(形状)不同环境下对Tensor的解释卷积神经网络中对Tensor的解释(CNN)PyTorch下的基本张量输出通道和特征映射PyTorch中对Tensor的解释 PyTorch的简介 PyTorch中主要的包 torch:是顶级PyTorch软件包和tensor库。 torc 阅读详情

相关推荐

龙良曲pytorch基础课程学习笔记

什么是Pytorch? PyTorch 是一个基于 Python 的科学计算包,主要定位两类人群: NumPy 的替代品,可以利用 GPU 的性能进行计算 深度学习研究平台拥有足够的灵活性和速度 开始学习 tensor对象 在 TensorFlow 中,数据不是以整数,浮点数或者字符串形式存在的,而是被封装在一个叫做 tensor 的对象中。Tensor是张量的意思,张量包含了0到任意维度的量...

kexiaoleqq的博客 4052

深度学习之Pytorch tensor 的数学运算

1、基础运算 可以使用 + - * / 推荐 也可以使用 torch.add, mul, sub, div (1)加法运算 def add(): # add + # 这两个Tensor加减乘除会对b自动进行Broadcasting a = torch.rand(3,4) b = torch.rand(4) print("a = {}".format(a)) print("b = {}".format(b)) # a、b列数相同,行数不同,将a.

deep_love1314的博客 1709

PyTorch学习笔记(一)Tensor运算

PyToch学习笔记,记录了张量的运算和求梯度的方法。

longrootchen的博客 2312

pytorch把整数tensor转为int

【代码】pytorch把整数tensor转为int。

zhuzyibooooo的博客 2079

深度学习Pytorch-Tensor的属性、算术运算

深度学习Pytorch-Tensor的属性、算术运算

算法工程师 1322

PyTorch学习笔记(一)——Tensor的基础语法

目录一、张量的创建1.1 直接从数据中创建 一、张量的创建 1.1 直接从数据中创建 data = [1, 2, 3] torch.tensor(data) # tensor([1, 2, 3])

⚡ 1398

Pytorch中Tensor数据类型转换

Pytorch中Tensor数据类型转换: 1)Tensor的int、float数据类型转换: 在Tensor后加 .long(), .int(), .float(), .double()等即可 2)Tensor与numpy数据类型转换: Tensor -> Numpy 使用 data.numpy(),data为Tensor变量 Numpy -> Tensor 使用 torch.from_numpy(data),data为numpy变量 3)Tensor与Python数据类型转换: Tenso

weixin_45590193的博客 1万+

【Niagara Vykon N4 】物联网学习 03照明控制及照明时间表

3.1 设计思路 3.2逻辑组件添加 ①依据原有控制照明逻辑,打开palette,找到schedule模块,添加BoolenSchedule。 ②打开kitContrl,找到Util,并添加BoolenSwitch。 ③剪切到原有的逻辑线,并进行逻辑连接,如下图。 ④新建BooleanWritable,命名为Switch,设置参数并进行逻辑连接,若下图。 3.3界面设计 ⑤至此完成了逻辑的设...

weixin_45217107的博客 2867

Pytorch tensor 数据类型快速转换三种方法

tensor.type(torch.cuda.DoubleTensor) 或者 tensor.type(‘torch.cuda.DoubleTensor’)tensor.type(torch.cuda.FloatTensor) 或者 tensor.type('torch.cuda.FloatTensor')tensor.type(torch.cuda.LongTensor) 或者 tensor.type('torch.cuda.LongTensor')

张哥频道:电生理信号和磁共振成像 1万+

scannet数据集下载文件

scannet数据集下载文件 由于大家会申请scannet数据集,审批比较慢,我将下载的文件里面的内容贴出来,大家可以复制放进py文件中,运行就可以下载 ps:别再私信要数据集了,这个自己下载,如果光三维数据的话,还是很快的,当然如果路由器翻了墙的话,下载会更快。 #!/usr/bin/env python # Downloads ScanNet public data release # Run with ./download-scannet.py (or python download-scannet.

weixin_40766438的博客 9242

20220601超简单百度地图街景图片爬取+绿视率计算

真的不难咯。

weixin_39676904的博客 1万+

基于PyTorch的Tensor基本操作总结(一)

本文全面详细地简介了再深度学习中用pytorch时不可避免地tensor的基本操作,包括tensor的十多种创建方法、numpy转tensor、tensor的加减乘除以及各种函数计算(常见的三角函数、sigmoid)和求和求均值等等、tensor的比较,还有常用的tensor的形状调整

weixin_60418242的博客 3577

别再套用星形公式了!三角形接法PMSM的FOC控制,扇区判断与作用时间推导全解析

本文深入解析三角形接法永磁同步电机(PMSM)的FOC控制技术,重点探讨30度相位差对SVPWM扇区判断与电压矢量作用时间的影响。通过数学推导与实验验证,详细讲解修正后的扇区划分规则、作用时间计算公式优化方法,并提供可直接移植到STM32的代码实现,帮助工程师解决三角形接法特有的相电流重构与同步采样难题。

weixin_30689307的博客 483

PyTorch中Tensor的数据类型和运算

在使用Tensor时,我们首先要掌握如何使用Tensor来定义不同数据类型的变量。Tensor时张量的英文,表示多维矩阵,和numpy对应,PyTorch中的Tensor可以和numpy的ndarray相互转换,唯一不同的是PyTorch可以在GPU上运行,而numpy的ndarray只能在cpu上运行。 常用的不同数据类型的Tensor,有32位的浮点型torch.F...

ch_musk的博客 2万+

解决rt-thread上使用SPI+DMA

首先阐述下遇到的问题 使用SPI读取icm20602数据,读取频率为1000hz,使用stm32f407主控,发现CPU占用率达到了70%,将此线程注释掉后CPU占用率掉到25%,看来这里要着重优化,便萌生了使用DMA的想法。 使用SPI+DMA要进行的配置 1.开启RTT设备驱动。点击自己的工程 ->RT-Thread Setting2.在board.hzhong3.在board.c文件里加入以下函数,此函数受设备框架调用 void HAL_SPI_MspInit(SPI_HandleTypeDef

响望的博客 8097

金蝶云星空初级实施认证考题

Q4.[单选题] (1.5分) 总账中的多账簿账表主要是基于什么进行查看的Q47.[多选题] (2.5分) 销售订单的收款计划页签勾选预收之后,预收控制环节可以控制哪些节点?

m0_51994557的博客 3135

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万+

【二.图像处理核心技术】【5.形态学操作:腐蚀/膨胀/开闭运算】

想象一下,你拍了一张布满雪花点的老照片,或者扫描了字迹断裂的文档,这时候形态学操作就是你的像素整形师!它们能让模糊的边界变清晰,把断裂的笔画连起来,甚至从X光片里揪出癌细胞。今天我们要聊的,是计算机视觉界的"广场舞双雄"——腐蚀和膨胀。这俩操作就像给像素点们请了个健身教练,要么集体减肥(腐蚀),要么组团增肌(膨胀)。下次当你用美颜相机时,不妨会心一笑——这看似魔法的背后,正是形态学在默默耕耘。腐蚀的规则很简单:如果一个像素点周围的邻居不全白,它就"狗带"(变黑)。:先用砂纸打磨(腐蚀),再喷漆填补(膨胀)

商务合作|问题讨论|交流学习 请联系作者微信,加微信请务必注明来意,博客主页有联系方式 437

五、Pytorch tensor 的数学运算

目录 1、基础运算 (1)加法运算 (2)减法运算 (3)哈达玛积(element wise,对应元素相乘) (4)除法运算 2、矩阵运算 (1)二维矩阵相乘 (2)多维矩阵相乘 3、幂运算 4、开方运算 5、指数与对数运算 6、近似值运算 7、裁剪运算 1、基础运算 可以使用 + - * / 推荐 也可以使用 torch.add, mul, sub, div (1...

嘻哈吼嘿呵的博客 3699

17|CI/CD 集成与质量门禁:让精准测试进入发布流水线

本文讲解精准测试如何接入 CI/CD 流水线,并通过质量门禁辅助发布决策。测试开发工程师。Java 后端开发工程师。质量平台 / DevOps 平台建设者。想了解精准测试落地方法的技术负责人。

专注 AI 精准测试平台实战落地,分享从代码 Diff 到回归决策的完整工程闭环。主张“先建数据链路,再上 AI 智能”,让测试从“靠经验”走向“基于风险”。 74

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

【pytorch】torch.Tensor详解和常用操作

学习教材: 动手学深度学习 PYTORCH 版(DEMO) (https://github.com/ShusenTang/Dive-into-DL-PyTorch) PDF 制作by [Marcus Yang](https://github.com/chenyang1999) 1.tensor简介 在PyTorch中,torch.Tensor是存储和变换数据的主要工具。 Tensor与Numpy的多维数组非常相似。 Tensor还提供了GPU计算和自动求梯度等更多功能,这些使Tensor更适合深度学习。 2

sazass的博客 9万+

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

【Pytorch】Tensor的数学运算

Pytorch中Tensor的数学运算

宫瑞阳的博客 1932

深度学习工具包 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")

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

pytorch学习笔记(四)--tensor的基本运算

加减乘除 矩阵相乘 torch.mm 只适用于2d,不推荐 torch.matmul 推荐使用 @ 运算符重载 次方运算 a = torch.full([2,2],3) aa = a.pow(2) 操作运算如下: a.pow(n) 表示an a**n 表示an aa.sqrt() 表示aa 1/2 aa.rsqrt() 表示aa1/3 注意这里没有torch. 幂/对数 a = to...

ThetaQing的博客 7538

PyTorch基础(Numpy与Tensor)

对Tensor的操作很多,从接口的角度来划分,可以分为两类:1)torch.function,如torch.sum、torch.add等;2)tensor.function,如tensor.view、tensor.add等。这些操作对大部分Tensor都是等价的,如torch.add(x,y)与x.add(y)等价。在实际使用时,可以根据个人爱好选择。如果从修改方式的角度来划分,可以分为以下两类:1)不修改自身数据,如x.add(y),x的数据不变,返回一个新的Tensor。

钢铁男儿 1242

PyTorch基础-Tensors属性、Tensor的运算

返回一个标记元素是否为 finite/inf/nan 的mask 张量。标量说零维的张量,向量是一维的张量,矩阵是二维的张量。随机数 正态分布 标准分布。张量高于标量、向量、矩阵。

小旺的博客 537

Pytorch基础:Tensor的reshape()方法

PyTorch中的reshape()方法用于改变张量形状而不改变数据顺序,与NumPy的reshape类似。该方法支持多种参数形式(元组、列表或单独整数),要求新形状的元素总数与原张量一致。特殊参数-1可实现自动维度推断,但不能在多维度同时使用。reshape()可能返回原张量的视图(共享存储),需注意张量连续性问题。此外,torch.reshape()函数与该方法功能相同。

保持终身学习的能力,温故而知新 1万+
上一篇: cannot find output in imported module librosa报错解决
下一篇: tensorflow gpu windows配置步骤教学
Cy_coding
博客等级 码龄7年 49粉丝 88原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址