pytorch实现猴痘病识别

news2024/11/25 11:53:47
  •  🍨 本文为🔗365天深度学习训练营 中的学习记录博客
  • 🍦 参考文章地址: 365天深度学习训练营-第P4周:猴痘病识别
  • 🍖 作者:K同学啊

一、前期准备

1.设置GPU

import torch
from torch import nn
import torchvision
from torchvision import transforms,datasets,models
import matplotlib.pyplot as plt
import os,PIL,pathlib
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
device
device(type='cuda')

2.导入数据

data_dir = './houdou/'
data_dir = pathlib.Path(data_dir)

data_paths = list(data_dir.glob('*'))
classNames = [str(path).split('\\')[1] for path in data_paths]
classNames
train_transforms = transforms.Compose([
    transforms.Resize([224,224]),# resize输入图片
    transforms.ToTensor(), # 将PIL Image或numpy.ndarray转换成tensor
    transforms.Normalize(
        mean = [0.485, 0.456, 0.406],
        std = [0.229,0.224,0.225]) # 从数据集中随机抽样计算得到
])

total_data = datasets.ImageFolder(data_dir,transform=train_transforms)
total_data
Dataset ImageFolder
    Number of datapoints: 2142
    Root location: houdou
    StandardTransform
Transform: Compose(
               Resize(size=[224, 224], interpolation=PIL.Image.BILINEAR)
               ToTensor()
               Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
           )

3.数据集划分

train_size = int(0.8*len(total_data))
test_size = len(total_data) - train_size
train_dataset, test_dataset = torch.utils.data.random_split(total_data,[train_size,test_size])
train_size,test_size
(1713, 429)
batch_size = 32
train_dl = torch.utils.data.DataLoader(train_dataset,
                                       batch_size=batch_size,
                                       shuffle=True,
                                       num_workers=1)
test_dl = torch.utils.data.DataLoader(test_dataset,
                                       batch_size=batch_size,
                                       shuffle=True,
                                       num_workers=1)

4.数据可视化

imgs, labels = next(iter(train_dl))
imgs.shape

torch.Size([32, 3, 224, 224])

import numpy as np

 # 指定图片大小,图像大小为20宽、5高的绘图(单位为英寸inch)
plt.figure(figsize=(20, 5)) 
for i, imgs in enumerate(imgs[:20]):
    npimg = imgs.numpy().transpose((1,2,0))
    npimg = npimg * np.array((0.229, 0.224, 0.225)) + np.array((0.485, 0.456, 0.406))
    npimg = npimg.clip(0, 1)
    # 将整个figure分成2行10列,绘制第i+1个子图。
    plt.subplot(2, 10, i+1)
    plt.imshow(npimg)
    plt.axis('off')

for X,y in test_dl:
    print('Shape of X [N, C, H, W]:', X.shape)
    print('Shape of y:', y.shape)
    break
Shape of X [N, C, H, W]: torch.Size([32, 3, 224, 224])
Shape of y: torch.Size([32])

二、构建简单的CNN网络

# import torch.nn.functional as F

# num_classes = 4  # 图片的类别数

# class Network_bn(nn.Module):
#      def __init__(self):
#         super().__init__()
#          # 特征提取网络
#         self.conv1 = nn.Conv2d(in_channels=3, out_channels=12, kernel_size=5, stride=1, padding=0) 
#         self.bn1 = nn.BatchNorm2d(12)                
#         self.conv2 = nn.Conv2d(in_channels=12, out_channels=12, kernel_size=5, stride=1, padding=0) 
#         self.bn2 = nn.BatchNorm2d(12)
#         self.pool = nn.MaxPool2d(2,2)
#         self.conv3 = nn.Conv2d(in_channels=12, out_channels=24, kernel_size=5, stride=1, padding=0)
#         self.bn3 = nn.BatchNorm2d(24) 
#         self.conv4 = nn.Conv2d(in_channels=24, out_channels=24, kernel_size=5, stride=1, padding=0)
#         self.bn4 = nn.BatchNorm2d(24)  
#         # 分类网络
#         self.fc1 = nn.Linear(24*50*50,num_classes)
#      # 前向传播
#      def forward(self, x):
#         x = F.relu(self.bn1(self.conv1(x)))
#         x = F.relu(self.bn2(self.conv2(x)))
#         x = self.pool(x)
#         x = F.relu(self.bn3(self.conv3(x)))
#         x = F.relu(self.bn4(self.conv4(x)))
#         x = self.pool(x)
#         x = x.view(-1,24*50*50)
#         x = self.fc1(x)
       
