Pytorch笔记

PyTorch 笔记 PyTorch 是一个开源的 Python 机器学习库,基于 Torch 库,底层由C++实现,应用于人工智能领域,如计算机视觉和自然语言处理。PyTorch 最初由 Meta Platforms 的人工智能研究团队开发,现在属 于Linux 基金会的一部分。PyTorch 特性:动态计算图: PyTorch 的计算图是动态的,在执行时构建计算图,这意味着在每次计算时,图都会根据输入数据的形状自动变化。这为实验和调试提供了极大的灵活性,因为开发者可以逐行执行代码,查看中间结果。张量计算。 阅读详情

目录

tensor与array转换

查看 Tensor 数据类型

Tensor数据类型转换

扩维(unsqueeze)和降维(squeeze)

更改数据维度

PIL和OpneCV的RGB排列

ToTensor

torch.view()

参数 inplace

判断一个对象是否可以迭代

ipython 常用指令

模块函数

Visdom 可视化

tensorboardX 可视化

保存 ipython 环境数据

提取迭代器中的某些元素(将其转化为list)

pytorch图像预处理

张量乘法


PyTorch中文文档:https://www.pytorchtutorial.com/docs/

PyTorch官方手册:https://pytorch.org/docs/stable/index.html

PyTorch 教程目录:https://www.pytorchtutorial.com/pytorch-tutorials-list/#PyTorch

tensor与array转换

