TorchVision官方文档翻译为中文-示例库变换图解-003

10、随机图片水平翻转 transforms.RandomHorizontalFlip(p=0.5) transforms.RandomHorizontalFlip(p=0.5) import torchvision.transforms as transform from PIL import Image import matplotlib.pyplot as plt import numpy as np import torch img0=Image.open('lin-xiao-xun-000003.jpg') img1=transform.RandomHorizontalFlip(p=0.8)(i 阅读详情

此示例演示了torchvision.transforms模块中提供的各种变换。

from PIL import Image
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np

import torch
import torchvision.transforms as T


plt.rcParams["savefig.bbox"] = 'tight'
orig_img = Image.open(Path('assets') / 'astronaut.jpg')
# if you change the seed, make sure that the randomly-applied transforms
# properly show that the image can be both transformed and *not* transformed!
torch.manual_seed(0) #保证每次随机生成的数是相同的


def plot(imgs, with_orig=True, row_title=None, **imshow_kwargs):
    if not isinstance(imgs[0], list): #类型是否相同,不同则对其进行变换
        # Make a 2d grid even if there's just 1 row
        imgs = [imgs]

    num_rows = len(imgs)
    num_cols = len(imgs[0]) + with_orig
    fig, axs = plt.subplots(nrows=num_rows, ncols=num_cols, squeeze=False) # 构建排布
    for row_idx, row in enumerate(imgs):
        row = [orig_img] + row if with_orig else row
        for col_idx, img in enumerate(row):
            ax = axs[row_idx, col_idx]
            ax.imshow(np.asarray(img), **imshow_kwargs)
            ax.set(xticklabels=[], yticklabels=[], xticks=[], yticks=[])

    if with_orig:
        axs[0, 0].set(title='Original image')
        axs[0, 0].title.set_size(8)
    if row_title is not None:
        for row_idx in range(num_rows):
            axs[row_idx, 0].set(ylabel=row_title[row_idx])

    plt.tight_layout()

Pad
Pad变换使用一些像素值填充图像边界。

padded_imgs = [T.Pad(padding=padding)(orig_img) for padding in (3, 10, 30, 50)]
plot(padded_imgs)

在这里插入图片描述
Resize
调整图像大小

resized_imgs = [T.Resize(size=size)(orig_img) for size in (30, 50, 100, orig_img.size)]
plot(resized_imgs)

在这里插入图片描述
CenterCrop
在中心裁剪给定图像

center_crops = [T.CenterCrop(size=size)(orig_img) for size in (30, 50, 100, orig_img.size)]
plot(center_crops)

在这里插入图片描述
FiveCrop
FiveCrop变换将给定图像裁剪为四个角和中心裁剪

(top_left, top_right, bottom_left, bottom_right, center) = T.FiveCrop(size=(100, 100))(orig_img)
plot([top_left, top_right, bottom_left, bottom_right, center])

在这里插入图片描述
Grayscale
灰度变换将图像转换为灰度

gray_img = T.Grayscale()(orig_img)
plot([gray_img], cmap='gray')

在这里插入图片描述
Random transforms

以下变换是随机的,这意味着同一Transformer实例每次变换给定图像时将产生不同的结果

ColorJitter
ColorJitter变换随机更改图像的亮度、饱和度和其他属性。

jitter = T.ColorJitter(brightness=.5, hue=.3)
jitted_imgs = [jitter(orig_img) for _ in range(4)]
plot(jitted_imgs)

在这里插入图片描述
GaussianBlur
高斯模糊变换对图像执行高斯模糊变换

blurrer = T.GaussianBlur(kernel_size=(5, 9), sigma=(0.1, 5))
blurred_imgs = [blurrer(orig_img) for _ in range(4)]
plot(blurred_imgs)

在这里插入图片描述
RandomPerspective
随机透视变换对图像执行随机透视变换

perspective_transformer = T.RandomPerspective(distortion_scale=0.6, p=1.0)
perspective_imgs = [perspective_transformer(orig_img) for _ in range(4)]
plot(perspective_imgs)

在这里插入图片描述
输出

/home/matti/miniconda3/envs/pytorch-test/lib/python3.8/site-packages/torchvision/transforms/functional.py:594: UserWarning: torch.lstsq is deprecated in favor of torch.linalg.lstsq and will be removed in a future PyTorch release.
torch.linalg.lstsq has reversed arguments and does not return the QR decomposition in the returned tuple (although it returns other information about the problem).
To get the qr decomposition consider using torch.linalg.qr.
The returned solution in torch.lstsq stored the residuals of the solution in the last m - n columns of the returned value whenever m > n. In torch.linalg.lstsq, the residuals in the field ‘residuals’ of the returned named tuple.
The unpacking of the solution, as in
X, _ = torch.lstsq(B, A).solution[:A.size(1)]
should be replaced with
X = torch.linalg.lstsq(A, B).solution (Triggered internally at /opt/conda/conda-bld/pytorch_1623448216815/work/aten/src/ATen/LegacyTHFunctionsCPU.cpp:389.)
res = torch.lstsq(b_matrix, a_matrix)[0]

RandomRotation
随机角度旋转图像

rotater = T.RandomRotation(degrees=(0, 180))
rotated_imgs = [rotater(orig_img) for _ in range(4)]
plot(rotated_imgs)

在这里插入图片描述
RandomAffine
随机仿射变换对图像执行随机仿射变换

affine_transfomer = T.RandomAffine(degrees=(30, 70), translate=(0.1, 0.3), scale=(0.5, 0.75))
affine_imgs = [affine_transfomer(orig_img) for _ in range(4)]
plot(affine_imgs)

在这里插入图片描述
RandomCrop
随机裁剪变换在随机位置裁剪图像

cropper = T.RandomCrop(size=(128, 128))
crops = [cropper(orig_img) for _ in range(4)]
plot(crops)

在这里插入图片描述
RandomResizedCrop
RandomResizedCrop变换在随机位置裁剪图像,然后将裁剪大小调整为给定大小

resize_cropper = T.RandomResizedCrop(size=(32, 32))
resized_crops = [resize_cropper(orig_img) for _ in range(4)]
plot(resized_crops)

在这里插入图片描述
RandomInvert

随机反转变换随机反转给定图像的颜色。

inverter = T.RandomInvert()
invertered_imgs = [inverter(orig_img) for _ in range(4)]
plot(invertered_imgs)

在这里插入图片描述
RandomPosterize
RandomPosterize变换通过减少每个颜色通道的位数来随机对图像进行后验证

posterizer = T.RandomPosterize(bits=2)
posterized_imgs = [posterizer(orig_img) for _ in range(4)]
plot(posterized_imgs)

在这里插入图片描述
RandomSolarize
RandomSolarize变换通过反转阈值以上的所有像素值来随机对图像进行solarizes

solarizer = T.RandomSolarize(threshold=192.0)
solarized_imgs = [solarizer(orig_img) for _ in range(4)]
plot(solarized_imgs)

在这里插入图片描述
RandomAdjustSharpness
RandomAdjustSharpness变换随机调整给定图像的清晰度

sharpness_adjuster = T.RandomAdjustSharpness(sharpness_factor=2)
sharpened_imgs = [sharpness_adjuster(orig_img) for _ in range(4)]
plot(sharpened_imgs)

在这里插入图片描述
RandomAutocontrast

RandomAutocontrast变换随机将自动对比应用于给定图像

autocontraster = T.RandomAutocontrast()
autocontrasted_imgs = [autocontraster(orig_img) for _ in range(4)]
plot(autocontrasted_imgs)

在这里插入图片描述

RandomEqualize
随机均衡给定图像的直方图

equalizer = T.RandomEqualize()
equalized_imgs = [equalizer(orig_img) for _ in range(4)]
plot(equalized_imgs)

在这里插入图片描述
AutoAugment
自动扩充转换根据给定的自动扩充策略自动扩充数据

policies = [T.AutoAugmentPolicy.CIFAR10, T.AutoAugmentPolicy.IMAGENET, T.AutoAugmentPolicy.SVHN]
augmenters = [T.AutoAugment(policy) for policy in policies]
imgs = [
    [augmenter(orig_img) for _ in range(4)]
    for augmenter in augmenters
]
row_title = [str(policy).split('.')[-1] for policy in policies]
plot(imgs, row_title=row_title)

在这里插入图片描述
Randomly-applied transforms
在给定概率p的情况下,随机应用一些变换。也就是说,即使使用相同的transformer实例调用,转换后的图像实际上可能与原始图像相同
RandomHorizontalFlip
RandomHorizontalFlip变换以给定的概率执行图像的水平翻转

hflipper = T.RandomHorizontalFlip(p=0.5)
transformed_imgs = [hflipper(orig_img) for _ in range(4)]
plot(transformed_imgs)

在这里插入图片描述
RandomVerticalFlip
RandomVerticalFlip变换以给定的概率执行图像的垂直翻转

vflipper = T.RandomVerticalFlip(p=0.5)
transformed_imgs = [vflipper(orig_img) for _ in range(4)]
plot(transformed_imgs)

在这里插入图片描述
RandomApply
随机应用变换以给定的概率随机应用变换列表

applier = T.RandomApply(transforms=[T.RandomCrop(size=(64, 64))], p=0.5)
transformed_imgs = [applier(orig_img) for _ in range(4)]
plot(transformed_imgs)

在这里插入图片描述

更多计算机视觉与图形学相关资料,请关注微信公众号:计算机视觉与图形学实战
在这里插入图片描述

11、随机视角变化 transforms.RandomPerspective() transforms.RandomPerspective(distortion_scale=0.5, p=0.5, interpolation=<InterpolationMode.BILINEAR: 'bilinear'>, fill=0) distortion_scale:角度的倾斜值,取值(0,1) import torchvision.transforms as transform from PIL import Image import matplotlib.pyplot as pl 阅读详情

相关推荐

transforms图像增强(一)

数据增强(Data Augmentation)是一种常用的数据预处理技术,通过对训练集进行各种变换和扩增操作,可以增加训练数据的多样性和丰富性,从而提高模型的泛化能力。数据增强的目的是通过对训练集中的图像进行随机变换,生成更多样的图像样本,以模拟真实世界中的各种场景和变化。这样可以帮助模型学习到更多不同的特征和模式,提高模型对于不同样本的适应能力,减少过拟合的风险。常见的数据增强操作包括图像翻转、旋转、缩放、裁剪、平移、变换色彩空间、添加噪声等。

学习记录 2727

pytorch模型构建(二)——datasets部分之数据增广及其他数据处理

一、简介 1. 图像中数据增强目的及分类概述: 目的: 增量 丰富多样性 提高模型泛化能力(尽可能的使得训练的数据与真实场景中的数据分布一致。) 原则: 保持标签一致(相应的转换) 针对业务场景(例如路标箭头检测就不要用翻转了) 不要引入无关的数据。 方法: 单样本: 主要包括 翻转,旋转,扭曲,图像仿射变换,缩放,压缩,随机crop,随机padding,HSV变换,噪声,模糊,图像(feature map)区域随机擦除,风格转换(GAN),GAN网络生成等。 多样本 主要包括 mosaic,Mi

weixin_39263657的博客 4602

眼动数据分析基础_AOI分析动态刺激物

如果您正在研究人们对如视频、动画等动态刺激物的视觉行为,动态AOI工具可为您提供类似静态AOI工具对于图片及其他静止刺激物分析的同样功能。创建和编辑动态AOI的过程和静态AOI相似。 关于动态AOI工具的使用,有几点非常重要: 多个看到相同线性动态刺激物的用户的眼动数据叠加是有价值的; 动态AOI不能用于非线性动态记录的分析; 动态AOI不能用于静态刺激物,如图片的分析; 动态AOI可以被开启、关闭、移动、调整大小及跟踪相关分析对象 首先,我们来定义两种不同的动态刺激物:线性动态刺激物(LDS),是指固

Kobe123brant的博客 3502

PyTorch 笔记Ⅸ——数据增强

文章目录数据增强说明导入必要的包读取图片并显示显示方式一显示方式二Pytorch 数据增强transforms 之旋转transforms 之裁剪transforms.functional 之裁剪特殊数据增强方式Augmentor导入 Augmentor 包读取图像并进行弹性形变数据增强实践导入新需要的模块定义数据增强函数开始处理效果展示 数据增强说明 1.本次将演绎常用的Pytorch数据增强方式 2.本次将简单介绍数据增强模块Augmentor的使用方式 导入必要的包 import PIL.Image

DeepHao'Blog 3582

IC617多线程仿真卡死?手把手教你用TigerVNC替换解决ADE XL Explorer问题(附Manjaro/Centos8实测)

本文针对IC617在Manjaro、CentOS 8等高版本Linux系统中运行ADE XL Explorer进行多线程仿真时出现的卡死问题,提供了详细的诊断与解决方案。文章指出问题根源在于软件内置的旧版VNC组件不兼容,并手把手指导用户通过使用TigerVNC替换原组件来彻底解决,附有在Manjaro和CentOS 8系统上的实测步骤与验证方法。

hill8的博客 774

宇树机器狗go2—slam建图(1)点云格式

上一篇番外文章教大家如何在宇树机器狗go2的gazebo仿真环境中实现简单的导航运动,本期文章会教大家如何让宇树的机器狗go2在仿真环境中进行slam建图时经常会遇到的一些点云格式,在后续的slam建图和slam算法解析的时候会经常与这些点云信息打交道。宇树机器狗go2仿真会作为一个长期项目来进行不定期更新,仿真不只限于在gazebo上实现,后面还会在isaac sim等仿真平台上教大家如何搭建,其目的还是帮助各位都能以较低的成本加入到宇树机器狗go2的学习中。

古月居 3271

Build a Large Language Model (From Scratch)-appendix A-Introduction to PyTorch

本附录旨在为您提供将深度学习应用于实践并从头开始实现大型语言模型(LLM)所需的技能和知识。PyTorch 是一个流行的基于 Python 的深度学习库,它将是本书使用的主要工具。我将指导您设置一个配备 PyTorch 和 GPU 支持的深度学习工作环境。然后,你将学习张量的基本概念及其在 PyTorch 中的应用。我们还将深入探讨 PyTorch 的自动微分引擎,该功能使我们能够便捷、高效地使用反向传播,而反向传播是神经网络训练的关键环节。本附录旨在为刚接触PyTorch深度学习的读者提供入门指南。尽管它

jsdoulaoula的博客 1227

Python控制LitePoint IQxel-MW 无线网络测试仪

由于项目需要进行WIFI和BT(蓝牙)的射频测试,所以需要开发一款支持WIFI/BT射频测试的工具。开发射频测试工具的话那肯定离不开仪表的控制。我们项目用的就Litepoint的IQxel-MW无线网络测试仪。这篇文章主要就是介绍一下如何控制仪表以及实现的过程!LitePoint是美国硅谷的一家仪器厂商,主要做一些无线通讯测试仪表,包括WIFI,BT(Bluetooth),LTE等等。

xgh1951的博客 1万+

torch_vision(一):数据增强和转换模块torchvision.transforms

torchvision包含了很多通用的数据集,模型架构,以及图像转换方法,配合pytorch使用更好搭建训练模型。

tony365的博客 2928

LangChain4j + MCP:从工具协议到生产级 Agent

这两年,很多团队都已经把「大模型问答」接入到系统里了:前端一个输入框,后端调一下 OpenAI / DeepSeek / 本地模型,返回一段回答——这类 「简单问答型」AI 功能它只能说,不会做:不会主动查数据库,不会调用你的接口,不会帮你真正执行脚本;面对复杂一点的需求,比如「帮我生成这个报表的 SQL 并执行一下」,普通 ChatGPT 式的问答就开始力不从心了。而Agent 智能体想解决的,就是这件事:不只是回答你「怎么做」,而是能自己思考、自己决定要不要用工具、再用工具把事做完。

OFFTime_we的博客 1152

【网络基础2】路由器的 “两扇门”:二层接口和三层接口到底有啥不一样?

家里的路由器背后总有几个网线接口,有的标着 “LAN”,有的标着 “WAN”;公司机房的路由器上,接口更是五花八门,有的插着网线,有的连着光纤,旁边还贴着 “GE0/0/1”“Eth-Trunk1” 这样的标签。你可能会想:不就是插网线的地方吗?有啥区别?其实,这些接口分 “二层接口” 和 “三层接口”,它们的作用差得远了 —— 就像你家的门,有的是 “小区内的单元门”(只通小区内部),有的是 “小区的大门”(能通往外面的世界)。接下来,咱们用大白话 + 生活例子,一点点把这两种接口讲透。

jundao1997的专栏 565

神经网络数据增强transforms的相关操作(持续更新)

transforms的相关操作(Pytorch)一、图像的相关变化1、格式转换(1)transforms.ToTensor()(2)transforms.ToPILImage()1、图像大小(1) 一、图像的相关变化 1、格式转换 (1)transforms.ToTensor() 可将PIL格式、数组格式转换为tensor格式 img_path = "E:\expression_recognition\\2.jpg" img = Image.open(img_path) # #数组类型PIL类型都可 a1

hjkdh的博客 1万+

解读 2025《高质量数据集 质量评测规范》

《高质量数据集质量评测规范》为2025年数据质量评估提供标准化框架,适用于政府部门、AI企业、数据服务商等行业主体。规范以"说明文档-数据质量-模型应用"三维体系为核心:明确定义高质量数据集分类,细化各项指标要求(包括文档完整性、数据规范性、应用多样性等),并提供具体评分细则(百分制,90分达标)和计算方法。附录补充多模态数据处理细则,旨在建立可操作的质量评估标准,保障优质数据供给流通。

cdfunlove的博客 1883

图像分类训练技巧之数据增强篇

转自:https://zhuanlan.zhihu.com/p/430563265 一个模型的性能除了和网络结构本身有关,还非常依赖具体的训练策略,比如优化器,数据增强以及正则化策略等(当然也很训练数据强相关,训练数据量往往决定模型性能的上线)。近年来,图像分类模型在ImageNet数据集的top1 acc已经由原来的56.5(AlexNet,2012)提升至90.88(CoAtNet,2021,用了额外的数据集JFT-3B),这进步除了主要归功于模型,算力和数据的提升,也与训练策略的提升紧密相关。最近刚

sinat_16423171的博客 3588

【深度学习时间序列预测案例】零基础入门经典深度学习时间序列预测项目实战(附代码+数据集+原理介绍)

本专栏整理了《深度学习时间序列预测案例》,内包含了各种不同的基于深度学习模型的时间序列预测方法,例如LSTM、GRU、CNN(一维卷积、二维卷积)、LSTM-CNN、BiLSTM、Self-Attention、LSTM-Attention、Transformer等经典模型,包含项目原理以及源码,每一个项目实例都附带有完整的代码+数据集。

优快云 精品推荐 4万+

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

玩转pytorch中的torchvision.transforms

文章作者:Tyan 博客:noahsnail.com  |  优快云  |  简书 0. 运行环境 python 3.6.8, pytorch 1.5.0 1. torchvision.transforms 在深度学习中,计算机视觉(CV)是其中的一大方向,而在CV任务中,图像变换(Image Transform)通常是必不可少的一环,其可以用来对图像进行预处理,数据增强等。本文主要整理PyTorch中torchvision.transforms提供的一些功能(代码

SnailTyan 5138

深度学习工具包 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】2.3 transforms图像增强(一)

任务简介: pytorch提供了大量的transforms预处理方法,在这里归纳总结为四大类共二十二种方法进行一 一学习;学会自定义transforms方法以兼容实际项目; 详细说明: 本节将介绍张量的基本操作,如张量拼接切分、索引和变换,同时学习张量的数学运算,并基于所学习的知识,实现线性回归模型的训练,以加深知识点的认识。 本节第二部分介绍pytorch最大的特性——动态图机制,动态图机制是pytorch与tensorflow最大的区别,该部分首先介绍计算图的概念,并通过演示动态图与静态图的搭建

尊新必威的博客 1281

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

transforms数据预处理方法(一)

transform 数据预处理方法

weixin_43584866的博客 5171

[Task 3]【#DataWhale #AI 夏令营】【kaggle — CV图像】

机器学习、深度学习、数据增强

butaiqingxing的博客 2157

秃姐学AI系列之:数据增广 + 代码实现

图像增广基于现有的训练数据生成随机图像,来提高模型的泛化能力。为了在预测过程中得到确切的结果,我们通常对训练样本只进行图像增广,而在预测过程中不使用带随机操作的图像增广。深度学习框架提供了许多不同的图像增广方法,这些方法可以被同时应用。常见的图片增广包括反转、切割、变色。

m0_62415132的博客 1059

torchvision.transforms的图像增强

随机裁剪和缩放图像。它将图像随机裁剪为指定的大小(这里是512x512),并且可以根据给定的比例范围进行缩放。将图像以随机角度旋转,这里的参数45表示随机旋转的角度范围为-45度到+45度。该操作通过随机调整图像的亮度、对比度、饱和度和色调来增加图像的变化。该操作可以进行随机旋转、平移、缩放和剪切图像。:随机水平翻转图像。以0.5的概率随机选择是否对图像进行水平翻转。:随机垂直翻转图像。以0.5的概率随机选择是否对图像进行垂直翻转。表示将图像在0.8倍到1.0倍之间进行缩放。这个操作没有使用额外的参数。

qq_26974921的博客 755

20、日光化 transforms.RandomSolarize(threshold, p=0.5)

transforms.RandomSolarize(threshold, p=0.5) 通过反转阈值以上的所有像素值,以给定的概率随机对图像进行日光化 import torchvision.transforms as transform from PIL import Image import matplotlib.pyplot as plt import numpy as np import torch img0=Image.open('lin-xiao-xun-000003.jpg') img1=t

lichaoqi1的博客 1177

【计算机视觉】Image Data Augmentation算法介绍合集(一)

【计算机视觉】Image Data Augmentation算法介绍合集(一)

wzk4869的博客 1050

19、随机后处理 transforms.RandomPosterize(bits, p=0.5)

transforms.RandomPosterize(bits, p=0.5) 通过减少每个颜色通道的位数,以给定的概率随机对图像进行后处理。 bits :每个通道要保留的位数(0- import torchvision.transforms as transform from PIL import Image import matplotlib.pyplot as plt import numpy as np import torch img0=Image.open('lin-xiao-xun-0000

lichaoqi1的博客 884

23、随机均衡器 transforms.RandomEqualize(p=0.5)

transforms.RandomInvert(p=0.5) import torchvision.transforms as transform from PIL import Image import matplotlib.pyplot as plt import numpy as np import torch img0=Image.open('lin-xiao-xun-000003.jpg') img1=transform.RandomInvert(p=0.8)(img0) axs = plt.f

lichaoqi1的博客 913

【从零学习PyTorch】 transfrom之三种旋转翻转的方法(Flip and Rotation)

RandomHorizontalFlip() class torchvision.transforms.RandomHorizontalFlip(p=0.5) 功能:依据概率p对PIL图片进行水平翻转,p默认0.5 RandomVerticalFlip() class torchvision.transforms.RandomVerticalFlip() **功能:**按照概率p对PIL图片...

忽逢桃林的博客 9481
上一篇: 优快云文章如何迁移至微信公众号
下一篇: Pytorch学习之LSTM识别MNIST数据集
元宇宙MetaAI
博客等级 码龄10年 331粉丝 333原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值