#         return x
    
# model = Network_bn().to(device)
# model

2.1 迁移学习

2.1.1 调用resnet18预训练模型、冻结参数 

feature_extract = True

# 冻结参数
def set_parameter_requires_grad(model, feature_extracting):
    if feature_extracting:
        for param in model.parameters():
            param.requires_grad = False


# 修改输出层
def initialize_model(num_classes, feature_extract, use_pretrained=True):
    
    model_ft = models.resnet18(pretrained=use_pretrained)
    set_parameter_requires_grad(model_ft, feature_extract)
    
    num_ftrs = model_ft.fc.in_features
    model_ft.fc = nn.Linear(num_ftrs, num_classes)
                            
    input_size = 32

    return model_ft, input_size
model_ft, input_size = initialize_model(2, feature_extract, use_pretrained=True)
model_ft = model_ft.to(device)
model_ft

2.1.2 取出输出层参数 

取出输出层参数  后面用于训练更新 

# 设置训练哪些层
params_to_update = model_ft.parameters()
print("Params to learn:")
if feature_extract: # 自己只训练输出层
    params_to_update = []
    for name,param in model_ft.named_parameters():
        if param.requires_grad == True:
            params_to_update.append(param)
            print("\t",name)
else:
    for name,param in model_ft.named_parameters():
        if param.requires_grad == True:
            print("\t",name)
Params to learn:
	 fc.weight
	 fc.bias

三、训练模型

3.1 设置超参数

动态学习率 

# 优化器设置
optimizer = torch.optim.Adam(params_to_update, lr=1e-4)#要训练啥参数,你来定
scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=5, gamma=0.92)#学习率每7个epoch衰减成原来的1/10
loss_fn = nn.CrossEntropyLoss()
# def adjust_learning_rate(optimizer, epoch, start_lr):
#     # 每2个 epoch衰减到原来的0.98
#     lr = start_lr * (0.92 ** (epoch //2))
#     for param_group in optimizer.param_groups:
#         param_group['lr'] = lr
        
# optimizer = torch.optim.Adam(params_to_update,lr=1e-4)

3.2 编写训练函数

# 训练循环
def train(dataloader, model, loss_fn, optimizer):
    size = len(dataloader.dataset)  # 训练集的大小,一共900张图片
    num_batches = len(dataloader)   # 批次数目,29(900/32)

    train_loss, train_acc = 0, 0  # 初始化训练损失和正确率
    
    for X, y in dataloader:  # 获取图片及其标签
        X, y = X.to(device), y.to(device)
        
        # 计算预测误差
        pred = model(X)          # 网络输出
        loss = loss_fn(pred, y)  # 计算网络输出和真实值之间的差距,targets为真实值,计算二者差值即为损失
        
        # 反向传播
        optimizer.zero_grad()  # grad属性归零
        loss.backward()        # 反向传播
        optimizer.step()       # 每一步自动更新
        
        # 记录acc与loss
        train_acc  += (pred.argmax(1) == y).type(torch.float).sum().item()
        train_loss += loss.item()
            
    train_acc  /= size
    train_loss /= num_batches

    return train_acc, train_loss

3.3 编写测试函数

def test (dataloader, model, loss_fn):
    size        = len(dataloader.dataset)  # 测试集的大小,一共10000张图片
    num_batches = len(dataloader)          # 批次数目,8(255/32=8,向上取整)
    test_loss, test_acc = 0, 0
    
    # 当不进行训练时,停止梯度更新,节省计算内存消耗
    with torch.no_grad():
        for imgs, target in dataloader:
            imgs, target = imgs.to(device), target.to(device)
            
            # 计算loss
            target_pred = model(imgs)
            loss        = loss_fn(target_pred, target)
            
            test_loss += loss.item()
            test_acc  += (target_pred.argmax(1) == target).type(torch.float).sum().item()

    test_acc  /= size
    test_loss /= num_batches

    return test_acc, test_loss

3.4 正式训练

3.4.1 训练输出层

epochs     = 20
train_loss = []
train_acc  = []
test_loss  = []
test_acc   = []
best_acc = 0