>>> a = torch.Tensor([4,5,6])  # 默认 a.dtype 为 int64
>>> b = np.array([1,2,3]       # 默认 b.dtype 为 int32

>>> c = torch.Tensor(b)        # array --> tensor(float32)
>>> c = torch.from_numpy(b)    # array --> tensor(int32) 保持原数据类型

>>> d = np.array(a)            # tensor --> array(int64)
>>> d = a.numpy()              # tensor --> array(int64)

查看 Tensor 数据类型

pytorch所有数据类型:https://pytorch.org/docs/stable/tensors.html

>>> test = torch.Tensor([1.2, 3.4])
>>> test.dtype            # 查看数据类型
torch.float32
>>> test.type()           # 查看数据类型及平台
'torch.FloatTensor'               # CPU数据
'torch.cuda.FloatTensor'          # GPU数据

Tensor数据类型转换

>>> test = torch.Tensor([1.2, 3.4])
>>> test.dtype                    # 查看数据类型
torch.float32
>>> test.to(torch.uint8)          # 转换数据类型位8位整型
>>> test.dtype
torch.uint8
>>> test.to(torch.ByteTensor)     # Error,不能使用CPU或GPU类型来转换

扩维(unsqueeze)和降维(squeeze)

unsqueeze:参数是几,就在该维度上增加 / 减小 一个维度

>>> a = torch.ones(3)    # a.dtype == float32
>>> a.shape              # 输出 [3]
torch.Size([3])

>>> a.unsqueeze(0).shape    
torch.Size([1, 3])   

>>> a.unsqueeze(1).shape
torch.Size([3, 1])

squeeze:参数是几,且参数维度如果是1,则压缩掉,否则不变

>>> a = torch.ones(3, 1)    # [3, 1]
>>> a.squeeze(0).shape      # 不变
torch.Size([3, 1])
>>> a.squeeze(1).shape      # [3]
torch.Size([3])
>>> b = torch.ones(1,3,1)
>>> b.squeeze().shape       # [3],不带参数则会将所有为1的维度全部压缩掉
torch.Size([3])

更改数据维度

举例:将形状为(64, 28, 28)的 data 更改为 (64, 1, 28, 28)

>>> data = torch.zeros([64, 28, 28])    # shape = (64, 28, 28)

1、如上,扩维(unsqueeze)和降维(squeeze)

>>> data.unsqueeze(1).shape    # 在维度1上扩维
torch.Size([64, 1, 28, 28])

2、view(*shape) -> Tensor

>>> data.view(64, 1, 28, 28).shape
torch.Size([64, 1, 28, 28])
>>> data.view(data.shape[0], 1, data.shape[1], data.shape[2]).shape    # 一个道理
torch.Size([64, 1, 28, 28])

3、reshape(*shape) -> Tensor

用法同上

4、直接操作(使用 None,代表新增一个维度)

>>> data[:,None,:,:].shape        # 维度1上增加扩维
torch.Size([64, 1, 28, 28])

 

 

PIL和OpneCV的RGB排列

PIL图像在转换为numpy.ndarray后,格式为(H, W, C),像素顺序为RGB;
OpenCV在cv2.imread()后数据类型为numpy.ndarray,格式为(H, W, C),像素顺序为BGR。

ToTensor

先将图像由 (H, W, C) 转置为(C, H, W)格式,再转为float后每个像素除以255,将像素范围转换至 [0.0, 1.0]。

from PIL import Image
from torchvision.transforms import ToTensor, ToPILImage

col = Image.open('color.img')    # 彩色图像
col.size()    # (224, 224, 3)
to_tensor = ToTensor() # img -> tensor
t = to_tensor(col)    # to_tensor 接收 array 数组
t.size()    # (3, 224, 224)
gray = Image.open('gray.img')    # 灰度图像
gray.size()    # (224, 224)      # Image读取灰度图为二维
to_tensor(a).size()    # (1, 224, 224),也会添加一个维度

torch.view()

相当于 np.reshape()

参数 inplace

当 inplace = True,则操作是在原对象上完成,返回处理后的原对象。

而 inplace = False,则将在原对象上处理的结果保存到另一个对象上(会消耗多余的内存),返回另一个对象。

判断一个对象是否可以迭代

>>> from collections import Iterable
>>> isinstance([1, 2, 3], Iterable)         # 列表可以迭代
True

ipython 常用指令

shell 快捷键

  • Ctrl-C   中止当前正在执行的代码
  • Ctrl-A   将光标移动到行首
  • Ctrl-E   将光标移动到行尾
  • Ctrl-U  清除该行
  • Ctrl-L   清屏

% —— 魔法指令(实际使用时,指令前面不需加 %)

In [1]: pwd                        # 查看当前路径
In [2]: ls                         # 查看当前路径下的文件
In [3]: cd                         # 切换工作目录
In [4]: run 路径/test.py            # 运行python脚本
In [5]: who 或 %who_ls 或 %whos     # 查看环境中的变量信息
In [6]: xdel (或 del , 其属于python的关键字) # 删除环境中的变量
In [7]: hist                       # 查看输入的历史记录

【注】:切换盘符时,必须使用双引号:

>>> cd "D:\\work"
D:\work

!—— 系统指令,切换到 cmd 模式

In [1]: !pip search torch    # 切换到 cmd 模式

ipython中运行python文件

In [1]: !python "E:\code\example.py"

模块函数

scatter_(dim, index, src) ——> Tensor

功能:表示将src中的数据根据index的索引值按照dim的方向填充到objdect中

eg:E:\J---Paper\Paper Code\luo_[XifengGuo]_CapsNet-Pytorch-master\capsulenet.py    
line 77
--------------------
class CapsuleNet(nn.Module):
    ...
    y = Variable(torch.zeros(length.size()).scatter_(1, index.view(-1, 1), 1.))
    ...

torch.clamp(input, min, max, out=None) -> Tensor

功能:限定输入变量(可以为向量)的区间

y_i \left\{\begin{matrix} min,\ \ if\ x_i<min \ \ \ \ \ \ \ \ \ \ \ \ \\ x_i,\ \ \ \ \ if\ min\leq x_i\leq max \ \ \\ max,\ \ if\ x_i>max \ \ \ \ \ \ \ \ \ \ \ \ \end{matrix}\right.

np.concatenate((a1, a2, ...), axis=0, out=None)

功能:数据拼接

eg:E:\J---Paper\Paper Code\luo_[XifengGuo]_CapsNet-Pytorch-master\capsulenet.py    
line 133
--------------------
def show_reconstruction(model, test_loader, n_images, args):
    ...
    img = combine_images(np.transpose(data, [0, 2, 3, 1]))
    ...

torch.Tensor.max(dim=None, keepdim=False) -> Tensor or (Tensor, Tensor)

功能:求张量在维度dim上的最大值,返回最大值和最大值的索引

eg:E:\J---Paper\Paper Code\luo_[XifengGuo]_CapsNet-Pytorch-master\capsulenet.py    
line 73
--------------------
class CapsuleNet(nn.Module):
    ...
    index = length.max(dim=1)[1]
    ...

 

Visdom 可视化

详细使用方法:https://www.pytorchtutorial.com/tag/visdom/

1、启动 visdom

E:\python> python -m visdom.server    # 前台执行
E:\python> nohup python -m visdom.server &    # 后台执行

2、打开浏览器,输入启动后分配的地址,一般为:http://localhost:8097

3、运行脚本执行

tensorboardX 可视化

详细过程请参考github项目链接:https://github.com/lanpa/tensorboardX

1、首先需要安装 tensorflow、tensorboard、tensorboardX

>>> pip3 install tensorflow    # 一般安装完 tensorflow 后会默认安装后两个
>>> pip3 install tensorboard
>>> pip3 install tensorboardX

2、运行相应的代码,生成数据文件,待下一步可视化运行

以官网 demo.py 为例,其存放在如下路径:https://github.com/lanpa/tensorboardX/tree/master/examples

运行该脚本,则会生成 runs 文件,文件路径及名称在脚本代码中设定

3、使用 tensorboard 运行

E:\Python37\Scripts 是我 tensorboard 所在的路径(默认在python安装文件夹中的Scripts中),C:\Users\Tom\Desktop\runs 是我上部脚本运行生成文件 runs 的路径

E:\Python37\Scripts> tensorboard --logdir C:\Users\Tom\Desktop\runs

运行完后,终端会输出:

Serving TensorBoard on localhost; to expose to the network, use a proxy or pass --bind_all
TensorBoard 2.0.0 at http://localhost:6006/ (Press CTRL+C to quit)

4、复制输出中的链接:http://localhost:6006/ 在浏览器中运行即可

保存 ipython 环境数据

1、安装 save_ipython_variables

pip install save_ipython_variables

2、因为该模块中使用了python2的语法,直接导入会发生错误,所以需修改源码

错误如下:

进入该包的路径:你的python安装路径\Python37\Lib\site-packages\save_ipython_variables

将55行的

print 'Loaded the following variables:', names_loaded_successfully

修改为:

print('Loaded the following variables:', names_loaded_successfully)

提取迭代器中的某些元素(将其转化为list)

以读取MNIST数据集为例:

torch.utils.data.DataLoader(dataset, ...)

功能:装载数据集

【注】:第一个参数为数据集,数据集可通过 torchvision 包导入已有的数据集,也可以自己构造数据集。

构造自己的数据集:https://blog.youkuaiyun.com/Teeyohuang/article/details/79587125

torchvision.dataset.MNIST()

功能:导入MNIST数据集

# 此处仅读取MNIST的测试集
>>> test_loader = torch.utils.data.DataLoader(datasets.MNIST(dataset_path, train=False, \
    download=False,transform=transforms.ToTensor()),batch_size=batch_size, shuffle=True)
>>> for x, y in test_loader:
...     print(x.size())    # x 表示数据 (batch_size, C, W, H)
...     print(y.size())    # y 表示标签 (batch_size)

# 可以将 test_loader 转为列表
>>> list(test_loader)        # MNIST划分为许多batch_size
>>> list(test_loader)[0]     # 第一个batch
>>> list(test_loader)[0][0]  # 第一个batch的数据
>>> list(test_loader)[0][1]  # 第一个batch的标签

model.named_parameters(prefix='', recurse=True)

功能:迭代打印每一层的名称和权重参数

>>> for name, param in model.named_parameters():
...     print(name)
...     print(param.size())
...
conv1.weight
torch.Size([256, 1, 9, 9])
conv1.bias
torch.Size([256])
primarycaps.conv2d.weight
torch.Size([256, 256, 9, 9])
primarycaps.conv2d.bias
torch.Size([256])
digitcaps.weight
torch.Size([10, 1152, 16, 8])

model.parameters(recurse=True)

功能:与model.named_parameters类似,只是仅有权重参数,没有名称

>>> for name, param in model.parameters():
...     print(param.size())
...
torch.Size([256, 1, 9, 9])
torch.Size([256])
torch.Size([256, 256, 9, 9])
torch.Size([256])
torch.Size([10, 1152, 16, 8])

提取其中的元素:

>>> list(model.parameters())
[数据]
>>> len(list(model.parameters()))
5
>>> list(model.parameters())[0].size()
torch.Size([256, 1, 9, 9])
>>> list(model.parameters())[1].size()
torch.Size([256])

pytorch图像预处理

torchvision.transforms是pytorch中的图像预处理包,一般用Compose把多个步骤整合到一起:

transforms.Compose(
    [ transforms.CenterCrop(10),
      transforms.ToTensor() ]
)

参考:Pytorch:transforms的二十二个方法

张量乘法

torch.matmul(input, other, out=None) -> Tensor

功能:张量乘法,对于多维张量相乘:(1)看最后两个维度是否满足矩阵乘法定义: (a,\ b) \times (b,\ c)=(a,\ c),(2)前面的维度必须符合广播要求(对应的不同维度要么一方为空,要么一方为1)

广播机制:https://www.runoob.com/numpy/numpy-broadcast.html

【注】:多维的张量乘法的本质仍然进行的是矩阵乘法(在最后两个维度),而前面的维度则通过广播来进行匹配。

>>> a = torch.randn([3, 4])              # 
>>> b = torch.randn([6, 5, 8, 4, 2])     # 6, 5, 8   可以广播
>>> torch.matmul(a, b).shape
torch.Size([6, 5, 8, 3, 2])

>>> a = torch.randn([7, 1, 3, 4])        #    7, 1    可以广播
>>> b = torch.randn([6, 1, 8, 4, 2])     # 6, 1, 8
>>> torch.matmul(a, b).shape
torch.Size([6, 7, 8, 3, 2])

>>> a = torch.randn([7, 3, 4])           #       7    不能广播
>>> b = torch.randn([6, 1, 8, 4, 2])     # 6, 1, 8
>>> torch.matmul(a, b).shape
Error!

torch.dot(input, tensor) -> Tensor

功能:计算一维张量的点积

>>> torch.dot(torch.tensor([1, 2, 3]), torch.tensor([4, 5, 6]))
tensor(32)    # 1*4 + 2*5 + 3*6 = 32

*

功能:点乘(张量对应位置相乘)

>>> torch.tensor([2, 3]) * torch.tensor([2, 1])
tensor([4, 3]) 
>>> torch.tensor([[2, 3]]) * torch.tensor([[2], [1]])    # dim=(1, 2) dim=(2, 1) 此处两者皆会广播为(2, 2)
tensor([[4, 6],
        [2, 3]])
>>> torch.tensor([[1, 2],[3, 4]]) * torch.tensor([[5, 6],[7, 8]])
tensor([[ 5, 12],
        [21, 32]])

nn.ModuleList 与 nn.Sequential 的区别

        nn.ModuleList 的 forward函数需要自己实现,故可以自己定义网络的执行顺序(甚至重复执行),而 nn.Sequential 则会根据定义的网络自动生成 forward 函数,顺序执行。

PyTorch 中的 ModuleList 和 Sequential: 区别和使用场景:https://blog.youkuaiyun.com/byron123456sfsfsfa/article/details/89930990

官方文档:https://pytorch.org/docs/stable/nn.html#sequential

损失函数 nn.BCEloss()

参数:https://www.jianshu.com/p/ac3bec3dde3e

参考:https://blog.youkuaiyun.com/geter_CS/article/details/84747670

 

 

 

 

 

 

 

 

 

 

 

 

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

相关推荐

SLAM算法的优缺点

SLAM(Simultaneous Localization and Mapping,同时定位与地图构建)算法是一种通过传感器数据实时估计机器人自身位置和构建环境地图的技术。

selenia8860的博客 2907

Pytorch当中squeeze(1)函数和unsqueeze(1)函数的区别及含义

方法会在指定的位置(这里是维度 1)上增加一个新的维度,使得张量的维度数增加,并将新增的维度的大小设置为 1。是用于张量维度操作的方法之一,它的作用是在指定位置(这里是维度 1)上增加一个维度,将维度的大小设置为 1。是用于张量维度操作的方法之一,它的作用是将张量中尺寸为 1 的维度压缩(去除)掉。这表示在原来的张量中的维度 1 处增加了一个维度,该维度的大小为 1。具体来说,如果张量在指定维度(这里是维度 1)上的尺寸为 1,的张量,其中维度 1 的尺寸为 1。的张量,在维度 1 上使用。

m0_57317650的博客 3772

强化学习-马尔可夫模型

前文提到了强化学习源自马尔可夫决策过程,本文从马尔可夫概念入手,讲解和马尔可夫有关的模型和概念。在马尔科夫决策过程中,我们有一个智能体,它在一个马尔科夫过程中进行决策,每次决策都会导致状态的转移和获得即时奖励。智能体的目标是通过选择动作来最大化未来奖励的期望值。通常马尔科夫决策过程是个五元组:SAPRγSAPRγS 表示状态集合,代表智能体可能处于的所有状态。A 表示动作集合,代表智能体可以采取的所有动作。

君子之学必日新,日新者日进也。不日新者必日退,未有不进而不退者 8062

pytorch学习之---squeeze()和unsqueeze()函数功能及使用

首先这个squeeze单词啥意思: 1.squeeze(1)和squeeze(-1)作用: 两者的效果一样,都是给张量tensor降维,但不是啥张量都可以用这两个函数来降维,它只能降维一种情况下张量的维度。就是我的张量tensor是一个n*1维度的张量,例如:张量[[1], [2], [3]]是一个3*1维的,调用这两个函数后效果如图: 但是如果不是n*1的这种2维张量的话,如本就是1维的,或者m*n(其中m和n都是大于1的)这种的话,调用这个函数一点效果没有。 2.squeeze(0)

guihaiyuan123的博客 6万+

Linear超高PSRR线性稳压器-典型应用电路解析

本文整理完了LT3045数据手册内所有的典型应用电路,试图让沉默的电路开口,简单介绍了他们这样做的目的和原理,从中我们可以更加熟悉这颗经典芯片的应用。但也有一些电路并没有搞懂,遗留下了不少问题。

硬件工程师笔记 2945

SAP MM新手避坑指南:工厂间调拨用301还是303?手把手教你选对移动类型

本文深入解析SAP MM模块中工厂间调拨的301与303移动类型,帮助新手避开常见陷阱。通过对比一步法(301)和两步法(303+305)的核心差异、适用场景及财务影响,提供清晰的决策框架和实战技巧,确保库存调拨的准确性和效率。

weixin_29223603的博客 349

PyTorch中的squeeze() 函数

在神经网络中,某些层可能会输出带有大小为1的额外维度的张量。这些维度可能是因为在卷积层之后没有使用适当的池化层,或者在全连接层之前输入数据的维度不匹配所导致的。:在深度学习任务中,经常需要将不同来源的张量进行维度对齐以便进行运算(如加法、连接等)。函数是一个很有用的张量操作,它用于移除张量中所有大小为1的维度。函数可以用来移除这些多余的维度,使得输出张量的形状与后续层的输入要求相匹配。函数可以减少张量所占用的内存空间,从而允许在有限的内存资源下处理更多的数据。,则只会移除该指定维度上大小为1的维度。

YHKKun的博客 1784

java调用第三方api接口获取数据

弊端,但是并不是每个接口都适用于这套模板,之前写的接口不适用,都是在这个模板里做了定制处理(if 特殊表 -》处理),需要考虑兼容之前的代码,这种兼容代码,有风险会改掉之前的逻辑个人喜欢,有一个接口,写一段代码灵活自由些。2.还有一部分是对post请求的返回数据,做处理,因为json返回的格式如果双方没有约定好,里面数据是多层json嵌套,需要做处理。江同事交接的就是这个代码模板,可以看下源码调试一下,之前交接的视频,也可以看下,主要还是看代码理解快些,将 写好的代码达成jar包,上传到linux上去,

随风不随水的博客 2036

PyTorch 02:通过 PyTorch 构建神经网络

深度学习网络一般量级都很大,包含数百个层级,这也是为什么叫“深度”学习网络。你可以像在上个 notebook 展示的一样,仅使用权重矩阵构建深度网络,但是这通常很繁琐并且不好实施。PyTorch 有一个很方便的模块 nn,可以有效地构建大型神经网络。 # Import necessary packages %matplotlib inline %config InlineBackend.figure_format = 'retina' import numpy as np import torch i

科学边界 861

TCGA数据下载保姆级教程:用GDC-client从零搞定,附配置文件避坑指南

本文提供TCGA数据下载的完整教程,详细讲解如何使用GDC-client工具从零开始配置到高效获取基因组数据。涵盖环境准备、认证配置、数据检索、高效下载及故障处理等关键步骤,并附配置文件避坑指南,帮助生物医学研究者快速掌握TCGA数据下载技巧。

weixin_30892037的博客 262

YOLOv11 损失函数进阶:Varifocal Loss 让正负样本精度双升

创建self.alpha = alpha # 正样本权重系数self.gamma = gamma # 聚焦系数self.lambda_reg = lambda_reg # 回归损失权重# 分类损失:Varifocal Classification Loss# 正样本权重:基于预测置信度# 计算 BCE 损失并加权cls_loss = cls_loss.sum() / (cls_true.sum() + 1e-6) # 按正样本数归一化。

m0_71589036的博客 443

Pytorch教程(2)--0. 快速入门

本节我们使用的训练集为60000张手写数字图片及对应的标签,测试集为10000张同类型的图片及标签。我们设计一个人工神经网络,输入训练集进行训练,得到该网络模型及其参数。然后,用这个训练好的网络模型进行图片识别,再跟该图片的标签进行比对。具体过程包括以下几步:读取数据集、创建模型、训练模型、使用模型进行预测。

suizier的博客 440

【教程4>第8章>第44节】本章整体思维导图与学习总结

本教程系列提供FPGA/MATLAB/Simulink学习资源,包含《MATLAB入门100例》、《FPGA入门100例》、《Simulink入门60例》等基础教程,以及《FPGA/MATLAB/Simulink联合开发》进阶教程和《人工智能基础应用研究》专题,适合不同层次的学习者系统掌握相关技术。

FPGA/MATLAB学习教程/源码/项目合作开发 450

pytorch笔记

pytorch学习时的笔记

m0_63276919的博客 1134

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

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

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

Pytorch学习内容笔记

(3) torch.IntTensor、torch.FloatTensor、torch.DoubleTensor 创建指定类型的张量。data1=torch.randint(0,10,[3,4,5])#范围0-10 3个四行五列的张量。c.对数输入的shape不同的张量,对应的最后几个维度必须符合矩阵运算规则(二维点乘三维也能算)(2)torch.Tensor根据形状创建张量,也可以用来创建指定数据的张量。补充:创建指定值的:torch.full和torch.full_like。

2403_89474459的博客 766

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

【Pytorch入门】小土堆PyTorch入门教程完整学习笔记(详细笔记并附练习代码 ipynb文件)

【Pytorch入门】小土堆PyTorch入门教程完整学习笔记(详细笔记 文末附练习代码 ipynb文件)

几度热忱的博客 3万+

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

莫烦pytorch学习笔记

莫烦pytorch学习笔记(1)-Regression回归 莫烦pytorch视频 莫烦github 代码: """ View more, visit my tutorial page: https://morvanzhou.github.io/tutorials/ My Youtube Channel: https://www.youtube.com/user/MorvanZhou Dependencies: torch: 0.4 matplotlib """ import torch import t

weixin_41281151的博客 252

【pytorch学习】土堆pytorch笔记1

常用的图像预处理方法 ,一般用于转换图片格式有多个图片处理方法,如:PIL:用PIL的Image工具打开numpy:用OpenCV打开。

qq_61814350的博客 1186

小土堆PyTorch笔记

教程链接:【PyTorch深度学习快速入门教程(绝对通俗易懂!)【小土堆】】https://www.bilibili.com/video/BV1hE411t7RN?p=32&vd_source=f717c2112946f17e567aedfc2225b30e特别鸣谢几度热忱大佬的博客参考【Pytorch入门】小土堆PyTorch入门教程完整学习笔记(详细笔记并附练习代码 ipynb文件)-优快云博客GitHub代码仓库symyyds/pytorch_tudui: tudui_pytorchhttps://

m0_61179495的博客 677

pytorch个人学习笔记

来自datawhale的深入浅出pytorch教程的笔记。主要对第二章和第三章的常用函数和方法进行梳理,方便要用的时候查找和复习,同时巩固对pytorch实现深度学习基本流程的认识。

ersanwuqi的博客 569

【学习Pytorch代码笔记】【B站小土堆】

B站学习小土堆Pytorch代码

m0_69118404的博客 336

PyTorch教程笔记

Tensors||||Transforms||||Autograd||||1、PyTorch介绍与张量的创建_哔哩哔哩_bilibili环境:python3.9。

nkjbkj的博客 698

pytorch学习笔记

(开篇词)PyTorch 学习笔记 | PyTorch 学习笔记

天地沧海 175

刘二大人pytorch笔记目录

以下为刘二大人(pytorch)教程自己做的笔记,如有错误还请见谅,可评论交流 梯度下降 反向传播 线性回归(torch版本)

weixin_54646357的博客 990

Pytorch学习笔记【B站:小土堆】

pytorch学习入门

m0_58730471的博客 5146
上一篇: C/C++语言笔记
下一篇: Python笔记
且听风吟0618
博客等级 码龄11年 150粉丝 25原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值