当前位置: 首页 > news >正文

【深度学习】Pytorch基础

张量

  • 运算与操作
  1. 加减乘除
    pytorch中tensor运算逐元素进行,或者一一对应计算

  2. 常用操作
    典型维度为N X C X H X W,N为图像张数,C为图像通道数,HW为图高宽。

  • sum()
    一般,指定维度,且keepdim=True该维度上元素相加,长度变为1。
  • 升降维度
    unsqueeze() 扩充维度
    image = PIL.Image.open('lena.jpg').convert('RGB')transform = torchvision.tranforms.Compose([torchvision.transforms.ToTensor()])img = transform(image)img = img.unsqueeze(0)

sequeeze()将长度为1的维度抹除,数据不会减少。

  • 将输入(图像)转换为张量,torchvision.transforms.ToTensor()
class ToTensor:"""Convert a ``PIL Image`` or ``numpy.ndarray`` to tensor. This transform does not support torchscript.
  • tensor转换为cvMat
  1. 获得元素
  2. 反归一化
  3. 变换通道顺序
  • 维度展开
    # 除第1维,其他维展开x = torch.flatten(x, 1)

Variable

view()方法
卷积输出N*C*H*W,输入全连接层,需要变形为N*size

torchvision

import torchvision as tv
# 查看网络的结构
features = tv.models.alexnet().features
# 在dim=1上求和,第1维度压缩为1
torch.sum(in_feat**2,dim=1,keepdim=True)

torch.nn

  1. Module
    用于构建神经网络模型的基类,有方法
    register_bufferregister_parameter,声明常量与模型参数。
  2. ModuleList
  3. train()与eval()
  4. ConvTranspose2d 图像反卷积,可实现上采样,如ConvTranspose2d(256, 128, 3, 2, 1, 1), 输入输出通道分别为256\128,反卷积核大小为3,反卷积的stride为2,即图像大小变为2倍,输出尺寸公式是卷积公式的逆运算;与卷积参数一致,形式即正逆。

H o u t = ( H i n − 1 ) × stride [ 0 ] − 2 × padding [ 0 ] + dilation [ 0 ] × ( kernel_size [ 0 ] − 1 ) + output_padding [ 0 ] + 1 H_{out} = (H_{in} - 1) \times \text{stride}[0] - 2 \times \text{padding}[0] + \text{dilation}[0] \times (\text{kernel\_size}[0] - 1) + \text{output\_padding}[0] + 1 Hout=(Hin1)×stride[0]2×padding[0]+dilation[0]×(kernel_size[0]1)+output_padding[0]+1

  1. 模型参数
    for key in list(para_task.keys()):para_task[key.replace('module.', '')] = para_task.pop(key)

数据集的输入与处理

对图像预处理:https://pytorch.org/vision/stable/transforms.html
transforms.Compose()设置图像预处理模式组合,例如

train_transforms = transforms.Compose(# [transforms.RandomCrop(args.patch_size), transforms.ToTensor()]# [transforms.ToTensor(),]# 图像中心裁剪边长为256像素[transforms.CenterCrop(256), transforms.ToTensor(),])
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
# 含义为把PIL图像转换为tensor格式,
train_dataset = datasets.MNIST(root='data/',train=True,transform=transforms.Compose([transforms.ToTensor(),]),download=True)
test_dataset = datasets.MNIST(root='data/',train=False,transform=transforms.Compose([transforms.ToTensor(),]),download=True)
train_loader = DataLoader(dataset=train_dataset, batch_size=100, shuffle=True)
test_loader = DataLoader(dataset=test_dataset, batch_size=100, shuffle=True)

神经网络模型的构建与训练

import torch
import torchvision
from torch.autograd import Variable# 构建网络
class Model(torch.nn.Module):def __init__(self):super(Model, self).__init__()self.conv = torch.nn.Sequential(torch.nn.Conv2d(1, 64, 3, 1, 1),torch.nn.ReLU(),torch.nn.Conv2d(64, 128, 3, 1, 1),torch.nn.ReLU(),torch.nn.MaxPool2d(2, 2),)self.dense = torch.nn.Sequential(torch.nn.Linear(14 * 14 * 128, 1024),torch.nn.ReLU(),torch.nn.Dropout(p=0.5),torch.nn.Linear(1024, 10),)def forward(self, x):x = self.conv(x)x = x.view(-1, 14 * 14 * 128)x = self.dense(x)return x
# device
device = torch.device("cuda")
# 声明待训练的模型和优化方法
model = Model().to(device)
cost = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters())
# N epoch 训练
for epoch in range(epochs):sum_loss = 0.0train_correct = 0for data in train_loader:inputs, labels = datainputs, labels = Variable(inputs).cuda(), Variable(labels).cuda()optimizer.zero_grad()outputs = model(inputs)loss = cost(outputs, labels)loss.backward()optimizer.step()

通过pytorch.nn.module、torchvision构建的网络模型是否训练

if requires_grad: #需要训练时,设为真for para in <torch.nn.module 对象>.parameters():para.requires_grad = True

torch.nn.module的子类对象,如下可添加网络层数

nn.layers = nn.ModuleList()

然后把网络模型参数作为训练的优化参数

class Trainer:def __init__(self):self.parameters = list(<net>.parameters())self.lr = 1e-3self.optimizer_net = torch.optim.Adam(self.parameters,lr = self.lr)

池化

# power-2 pool of square window of size=3, stride=2
nn.LPPool2d(2, 3, stride=2)class L2pooling(nn.Module):def __init__(self, filter_size=5, stride=2, channels=None, pad_off=0):super(L2pooling, self).__init__()self.padding = (filter_size - 2) // 2self.stride = strideself.channels = channelsa = np.hanning(filter_size)[1:-1]g = torch.Tensor(a[:, None] * a[None, :])g = g / torch.sum(g)# pdb.set_trace()self.register_buffer("filter", g[None, None, :, :].repeat((self.channels, 1, 1, 1)))def forward(self, input):input = input ** 2out = F.conv2d(input,self.filter,stride=self.stride,padding=self.padding,groups=input.shape[1],)return (out + 1e-12).sqrt()

错误

  1. 分类标签有9类,在构建数据集的标签时写为1~9,运行时错误,将标签-1解错。
  2. 使用list错误,pytorch无法构造tensor。
    TypeError: Variable data has to be a tensor, but got list
    label = np.zeros(10, dtype=np.float32)
  3. numpy中float是双精度,pytorch变量均为单精度。
  4. pytorch transform必须放在Dataset对象,且库为
torchvision.transforms.Compose([torchvision.transforms.ToTensor(),  torchvision.transforms.RandomCrop((506, 606))])
  1. File “/home/zpk/CompressAI/iqa_models.py”, line 220, in forward
    dist_s += (self.alpha0 * self.structure(mu0a, mu0b)
    RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu!
    程序参数 忘记加–cuda,导致训练数据是在cpu上。

  2. RuntimeError: grad can be implicitly created only for scalar outputs
    模型输出取mean()。

COCO数据集训练

使用fiftyone库实现训练。

fiftyone下载数据集在/home//fiftyone,

fiftyone/coco-2017
├── info.json
├── raw
│   ├── captions_train2017.json
│   ├── captions_val2017.json
│   ├── instances_train2017.json
│   ├── instances_val2017.json
│   ├── person_keypoints_train2017.json
│   └── person_keypoints_val2017.json
├── train
│   ├── data -> /home/zpk/Data/coco_real/train2017
│   └── labels.json
└── validation├── data -> /home/zpk/Data/coco_real/val2017└── labels.json
import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F
class FiftyOneTorchDataset(torch.utils.data.Dataset):"""A class to construct a PyTorch dataset from a FiftyOne dataset.Args:fiftyone_dataset: a FiftyOne dataset or view that will be used for training or testingtransforms (None): a list of PyTorch transforms to apply to images and targets when loadinggt_field ("ground_truth"): the name of the field in fiftyone_dataset that contains the desired labels to loadclasses (None): a list of class strings that are used to define the mapping betweenclass names and indices. If None, it will use all classes present in the given fiftyone_dataset."""def __init__(self,fiftyone_dataset,transforms=None,gt_field="ground_truth",classes=None,):self.samples = fiftyone_datasetself.transforms = transformsself.gt_field = gt_fieldself.img_paths = self.samples.values("filepath")self.classes = classesif not self.classes:# Get list of distinct labels that exist in the viewself.classes = self.samples.distinct("%s.detections.label" % gt_field)if self.classes[0] != "background":self.classes = ["background"] + self.classesself.labels_map_rev = {c: i for i, c in enumerate(self.classes)}def __getitem__(self, idx):img_path = self.img_paths[idx]sample = self.samples[img_path]metadata = sample.metadataimg = Image.open(img_path).convert("RGB")boxes = []labels = []area = []iscrowd = []detections = sample[self.gt_field].detectionsfor det in detections:category_id = self.labels_map_rev[det.label]coco_obj = fouc.COCOObject.from_label(det, metadata, category_id=category_id,)x, y, w, h = coco_obj.bboxboxes.append([x, y, x + w, y + h])labels.append(coco_obj.category_id)area.append(coco_obj.area)iscrowd.append(coco_obj.iscrowd)target = {}target["boxes"] = torch.as_tensor(boxes, dtype=torch.float32)target["labels"] = torch.as_tensor(labels, dtype=torch.int64)target["image_id"] = torch.as_tensor([idx])target["area"] = torch.as_tensor(area, dtype=torch.float32)target["iscrowd"] = torch.as_tensor(iscrowd, dtype=torch.int64)if self.transforms is not None:img, target = self.transforms(img, target)return img, targetdef __len__(self):return len(self.img_paths)def get_classes(self):return self.classes
fo_dataset = foz.load_zoo_dataset("coco-2017", split = "train")
dataset_dir = "/path/to/coco-2017"
# The type of the dataset being imported
dataset_type = fo.types.COCODetectionDataset  # for example
dataset = fo.Dataset.from_dir(dataset_dir=dataset_dir,dataset_type=dataset_type,name=name,
)
valid_view = fo_dataset.match(F("ground_truth.detections").length() > 1)
torch_dataset = FiftyOneTorchDataset(valid_view)

相关文章:

【深度学习】Pytorch基础

张量 运算与操作 加减乘除 pytorch中tensor运算逐元素进行&#xff0c;或者一一对应计算 常用操作 典型维度为N X C X H X W&#xff0c;N为图像张数&#xff0c;C为图像通道数&#xff0c;HW为图高宽。 sum() 一般&#xff0c;指定维度&#xff0c;且keepdimTrue该维度上元…...

C++模拟揭秘刘谦魔术,领略数学的魅力

新的一年又开始了&#xff0c;大家新年好呀~。在这我想问大家一个问题&#xff0c;有没有同学看了联欢晚会上刘谦的魔术呢&#xff1f; 这个节目还挺有意思的&#xff0c;它最出彩的不是魔术本身&#xff0c;而是小尼老师“念错咒语”而导致他手里的排没有拼在一起&#xff0c;…...

JAVA语言编写一个方法,两个Long参数传入,使用BigDecimal类,计算相除四舍五入保留2位小数返回百分数。

在Java中&#xff0c;你可以使用BigDecimal类来执行精确的浮点数计算&#xff0c;并且可以指定结果的小数位数。以下是一个方法&#xff0c;它接受两个Long类型的参数&#xff0c;并使用BigDecimal来计算它们的商&#xff0c;然后将结果四舍五入到两位小数&#xff0c;并返回一…...

SQL教学:掌握MySQL数据操作核心技能--DML语句基本操作之“增删改查“

大家好&#xff0c;今天我要给大家分享的是SQL-DML语句教学。DML&#xff0c;即Data Manipulation Language&#xff0c;也就是我们常说的"增 删 改 查"&#xff0c;是SQL语言中用于操作数据库中数据的一部分。作为MySQL新手小白&#xff0c;掌握DML语句对于数据库数…...

【性能测试】Jmeter性能压测-阶梯式/波浪式场景总结(详细)

目录&#xff1a;导读 前言一、Python编程入门到精通二、接口自动化项目实战三、Web自动化项目实战四、App自动化项目实战五、一线大厂简历六、测试开发DevOps体系七、常用自动化测试工具八、JMeter性能测试九、总结&#xff08;尾部小惊喜&#xff09; 前言 1、阶梯式场景&am…...

前端面试 跨域理解

2 实现 2-1 JSONP 实现 2-2 nginx 配置 2-2 vue 开发中 webpack自带跨域 2 -3 下载CORS 插件 或 chrome浏览器配置跨域 2-4 通过iframe 如&#xff1a;aaa.com 中读取bbb.com的localStorage 1)在aaa.com的页面中&#xff0c;在页面中嵌入一个src为bbb.com的iframe&#x…...

JetBrains TeamCity 身份验证绕过漏洞复现(CVE-2024-27198)

0x01 产品简介 JetBrains TeamCity是一款由JetBrains开发的持续集成和持续交付(CI/CD)服务器。它提供了一个功能强大的平台,用于自动化构建、测试和部署软件项目。TeamCity旨在简化团队协作和软件交付流程,提高开发团队的效率和产品质量。 0x02 漏洞概述 JetBrains Team…...

设计模式—单例模式

单例模式&#xff08;Singleton Pattern&#xff09;是一种常用的软件设计模式&#xff0c;其核心思想是确保一个类仅有一个实例&#xff0c;并提供一个全局访问点来获取这个实例。单例模式主要用于控制资源的访问&#xff0c;比如配置文件的读取&#xff0c;数据库的连接等&am…...

Android在后台读取UVC摄像头的帧数据流并推送

Android在后台读取UVC摄像头的帧数据流并推送 添加UvcCamera依赖库 使用原版的 saki4510t/UVCCamera 在预览过程中断开可能会闪退&#xff0c;这里使用的是 jiangdongguo/AndroidUSBCamera 中修改的版本&#xff0c;下载到本地即可。 https://github.com/jiangdongguo/AndroidU…...

vue单向数据流介绍

Vue.js 的单向数据流是其核心设计原则之一&#xff0c;也是 Vue 响应式系统的基础。在 Vue.js 中&#xff0c;数据流主要是单向的&#xff0c;从父组件流向子组件。这种设计有助于保持组件之间的清晰通信&#xff0c;减少不必要的复杂性和潜在的错误。 以下是 Vue 单向数据流的…...

OpenMMlab AI实战营第四期培训

OpenMMlab AI实战营第四期培训 OpenMMlab实战营第四次课2023.2.6学习参考一、什么是目标检测1.目标检测下游视觉任务2.图像分类 v.s. 目标检测 二、目标检测实现1.滑窗 Sliding Window2.滑窗的效率问题3.改进思路&#xff08;1&#xff09;消除滑窗中的重复计算&#xff08;2&a…...

React轻松开发平台:实现高效、多变的应用开发范本

在当今快节奏的软件开发环境中&#xff0c;追求高效、灵活的应用开发方式成为了开发团队的迫切需求。React低代码平台崭露头角&#xff0c;为开发人员提供了一种全新的开发范式&#xff0c;让开发过程更高效、更灵活&#xff0c;从而加速应用程序的开发周期和交付速度。 1. 快…...

多域名SSL证书:保护多个网站的安全之选

什么是多域名SSL证书&#xff1f; 多域名SSL证书&#xff0c;顾名思义&#xff0c;是指一张SSL证书可以保护多个域名。与传统的单域名SSL证书相比&#xff0c;多域名SSL证书可以在一个证书中绑定多个域名&#xff0c;无需为每个域名单独购买和安装SSL证书。这样不仅可以节省成…...

HarmonyOS—HAP唯一性校验逻辑

HAP是应用安装的基本单位&#xff0c;在DevEco Studio工程目录中&#xff0c;一个HAP对应一个Module。应用打包时&#xff0c;每个Module生成一个.hap文件。 应用如果包含多个Module&#xff0c;在应用市场上架时&#xff0c;会将多个.hap文件打包成一个.app文件&#xff08;称…...

金三银四,程序员如何备战面试季

金三银四&#xff0c;程序员如何备战面试季 一个人简介二前言三面试技巧分享3.1 自我介绍 四技术问题回答4.1 团队协作经验展示 五职业规划建议5.1 短期目标5.2 中长期目标 六后记 一个人简介 &#x1f3d8;️&#x1f3d8;️个人主页&#xff1a;以山河作礼。 &#x1f396;️…...

VUE3项目学习系列--项目配置(二)

在项目团队开发过程中&#xff0c;多人协同开发为保证项目格式书写格式统一标准化&#xff0c;因此需要进行代码格式化校验&#xff0c;包括在代码编写过程中以及代码提交前进行自动格式化&#xff0c;因此需要进行在项目中进行相关的配置使之代码格式一致。 一、eslint配置 …...

idea:springboot项目搭建

目录 一、创建项目 1、File → New → Project 2、Spring Initializr → Next 3、填写信息 → Next 4、web → Spring Web → Next 5、填写信息 → Finish 6、处理配置不合理内容 7、注意事项 7.1 有依赖包&#xff0c;却显示找不到依赖&#xff0c;刷新一下maven 二…...

如何保证某个程序系统内只运行一个,保证原子性

GetMapping("/startETL") // Idempotent(expireTime 90, info "请勿90秒内连续点击")public R getGaugeTestData6() {log.info("start ETL");//redis设置t_data_load_record 值为2bladeRedis.set("t_data_load_record_type", 2);Str…...

golang常见面试题

1. go语言有哪些优点、特性&#xff1f; 语法简便&#xff0c;容易上手。 支持高并发&#xff0c;go有独特的协程概念&#xff0c;一般语言最小的执行单位是线程&#xff0c;go语言支持多开协程&#xff0c;协程是用户态线程&#xff0c;协程的占用内存更少&#xff0c;协程只…...

探索Python编程世界:从入门到精通

一.Python 从入门到精通 随着计算机科学的发展&#xff0c;编程已经成为了一种必备的技能。而 Python 作为一种简单易学、功能强大的编程语言&#xff0c;越来越受到人们的喜爱。本文将为初学者介绍 Python 编程的基础知识&#xff0c;帮助他们踏入 Python 编程的大门&#xf…...

生成xcframework

打包 XCFramework 的方法 XCFramework 是苹果推出的一种多平台二进制分发格式&#xff0c;可以包含多个架构和平台的代码。打包 XCFramework 通常用于分发库或框架。 使用 Xcode 命令行工具打包 通过 xcodebuild 命令可以打包 XCFramework。确保项目已经配置好需要支持的平台…...

Java 语言特性(面试系列2)

一、SQL 基础 1. 复杂查询 &#xff08;1&#xff09;连接查询&#xff08;JOIN&#xff09; 内连接&#xff08;INNER JOIN&#xff09;&#xff1a;返回两表匹配的记录。 SELECT e.name, d.dept_name FROM employees e INNER JOIN departments d ON e.dept_id d.dept_id; 左…...

在rocky linux 9.5上在线安装 docker

前面是指南&#xff0c;后面是日志 sudo dnf config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo sudo dnf install docker-ce docker-ce-cli containerd.io -y docker version sudo systemctl start docker sudo systemctl status docker …...

解决本地部署 SmolVLM2 大语言模型运行 flash-attn 报错

出现的问题 安装 flash-attn 会一直卡在 build 那一步或者运行报错 解决办法 是因为你安装的 flash-attn 版本没有对应上&#xff0c;所以报错&#xff0c;到 https://github.com/Dao-AILab/flash-attention/releases 下载对应版本&#xff0c;cu、torch、cp 的版本一定要对…...

MySQL中【正则表达式】用法

MySQL 中正则表达式通过 REGEXP 或 RLIKE 操作符实现&#xff08;两者等价&#xff09;&#xff0c;用于在 WHERE 子句中进行复杂的字符串模式匹配。以下是核心用法和示例&#xff1a; 一、基础语法 SELECT column_name FROM table_name WHERE column_name REGEXP pattern; …...

【HarmonyOS 5 开发速记】如何获取用户信息(头像/昵称/手机号)

1.获取 authorizationCode&#xff1a; 2.利用 authorizationCode 获取 accessToken&#xff1a;文档中心 3.获取手机&#xff1a;文档中心 4.获取昵称头像&#xff1a;文档中心 首先创建 request 若要获取手机号&#xff0c;scope必填 phone&#xff0c;permissions 必填 …...

LangChain知识库管理后端接口:数据库操作详解—— 构建本地知识库系统的基础《二》

这段 Python 代码是一个完整的 知识库数据库操作模块&#xff0c;用于对本地知识库系统中的知识库进行增删改查&#xff08;CRUD&#xff09;操作。它基于 SQLAlchemy ORM 框架 和一个自定义的装饰器 with_session 实现数据库会话管理。 &#x1f4d8; 一、整体功能概述 该模块…...

[ACTF2020 新生赛]Include 1(php://filter伪协议)

题目 做法 启动靶机&#xff0c;点进去 点进去 查看URL&#xff0c;有 ?fileflag.php说明存在文件包含&#xff0c;原理是php://filter 协议 当它与包含函数结合时&#xff0c;php://filter流会被当作php文件执行。 用php://filter加编码&#xff0c;能让PHP把文件内容…...

根目录0xa0属性对应的Ntfs!_SCB中的FileObject是什么时候被建立的----NTFS源代码分析--重要

根目录0xa0属性对应的Ntfs!_SCB中的FileObject是什么时候被建立的 第一部分&#xff1a; 0: kd> g Breakpoint 9 hit Ntfs!ReadIndexBuffer: f7173886 55 push ebp 0: kd> kc # 00 Ntfs!ReadIndexBuffer 01 Ntfs!FindFirstIndexEntry 02 Ntfs!NtfsUpda…...

掌握 HTTP 请求:理解 cURL GET 语法

cURL 是一个强大的命令行工具&#xff0c;用于发送 HTTP 请求和与 Web 服务器交互。在 Web 开发和测试中&#xff0c;cURL 经常用于发送 GET 请求来获取服务器资源。本文将详细介绍 cURL GET 请求的语法和使用方法。 一、cURL 基本概念 cURL 是 "Client URL" 的缩写…...