for epoch in range(epochs):
    model_ft.train()
    epoch_train_acc, epoch_train_loss = train(train_dl, model_ft, loss_fn, optimizer)
    
    scheduler.step()#学习率衰减
    
    model_ft.eval()
    epoch_test_acc, epoch_test_loss = test(test_dl, model_ft, loss_fn)
    
    # 保存最优模型
    if epoch_test_acc > best_acc:
        best_acc = epoch_train_acc
        state = {
            'state_dict': model_ft.state_dict(),#字典里key就是各层的名字,值就是训练好的权重
            'best_acc': best_acc,
            'optimizer' : optimizer.state_dict(),
        }
        torch.save(state, filename)
        
        
    train_acc.append(epoch_train_acc)
    train_loss.append(epoch_train_loss)
    test_acc.append(epoch_test_acc)
    test_loss.append(epoch_test_loss)
    
    template = ('Epoch:{:2d}, Train_acc:{:.1f}%, Train_loss:{:.3f}, Test_acc:{:.1f}%,Test_loss:{:.3f}')
    print(template.format(epoch+1, epoch_train_acc*100, epoch_train_loss, epoch_test_acc*100, epoch_test_loss))
print('Done')
print('best_acc:',best_acc)
Epoch: 1, Train_acc:54.6%, Train_loss:0.707, Test_acc:54.8%,Test_loss:0.677
Epoch: 2, Train_acc:61.2%, Train_loss:0.648, Test_acc:64.8%,Test_loss:0.637
Epoch: 3, Train_acc:67.3%, Train_loss:0.615, Test_acc:67.8%,Test_loss:0.603
Epoch: 4, Train_acc:70.5%, Train_loss:0.589, Test_acc:72.5%,Test_loss:0.583
Epoch: 5, Train_acc:73.6%, Train_loss:0.567, Test_acc:75.8%,Test_loss:0.554
Epoch: 6, Train_acc:75.0%, Train_loss:0.544, Test_acc:77.2%,Test_loss:0.561
Epoch: 7, Train_acc:76.7%, Train_loss:0.530, Test_acc:80.0%,Test_loss:0.528
Epoch: 8, Train_acc:78.4%, Train_loss:0.517, Test_acc:80.4%,Test_loss:0.510
Epoch: 9, Train_acc:78.5%, Train_loss:0.503, Test_acc:80.0%,Test_loss:0.503
Epoch:10, Train_acc:78.8%, Train_loss:0.499, Test_acc:81.6%,Test_loss:0.492
Epoch:11, Train_acc:80.2%, Train_loss:0.488, Test_acc:81.8%,Test_loss:0.477
Epoch:12, Train_acc:79.7%, Train_loss:0.478, Test_acc:81.1%,Test_loss:0.477
Epoch:13, Train_acc:81.7%, Train_loss:0.471, Test_acc:82.1%,Test_loss:0.468
Epoch:14, Train_acc:81.4%, Train_loss:0.460, Test_acc:82.8%,Test_loss:0.462
Epoch:15, Train_acc:81.7%, Train_loss:0.459, Test_acc:82.8%,Test_loss:0.454
Epoch:16, Train_acc:81.3%, Train_loss:0.455, Test_acc:82.8%,Test_loss:0.440
Epoch:17, Train_acc:82.7%, Train_loss:0.447, Test_acc:83.7%,Test_loss:0.440
Epoch:18, Train_acc:82.2%, Train_loss:0.449, Test_acc:82.1%,Test_loss:0.435
Epoch:19, Train_acc:83.1%, Train_loss:0.433, Test_acc:83.2%,Test_loss:0.439
Epoch:20, Train_acc:82.9%, Train_loss:0.432, Test_acc:82.5%,Test_loss:0.430
Done

3.4.2 训练所有层

for param in model_ft.parameters():
    param.requires_grad = True

# 再继续训练所有的参数,学习率调小一点
optimizer = torch.optim.Adam(model_ft.parameters(), lr=1e-4)
scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=5, gamma=0.92)

# 损失函数
criterion = nn.CrossEntropyLoss()
# 加载之前训练好的权重参数
checkpoint = torch.load(filename)
best_acc = checkpoint['best_acc']
model_ft.load_state_dict(checkpoint['state_dict'])
epochs     = 20
train_loss = []
train_acc  = []
test_loss  = []
test_acc   = []
best_acc = 0

for epoch in range(epochs):
    model_ft.train()
    epoch_train_acc, epoch_train_loss = train(train_dl, model_ft, loss_fn, optimizer)
    
    scheduler.step()#学习率衰减
    
    model_ft.eval()
    epoch_test_acc, epoch_test_loss = test(test_dl, model_ft, loss_fn)
    
    # 保存最优模型
    if epoch_test_acc > best_acc:
        best_acc = epoch_train_acc
        state = {
            'state_dict': model_ft.state_dict(),#字典里key就是各层的名字,值就是训练好的权重
            'best_acc': best_acc,
            'optimizer' : optimizer.state_dict(),
        }
        torch.save(state, filename)
        
        
    train_acc.append(epoch_train_acc)
    train_loss.append(epoch_train_loss)
    test_acc.append(epoch_test_acc)
    test_loss.append(epoch_test_loss)
    
    template = ('Epoch:{:2d}, Train_acc:{:.1f}%, Train_loss:{:.3f}, Test_acc:{:.1f}%,Test_loss:{:.3f}')
    print(template.format(epoch+1, epoch_train_acc*100, epoch_train_loss, epoch_test_acc*100, epoch_test_loss))
print('Done')
print('best_acc:',best_acc)
Epoch: 1, Train_acc:90.7%, Train_loss:0.229, Test_acc:93.0%,Test_loss:0.171
Epoch: 2, Train_acc:97.7%, Train_loss:0.067, Test_acc:96.7%,Test_loss:0.097
Epoch: 3, Train_acc:98.1%, Train_loss:0.052, Test_acc:95.3%,Test_loss:0.142
Epoch: 4, Train_acc:99.4%, Train_loss:0.024, Test_acc:97.0%,Test_loss:0.078
Epoch: 5, Train_acc:99.2%, Train_loss:0.026, Test_acc:97.4%,Test_loss:0.077
Epoch: 6, Train_acc:99.8%, Train_loss:0.009, Test_acc:97.2%,Test_loss:0.085
Epoch: 7, Train_acc:99.7%, Train_loss:0.014, Test_acc:97.0%,Test_loss:0.114
Epoch: 8, Train_acc:99.8%, Train_loss:0.006, Test_acc:97.4%,Test_loss:0.070
Epoch: 9, Train_acc:99.6%, Train_loss:0.011, Test_acc:97.4%,Test_loss:0.080
Epoch:10, Train_acc:99.5%, Train_loss:0.014, Test_acc:95.3%,Test_loss:0.145
Epoch:11, Train_acc:99.6%, Train_loss:0.012, Test_acc:95.8%,Test_loss:0.145
Epoch:12, Train_acc:99.6%, Train_loss:0.010, Test_acc:97.2%,Test_loss:0.081
Epoch:13, Train_acc:99.8%, Train_loss:0.008, Test_acc:96.3%,Test_loss:0.131
Epoch:14, Train_acc:99.8%, Train_loss:0.005, Test_acc:96.0%,Test_loss:0.106
Epoch:15, Train_acc:100.0%, Train_loss:0.002, Test_acc:96.5%,Test_loss:0.099
Epoch:16, Train_acc:99.9%, Train_loss:0.002, Test_acc:96.3%,Test_loss:0.105
Epoch:17, Train_acc:100.0%, Train_loss:0.001, Test_acc:97.0%,Test_loss:0.085
Epoch:18, Train_acc:100.0%, Train_loss:0.001, Test_acc:96.7%,Test_loss:0.105
Epoch:19, Train_acc:100.0%, Train_loss:0.001, Test_acc:97.0%,Test_loss:0.097
Epoch:20, Train_acc:99.9%, Train_loss:0.002, Test_acc:97.4%,Test_loss:0.077
Done

四、结果可视化

加载训练好的模型

model_ft, input_size = initialize_model(2, feature_extract, use_pretrained=True)

# GPU模式
model_ft = model_ft.to(device)

# 保存文件的名字
filename='best.pt'

# 加载模型
checkpoint = torch.load(filename)
best_acc = checkpoint['best_acc']
model_ft.load_state_dict(checkpoint['state_dict'])

结果可视化

import matplotlib.pyplot as plt
#隐藏警告
import warnings
warnings.filterwarnings("ignore")               #忽略警告信息
plt.rcParams['font.sans-serif']    = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False      # 用来正常显示负号
plt.rcParams['figure.dpi']         = 100        #分辨率

epochs_range = range(epochs)

plt.figure(figsize=(12, 3))
plt.subplot(1, 2, 1)

plt.plot(epochs_range, train_acc, label='Training Accuracy')
plt.plot(epochs_range, test_acc, label='Test Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')

plt.subplot(1, 2, 2)
plt.plot(epochs_range, train_loss, label='Training Loss')
plt.plot(epochs_range, test_loss, label='Test Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()

测试模型

train_on_gpu = True

# 得到一个batch的测试数据
imgs, labels = next(iter(train_dl))

# 进行预测
model_ft.eval()

if train_on_gpu:
    output = model_ft(imgs.cuda())
else:
    output = model_ft(imgs)


# 获得预测结果(概率最大的)
_, preds_tensor = torch.max(output, 1)

preds = np.squeeze(preds_tensor.numpy()) if not train_on_gpu else np.squeeze(preds_tensor.cpu().numpy())
preds
array([1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0,
       0, 1, 1, 0, 1, 0, 0, 1, 0, 0], dtype=int64)
import numpy as np

 # 指定图片大小,图像大小为20宽、5高的绘图(单位为英寸inch)
plt.figure(figsize=(20, 10)) 
for idx, imgs in enumerate(imgs[:10]):
    #ax = fig.add_subplot(rows, columns, idx+1, xticks=[], yticks=[])
    npimg = imgs.numpy().transpose((1,2,0))
    npimg = npimg * np.array((0.229, 0.224, 0.225)) + np.array((0.485, 0.456, 0.406))
    npimg = npimg.clip(0, 1)
    # 将整个figure分成2行10列,绘制第i+1个子图。
    ax = plt.subplot(2, 5, idx+1)
    ax.set_title("{} ({})".format(classNames[preds[idx]], classNames[labels[idx]]),
                 color=("green" if classNames[preds[idx]]==classNames[labels[idx]] else "red"))
    plt.imshow(npimg)
    plt.axis('off')

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/90608.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【java】java JSR 269 简介

1.概述 看这篇文章先看实战:【java】java JSR 269 自定义注解实战 Lombok @Data注解 先看实战在看原理,比较容易理解。 注解( Annotation)第- -次是在JDK1.5中被引入进来的,当时开发者只能在运行期处理注解。JDK1.6引人了JSR269规范,允许开发者在编译期间对注解进行处理,…

云原生 | Kubernetes - 调度框架

目录 调度器 调度概览 kube-scheduler kube-scheduler 调度流程 调度框架 框架工作流程 调度周期和绑定周期 扩展点 队列排序 PreFilter Filter PostFilter PreScore Score NormalizeScore Reserve Permit PreBind Bind PostBind Unreserve 插件 API 插…

美皓医疗港交所上市破发:首日跌14% 公司市值4亿港元

雷递网 雷建平 12月14日美皓医疗集团有限公司(简称:“美皓医疗”,股票代码为:“01947”)今日在港交所上市,发行价为0.84港元,位于发行区间最低端位置。美皓医疗此次募资净额为7490万港元。这之前…

53、多用户通信项目

只讲解最核心的代码部分,界面部分省略 一、基础知识 项目开发流程: 需求分析——》设计阶段——》编码实现——》测试阶段——》实施阶段 二、需求分析 1、用户登录 2、拉取在线用户列表 3、无异常退出(客户端、服务端) 4、私…

商城系统功能业务逻辑架构_功能描述_OctShop

随着移动电商,社区电商的迅猛发蔚县,网上购物系统已成为了企业或商家销售商品的重要渠道和方式。网上购物系统让人们的购物简单、方便、快捷。实现了消费者足不出户就可以购买到自己需要的商品。而网上购物系统是专门帮助企业商家快速打造自己的用户群体…

如何编写安装openjdk15的dockerfile

方法一 从官方网站下载 openjdk 15 tar 文件,解压文件,删除下载的 tar 文件并将路径设置为 java 二进制文件。 创建一个 Dockerfile 并复制以下内容 FROM centos:8ENV PATH$PATH:/opt/java/jdk-15.0.2/binWORKDIR /opt/javaRUN curl https://downloa…

2023年深圳/汕头/揭阳/中山/惠州数据分析CPDA认证招生简章

CPDA数据分析师认证是中国大数据领域有一定权威度的中高端人才认证,它不仅是中国较早大数据专业技术人才认证、更是中国大数据时代先行者,具有广泛的社会认知度和权威性。 无论是地方政府引进人才、公务员报考、各大企业选聘人才,还是招投标加…

科研在线实用工具(文献,编程,文档,格式转换,OCR、数据分析可视化,图片、视频动画处理,设计,简历)

SCI: Sci-Hub: 将知识带给每个人Sci-Hub网站。免费获取学术期刊。免费下载来自ScienceDirect、IEEE、Wiley、Springer、Nature及其他的研究论文。https://sci-hub.se/在线编程: Anycodes 在线编程 - 可以随时随地进行编程学习和代码练习的在线编程平台 …

JMeter 扩展开发:自定义 JMeter 插件的调试

前言 在本系列专题之前的文章中,我们已经介绍了 JMeter 扩展开发的一些方法。但是在开发过程中还有一个需要处理的环节,是对编写的代码进行调试。一种方式是将开发的扩展与 JMeter 源码放在一起进行调试。但是这种方法的缺点是需要将整个 JMeter 的源码…

卫龙明日上市:募资净额9亿港元 腾讯云锋红杉高瓴或浮亏

雷递网 雷建平 12月14日卫龙食品(股票代码为:“09985”)将于明日在港交所上市,发行价为10.56港元,位于发行区间10.4到11.4港元的下端位置。卫龙食品此次募资净额为8.99亿港元;若行使超配权,则可…

GcExcel for java 6.0 简单例子 -jar has been cracked

GrapeCity Documents for Excel (简称:GcExcel)是葡萄城推出的一款基于 Java 平台的服务端高性能表格组件,可与 纯前端表格控件 SpreadJS 前后端兼容,无需依赖 Office、POI 或第三方应用软件,在前端展示电子…

关于旅游景点主题的HTML网页设计——广东名胜古迹(7页)HTML+CSS

👨‍🎓学生HTML静态网页基础水平制作👩‍🎓,页面排版干净简洁。使用HTMLCSS页面布局设计,web大学生网页设计作业源码,这是一个不错的旅游网页制作,画面精明,排版整洁,内容…

Node项目文档生成工具standard-release

简介 爱美之心人皆有之。本文就介绍如何使用standadr-release自动生成好看的Git提交记录文档。 背景 作为一只程序猿,Git代码管理工具相信大家都用过,那么Git提交记录想必大家也都看过,不管是用什么工具查看,多多少少都感觉乱&…

GoC2018下册 第2课(C++画图)

慧通教育 慧通教育 709.改变身高(下册第2课) 登录 710.改变身高(下册第2课) 登录 711.改变体型(下册第2课) 登录 712.改变体型(下册第2课) 登录 713.完美身材(下册第…

类型转换和优先级

目录 一、表达式求值 二、隐式类型转换 1、整型提升的意义 2、如何进行整型提升(3个例子) 三、算术转换 四、操作符的属性 1、优先级顺序表 2、运算法则 一、表达式求值 表达式求值的顺序一部分是由操作符的优先级和结合性决定。 同样,有…

C++ Reference: Standard C++ Library reference: Containers: map: map: swap

C官网参考链接&#xff1a;https://cplusplus.com/reference/map/map/swap-free/ 函数模板 <map> std::swap (map) template <class Key, class T, class Compare, class Alloc> void swap (map<Key,T,Compare,Alloc>& x, map<Key,T,Compare,Alloc…

融捷能源携手企企通,打造智能化、数字化采购平台

随着全球能源危机和环境污染问题日益突出&#xff0c;节能、环保有关行业的发展被高度重视&#xff0c;全球能源消费结构正向低碳化转型&#xff0c;加快发展可再生能源已经在全球范围内形成共识。 作为新能源产业的核心&#xff0c;锂电池技术和产业的发展也备受关注&#xff…

中断线程化

中断线程化 中断处理程序包括上半部硬件中断处理程序&#xff0c;下半部处理机制&#xff0c;包括软中断、tasklet、workqueue、中断线程化。 当一个外设中断发生后&#xff0c;内核会执行一个函数来响应该中断&#xff0c;这个函数通常被称为中断处理程序或中断服务例程。 上…

G631两级电液伺服阀控制器

G631系列两级电液伺服阀在电气液压伺服系统中作为执行元件&#xff0c;在伺服系统中液压执行机构同电气及气动执行机构相比&#xff0c;具有快速性好、单位重量输出功率大、传动平稳、抗干扰能力强等特点。另一方面&#xff0c;在伺服系统中传递信号和校正特性时多用电气元件。…

数据结构---散列表

散列表哈希函数散列表读写写读扩容总结散列表也叫作 哈希表&#xff08;hash table&#xff09;&#xff0c;这种数据结构提供了键&#xff08;Key&#xff09;和值&#xff08;Value&#xff09;的映射关系。只要给出一个Key&#xff0c;就可以高效查找到它所匹配的Value&…