【PyTorch】图像多分类

多类图像分类的目标是为一组固定类别中的图像分配标签。

目录

加载和处理数据

搭建模型

定义损失函数

定义优化器

训练和迁移学习

用随机权重进行训练

用预训练权重进行训练


加载和处理数据

将使用 PyTorch torchvision 包中提供的 STL-10 数据集,数据集中有 10 个类:飞机、鸟、车、猫、鹿、狗、马、猴、船、卡车。图像为96*96像素的RGB图像。数据集包含 5,000 张训练图像和 8,000 张测试图像。在训练数据集和测试数据集中,每个类分别有 500 和 800 张图像。

from torchvision import datasets
import torchvision.transforms as transforms
import ospath2data="./data"
# 如果数据路径不存在,则创建
if not os.path.exists(path2data):os.mkdir(path2data)# 定义数据转换
data_transformer = transforms.Compose([transforms.ToTensor()])# 从datasets库中导入STL10数据集,并指定数据集的路径、分割方式、是否下载以及数据转换器
train_ds=datasets.STL10(path2data, split='train',download=True,transform=data_transformer)# 打印数据形状
print(train_ds.data.shape)

 若数据集导入较慢可直接下载:http://ai.stanford.edu/~acoates/stl10/stl10_binary.tar.gz

import collections# 获取标签
y_train=[y for _,y in train_ds]# 统计标签
counter_train=collections.Counter(y_train)
print(counter_train)

# 加载数据
test0_ds=datasets.STL10(path2data, split='test', download=True,transform=data_transformer)
# 打印数据形状
print(test0_ds.data.shape)

# 导入StratifiedShuffleSplit模块
from sklearn.model_selection import StratifiedShuffleSplit# 创建StratifiedShuffleSplit对象,设置分割次数为1,测试集大小为0.2,随机种子为0
sss = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=0)# 获取test0_ds的索引
indices=list(range(len(test0_ds)))# 获取test0_ds的标签
y_test0=[y for _,y in test0_ds]# 对索引和标签进行分割
for test_index, val_index in sss.split(indices, y_test0):# 打印测试集和验证集的索引print("test:", test_index, "val:", val_index)# 打印测试集和验证集的大小print(len(val_index),len(test_index))

# 从torch.utils.data中导入Subset类
from torch.utils.data import Subset# 从test0_ds中选取val_index索引的子集,赋值给val_ds
val_ds=Subset(test0_ds,val_index)
# 从test0_ds中选取test_index索引的子集,赋值给test_ds
test_ds=Subset(test0_ds,test_index)import collections
import numpy as np# 获取标签
y_test=[y for _,y in test_ds]
y_val=[y for _,y in val_ds]# 统计测试集和验证集的标签数量
counter_test=collections.Counter(y_test)
counter_val=collections.Counter(y_val)# 打印测试集和验证集的标签数量
print(counter_test)
print(counter_val)

from torchvision import utils
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline# 设置随机种子为0
np.random.seed(0)# 定义一个函数,用于显示图像
def show(img,y=None,color=True):# 将图像转换为numpy数组npimg = img.numpy()# 将图像的维度从(C,H,W)转换为(H,W,C)npimg_tr=np.transpose(npimg, (1,2,0))# 显示图像plt.imshow(npimg_tr)# 如果有标签,则显示标签if y is not None:plt.title("label: "+str(y))# 定义网格大小
grid_size=4
# 随机生成4个索引
rnd_inds=np.random.randint(0,len(train_ds),grid_size)
print("image indices:",rnd_inds)# 从训练集中获取这4个索引对应的图像和标签
x_grid=[train_ds[i][0] for i in rnd_inds]
y_grid=[train_ds[i][1] for i in rnd_inds]# 将这4个图像拼接成一个网格
x_grid=utils.make_grid(x_grid, nrow=4, padding=2)
print(x_grid.shape)# 调用helper函数显示网格
plt.figure(figsize=(10,10))
show(x_grid,y_grid)

 

# 设置随机种子为0 
np.random.seed(0)# 设置网格大小
grid_size=4
# 从验证数据集中随机选择grid_size个索引
rnd_inds=np.random.randint(0,len(val_ds),grid_size)
print("image indices:",rnd_inds)# 从验证数据集中选择对应的图像
x_grid=[val_ds[i][0] for i in rnd_inds]
# 从验证数据集中选择对应的标签
y_grid=[val_ds[i][1] for i in rnd_inds]# 将图像排列成网格
x_grid=utils.make_grid(x_grid, nrow=4, padding=2)
print(x_grid.shape)# 调用辅助函数
plt.figure(figsize=(10,10))
# 显示网格图像和标签
show(x_grid,y_grid)

 

 

import numpy as np# 计算训练集中每个样本的RGB均值
meanRGB=[np.mean(x.numpy(),axis=(1,2)) for x,_ in train_ds]  
# 计算训练集中每个样本的RGB标准差
stdRGB=[np.std(x.numpy(),axis=(1,2)) for x,_ in train_ds]  meanR=np.mean([m[0] for m in meanRGB])  # 计算所有样本的R通道均值的平均值
meanG=np.mean([m[1] for m in meanRGB])  
meanB=np.mean([m[2] for m in meanRGB])  stdR=np.mean([s[0] for s in stdRGB])  # 计算所有样本的R通道标准差的平均值
stdG=np.mean([s[1] for s in stdRGB])  
stdB=np.mean([s[2] for s in stdRGB])  print(meanR,meanG,meanB)  # 打印R、G、B通道的均值
print(stdR,stdG,stdB)  # 打印R、G、B通道的标准差

# 定义训练数据的转换器
train_transformer = transforms.Compose([# 随机水平翻转,翻转概率为0.5transforms.RandomHorizontalFlip(p=0.5),  # 随机垂直翻转,翻转概率为0.5transforms.RandomVerticalFlip(p=0.5),  # 将图像转换为张量transforms.ToTensor(),# 对图像进行归一化,均值和标准差分别为meanR, meanG, meanB和stdR, stdG, stdBtransforms.Normalize([meanR, meanG, meanB], [stdR, stdG, stdB])])# 定义测试数据的转换器
test0_transformer = transforms.Compose([# 将图像转换为张量transforms.ToTensor(),# 对图像进行归一化,均值和标准差分别为meanR, meanG, meanB和stdR, stdG, stdBtransforms.Normalize([meanR, meanG, meanB], [stdR, stdG, stdB]),])   # 将训练数据集的转换器赋值给训练数据集的transform属性
train_ds.transform=train_transformer
# 将测试数据集的转换器赋值给测试数据集的transform属性
test0_ds.transform=test0_transformerimport torch
import numpy as np
import matplotlib.pyplot as plt# 设置随机种子
np.random.seed(0)
torch.manual_seed(0)# 定义网格大小
grid_size=4# 从训练数据集中随机选择grid_size个样本的索引
rnd_inds=np.random.randint(0,len(train_ds),grid_size)
print("image indices:",rnd_inds)# 根据索引从训练数据集中获取对应的样本
x_grid=[train_ds[i][0] for i in rnd_inds]
y_grid=[train_ds[i][1] for i in rnd_inds]# 将样本转换为网格形式
x_grid=utils.make_grid(x_grid, nrow=4, padding=2)
print(x_grid.shape)# 创建一个10x10的图像
plt.figure(figsize=(10,10))
# 显示网格和对应的标签
show(x_grid,y_grid)

from torch.utils.data import DataLoader# 创建训练数据集的DataLoader,batch_size为32,shuffle为True,表示每次迭代时都会打乱数据集
train_dl = DataLoader(train_ds, batch_size=32, shuffle=True)
# 创建验证数据集的DataLoader,batch_size为64,shuffle为False,表示每次迭代时不会打乱数据集
val_dl = DataLoader(val_ds, batch_size=64, shuffle=False)  # 遍历训练数据集
for x, y in train_dl:# 打印x的形状print(x.shape)# 打印y的形状print(y.shape)# 跳出循环break

# 遍历val_dl中的每个元素,x和y分别表示输入和标签
for x, y in val_dl:# 打印输入的形状print(x.shape)# 打印标签的形状print(y.shape)# 退出循环break

# 从datasets库中导入FashionMNIST数据集,并将其设置为训练集
fashion_train=datasets.FashionMNIST(path2data, train=True, download=True)

搭建模型

使用torchvision为多分类任务构建一个模型。torchvision软件包提供了用于图像分类的多个最先进的深度学习模型的实现,包括 AlexNet、VGG、ResNet、SqueezeNet、DenseNet、Inception、GoogleNet、ShuffleNet。这些模型在 ImageNet 数据集上进行了训练,其中包含来自 1,000 个班级的 1400 多万张图像。可以分别使用具有随机初始化权重的架构、预训练权重进行尝试。

from torchvision import models
import torch# 创建一个resnet18模型,pretrained参数设置为False,表示不使用预训练的权重
model_resnet18 = models.resnet18(pretrained=False)
# 打印模型ResNet18
print(model_resnet18)

from torch import nn
# 定义类别数量
num_classes=10
# 获取模型ResNet18的全连接层输入特征数量
num_ftrs = model_resnet18.fc.in_features 
# 将全连接层替换为新的全连接层,输出特征数量为类别数量
model_resnet18.fc = nn.Linear(num_ftrs, num_classes)# 定义设备为GPU
device = torch.device("cuda:0")
# 将模型移动到GPU上
model_resnet18.to(device)

from torchsummary import summary# 打印模型结构,输入大小为(3, 224, 224),即3个通道,224x224大小的图像
summary(model_resnet18, input_size=(3, 224, 224))

# 遍历模型ResNet18的参数
for w in model_resnet18.parameters():# 将参数转换为CPU数据w=w.data.cpu()# 打印参数的形状print(w.shape)break# 计算参数的最小值
min_w=torch.min(w)
# 计算w1,其中w1 = (-1/(2*min_w))*w + 0.5 
w1 = (-1/(2*min_w))*w + 0.5 
# 打印w1的最小值和最大值
print(torch.min(w1).item(),torch.max(w1).item())# 计算网格大小
grid_size=len(w1)
# 生成网格
x_grid=[w1[i] for i in range(grid_size)]
x_grid=utils.make_grid(x_grid, nrow=8, padding=1)
print(x_grid.shape)# 创建一个5x5的图像
plt.figure(figsize=(5,5))
show(x_grid)

采用预训练权重

from torchvision import models
import torch# 加载预训练的resnet18模型
resnet18_pretrained = models.resnet18(pretrained=True)# 定义分类的类别数
num_classes=10
# 获取resnet18模型的最后一层全连接层的输入特征数
num_ftrs = resnet18_pretrained.fc.in_features
# 将最后一层全连接层替换为新的全连接层,新的全连接层的输出特征数为num_classes
resnet18_pretrained.fc = nn.Linear(num_ftrs, num_classes)# 定义设备为cuda:0
device = torch.device("cuda:0")
# 将模型移动到cuda:0设备上
resnet18_pretrained.to(device) 

# 遍历resnet18_pretrained的参数
for w in resnet18_pretrained.parameters():# 将参数转换为cpu格式w=w.data.cpu()print(w.shape)break# 计算w的最小值
min_w=torch.min(w)
# 计算w1,其中w1=(-1/(2*min_w))*w + 0.5
w1 = (-1/(2*min_w))*w + 0.5 
# 打印w1的最小值和最大值
print(torch.min(w1).item(),torch.max(w1).item())# 计算w1的网格大小
grid_size=len(w1)
# 将w1转换为网格形式
x_grid=[w1[i] for i in range(grid_size)]
x_grid=utils.make_grid(x_grid, nrow=8, padding=1)
print(x_grid.shape)# 创建一个5x5的图像
plt.figure(figsize=(5,5))
show(x_grid)

 

定义损失函数

定义损失函数的目的是将模型优化为预定义的指标。分类任务的标准损失函数是交叉熵损失或对数损失。在定义损失函数时,需要考虑模型输出的数量及其激活函数。对于多类分类任务,输出数设置为类数,输出激活函数确确定损失函数。

输出激活输出数量损失函数
None num_classes nn.CrossEntropyLoss
log_Softmax num_classes nn.NLLLoss
torch.manual_seed(0)# 定义输入数据的维度
n,c=4,5
# 生成随机输入数据,并设置requires_grad=True,表示需要计算梯度
y = torch.randn(n, c, requires_grad=True)
# 打印输入数据的形状
print(y.shape)# 定义交叉熵损失函数,reduction参数设置为"sum",表示将所有样本的损失相加
loss_func = nn.CrossEntropyLoss(reduction="sum")
# 生成随机目标数据,表示每个样本的类别
target = torch.randint(c,size=(n,))
# 打印目标数据的形状
print(target.shape)# 计算损失
loss = loss_func(y, target)
# 打印损失值
print(loss.item())

# 反向传播,计算梯度
loss.backward()
# 打印输出y的值
print (y.data)

定义优化器

torch.optim 包提供了通用优化器的实现。优化器将保持当前状态,并根据计算出的梯度更新参数。对于分类任务,随机梯度下降 (SGD) 和 Adam 优化器非常常用。Adam 优化器在速度和准确性方面通常优于 SGD,因此这里选择 Adam 优化器。

from torch import optim
# 定义优化器,使用Adam优化算法,优化model_resnet18的参数,学习率为1e-4
opt = optim.Adam(model_resnet18.parameters(), lr=1e-4)
# 定义一个函数,用于获取优化器的学习率
def get_lr(opt):# 遍历优化器的参数组for param_group in opt.param_groups:# 返回学习率return param_group['lr']# 调用函数,获取当前学习率
current_lr=get_lr(opt)
# 打印当前学习率
print('current lr={}'.format(current_lr))

 

from torch.optim.lr_scheduler import CosineAnnealingLR# 创建学习率调度器,T_max表示周期长度,eta_min表示最小学习率
lr_scheduler = CosineAnnealingLR(opt,T_max=2,eta_min=1e-5)
# 定义一个空列表lrs
lrs=[]
# 循环10次
for i in range(10):# 调用lr_scheduler.step()方法lr_scheduler.step()# 调用get_lr()方法获取当前学习率lr=get_lr(opt)# 打印当前epoch和对应的学习率print("epoch %s, lr: %.1e" %(i,lr))# 将当前学习率添加到列表lrs中lrs.append(lr)
# 绘制lrs列表中的数据
plt.plot(lrs)

 

 

训练和迁移学习

到目前为止,已经创建了数据集并定义了模型、损失函数和优化器,接下来将进行训练和验证。首先使用随机初始化的权重训练模型。然后使用预先训练的权重训练模型,这也称为迁移学习。迁移学习将从一个问题中学到的知识(权重)用于其他类似问题。训练和验证脚本可能很长且重复。为了提高代码可读性并避免代码重复,将先构建一些辅助函数。

# 定义一个函数metrics_batch,用于计算预测结果和目标之间的正确率
def metrics_batch(output, target):# 将输出结果的最大值所在的索引作为预测结果pred = output.argmax(dim=1, keepdim=True)# 计算预测结果和目标之间的正确率corrects=pred.eq(target.view_as(pred)).sum().item()# 返回正确率return corrects
def loss_batch(loss_func, output, target, opt=None):# 计算batch的损失loss = loss_func(output, target)# 计算batch的评估指标metric_b = metrics_batch(output,target)# 如果有优化器,则进行反向传播和参数更新if opt is not None:opt.zero_grad()loss.backward()opt.step()# 返回损失和评估指标return loss.item(), metric_bdevice = torch.device("cuda")# 定义一个函数loss_epoch,用于计算模型在数据集上的损失
def loss_epoch(model,loss_func,dataset_dl,sanity_check=False,opt=None):# 初始化运行损失和运行指标running_loss=0.0running_metric=0.0# 获取数据集的长度len_data=len(dataset_dl.dataset)# 遍历数据集for xb, yb in dataset_dl:# 将数据移动到GPU上xb=xb.to(device)yb=yb.to(device)# 获取模型输出output=model(xb)# 计算当前批次的损失和指标loss_b,metric_b=loss_batch(loss_func, output, yb, opt)# 累加损失和指标running_loss+=loss_bif metric_b is not None:running_metric+=metric_b# 如果是sanity_check模式,则只计算一个批次if sanity_check is True:break# 计算平均损失和指标loss=running_loss/float(len_data)metric=running_metric/float(len_data)# 返回平均损失和指标return loss, metricdef train_val(model, params):# 获取参数num_epochs=params["num_epochs"]loss_func=params["loss_func"]opt=params["optimizer"]train_dl=params["train_dl"]val_dl=params["val_dl"]sanity_check=params["sanity_check"]lr_scheduler=params["lr_scheduler"]path2weights=params["path2weights"]# 初始化损失和指标历史记录loss_history={"train": [],"val": [],}metric_history={"train": [],"val": [],}# 复制模型参数best_model_wts = copy.deepcopy(model.state_dict())# 初始化最佳损失best_loss=float('inf')# 遍历每个epochfor epoch in range(num_epochs):# 获取当前学习率current_lr=get_lr(opt)print('Epoch {}/{}, current lr={}'.format(epoch, num_epochs - 1, current_lr))# 训练模型model.train()train_loss, train_metric=loss_epoch(model,loss_func,train_dl,sanity_check,opt)# 记录训练损失和指标loss_history["train"].append(train_loss)metric_history["train"].append(train_metric)# 评估模型model.eval()with torch.no_grad():val_loss, val_metric=loss_epoch(model,loss_func,val_dl,sanity_check)# 如果验证损失小于最佳损失,则更新最佳损失和最佳模型参数if val_loss < best_loss:best_loss = val_lossbest_model_wts = copy.deepcopy(model.state_dict())# 将最佳模型参数保存到本地文件torch.save(model.state_dict(), path2weights)print("Copied best model weights!")# 记录验证损失和指标loss_history["val"].append(val_loss)metric_history["val"].append(val_metric)# 更新学习率lr_scheduler.step()# 打印训练损失、验证损失和准确率print("train loss: %.6f, dev loss: %.6f, accuracy: %.2f" %(train_loss,val_loss,100*val_metric))print("-"*10) # 加载最佳模型参数model.load_state_dict(best_model_wts)# 返回模型、损失历史和指标历史return model, loss_history, metric_history

用随机权重进行训练

import copy# 定义交叉熵损失函数,reduction参数设置为"sum",表示将所有样本的损失相加
loss_func = nn.CrossEntropyLoss(reduction="sum")
# 定义Adam优化器,优化模型参数,学习率为1e-4
opt = optim.Adam(model_resnet18.parameters(), lr=1e-4)
# 定义余弦退火学习率调度器,T_max参数设置为5,eta_min参数设置为1e-6
lr_scheduler = CosineAnnealingLR(opt,T_max=5,eta_min=1e-6)# 定义训练参数字典
params_train={"num_epochs": 3,  # 训练轮数"optimizer": opt,  # 优化器"loss_func": loss_func,  # 损失函数"train_dl": train_dl,  # 训练数据集"val_dl": val_dl,  # 验证数据集"sanity_check": False,  # 是否进行sanity check"lr_scheduler": lr_scheduler,  # 学习率调度器"path2weights": "./models/resnet18.pt",  # 模型权重保存路径
}# 训练和验证模型
model_resnet18,loss_hist,metric_hist=train_val(model_resnet18,params_train)

# 获取训练参数中的训练轮数
num_epochs=params_train["num_epochs"]# 绘制训练和验证损失曲线
plt.title("Train-Val Loss")
plt.plot(range(1,num_epochs+1),loss_hist["train"],label="train")
plt.plot(range(1,num_epochs+1),loss_hist["val"],label="val")
plt.ylabel("Loss")
plt.xlabel("Training Epochs")
plt.legend()
plt.show()# 绘制训练和验证准确率曲线
plt.title("Train-Val Accuracy")
plt.plot(range(1,num_epochs+1),metric_hist["train"],label="train")
plt.plot(range(1,num_epochs+1),metric_hist["val"],label="val")
plt.ylabel("Accuracy")
plt.xlabel("Training Epochs")
plt.legend()
plt.show()

用预训练权重进行训练

import copy# 定义损失函数,使用交叉熵损失,并设置reduction为sum
loss_func = nn.CrossEntropyLoss(reduction="sum")
# 定义优化器,使用Adam优化器,并设置学习率为1e-4
opt = optim.Adam(resnet18_pretrained.parameters(), lr=1e-4)
# 定义学习率调度器,使用余弦退火调度器,设置最大周期为5,最小学习率为1e-6
lr_scheduler = CosineAnnealingLR(opt,T_max=5,eta_min=1e-6)# 定义训练参数
params_train={"num_epochs": 3,  # 设置训练周期为3"optimizer": opt,  # 设置优化器"loss_func": loss_func,  # 设置损失函数"train_dl": train_dl,  # 设置训练数据集"val_dl": val_dl,  # 设置验证数据集"sanity_check": False,  # 设置是否进行sanity check"lr_scheduler": lr_scheduler,  # 设置学习率调度器"path2weights": "./models/resnet18_pretrained.pt",  # 设置权重保存路径
}# 调用train_val函数进行训练和验证,并返回训练后的模型、损失历史和指标历史
resnet18_pretrained,loss_hist,metric_hist=train_val(resnet18_pretrained,params_train)

# 获取训练参数中的训练轮数
num_epochs=params_train["num_epochs"]# 绘制训练和验证损失曲线
plt.title("Train-Val Loss")
plt.plot(range(1,num_epochs+1),loss_hist["train"],label="train")
plt.plot(range(1,num_epochs+1),loss_hist["val"],label="val")
plt.ylabel("Loss")
plt.xlabel("Training Epochs")
plt.legend()
plt.show()# 绘制训练和验证准确率曲线
plt.title("Train-Val Accuracy")
plt.plot(range(1,num_epochs+1),metric_hist["train"],label="train")
plt.plot(range(1,num_epochs+1),metric_hist["val"],label="val")
plt.ylabel("Accuracy")
plt.xlabel("Training Epochs")
plt.legend()
plt.show()

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

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

相关文章

计算机视觉----opencv实战----指纹识别的案例

一、数据准备src2.BMPsrc1.BMPsrc.bmpmodel.BMP二、识别原理讲解&#xff08;sift特征提取&#xff09;SIFT&#xff08;Scale-Invariant Feature Transform&#xff0c;尺度不变特征变换&#xff09;是一种经典的图像特征提取算法&#xff0c;核心优势是不受图像尺度缩放、旋转…

npm 发布流程——从创建组件到发布到 npm 仓库

1. 准备组件 1.1 创建一个 Vue 组件 假设我们要创建一个简单的按钮组件&#xff1a; src/MyButton.vue <template><button class"my-btn" click"$emit(click)"><slot /></button> </template><script setup lang"ts…

MySQL入门基础指南

目录 一、什么是数据库&#xff1f; 仅依靠文件存储数据存在以下几个明显缺点&#xff1a; 数据库的存储介质通常包括&#xff1a; 二、主流数据库介绍 三、客户端 VS 服务器 四、推荐看的MySQL安装技术博客 五、数据库的存储介质 数据库的存储介质主要分为以下两类&am…

【实战中提升自己完结篇】分支篇之分支之无线、内网安全与QOS部署(完结)

1 1拓扑 「模拟器、工具合集」复制整段内容 链接&#xff1a;https://docs.qq.com/sheet/DV0xxTmFDRFVoY1dQ?tab7ulgil1 分支无线部署 说明&#xff1a;分支无线用瘦AP部署&#xff0c;通过VPN直接注册到总部的AC上面&#xff0c;实现无线的业务提供&…

带你了解STM32:GPIO通用输入输出口

目录 3.1 GPIO简介 3.2 GPIO基本结构 3.3 GPIO位结构 输入部分&#xff1a; 二极管的保护作用&#xff1a; 施密特触发器&#xff1a; 片上外设端口 输出部分&#xff1a; MOS管 3.4 GPIO模式 3.4.1 浮空/上拉/下拉输入 3.4.2 模拟输入 3.4.3 开漏/推挽输出 3.4.…

Http(自写)

作为一个程序员&#xff0c;假设我们要在a电脑的进程里发一段数据到b电脑&#xff0c;一般使用socket编程&#xff0c;可选项也就tcp&#xff0c;udp二选一socket本质上就是一个代码库tcp有粘包问题&#xff08;字节流&#xff09;&#xff0c;纯裸tcp不能之际拿来使用所以我们…

C#使用OpenVinoSharp和PP-Human进行行人检测

效果 项目依赖 OpenCvSharp 4.11.0.20250507 OpenVINO.CSharp.Windows 2024.0.0.1 主要代码 using OpenCvSharp; using OpenVinoSharp; using System; using System.Windows.Forms;namespace HelloPPHuman {public partial class Form1 : Form{public Form1(){InitializeCo…

四、Scala深入面向对象:类、对象与伴生关系

在前几节中&#xff0c;我们学习了 Scala 的基础语法和流程控制。现在&#xff0c;我们将深入探索 Scala 作为一门纯粹的面向对象语言的核心。在 Scala 中&#xff0c;万物皆对象&#xff0c;没有像 Java 那样的原始类型和静态成员的区分。本节将重点介绍如何定义对象的蓝图&am…

【大语言模型 58】分布式文件系统:训练数据高效存储

分布式文件系统&#xff1a;训练数据高效存储 关键词&#xff1a;分布式文件系统、HDFS、Lustre、GlusterFS、数据本地性、I/O优化、存储架构、大数据存储、训练数据管理、存储性能调优 摘要&#xff1a;本文深入探讨大语言模型训练中的分布式文件系统技术&#xff0c;从存储架…

【科研绘图系列】R语言绘制散点图以及线性回归拟合曲线图

禁止商业或二改转载,仅供自学使用,侵权必究,如需截取部分内容请后台联系作者! 文章目录 介绍 加载R包 数据下载 函数 导入数据 数据预处理 画图 总结 系统信息 介绍 数据导入 代码的开始部分涉及多个数据集的导入,这些数据集涵盖了不同类型的生态学数据,包括实验室培养…

SQL 数据库操作语言详解

1. SQL 语言概述SQL&#xff08;Structured Query Language&#xff09;是用于管理关系型数据库的标准语言&#xff0c;主要分为以下几个子语言&#xff1a;- DQL&#xff08;数据查询语言&#xff09;&#xff1a;SELECT - 用于数据查询 - DML&#xff08;数据操作语言&#x…

积分变换的前世今生

积分变换常应用于解微分方程微分方程的解法&#xff1a;时域经典法&#xff1b;频域变换法&#xff1b;“积分变换”最初并不是为了解微分方程&#xff0c;而是出于更“纯粹”的数学动机——理解函数的结构、求解代数或几何问题&#xff0c;以及简化复杂的积分运算。微分方程的…

《Linux——gflags》

一、什么是gflags&#xff1f; gflags 是一个由 Google 开发的命令行参数解析库&#xff0c;主要用于在 C&#xff08;也支持其他语言&#xff09;程序中便捷地处理命令行参数。它的核心作用是帮助开发者快速定义、解析和使用命令行选项&#xff0c;避免手动编写繁琐的参数解析…

编译器的前端中端和后端

前面说的词法分析和语法分析&#xff0c;确实是编译器前端 (Front End) 最核心的两个部分。但前端的工作还没有结束。编译器各阶段划分 一个完整的编译器通常可以分为三个部分&#xff1a;前端、中端 (Middle End)、后端 (Back End)。 前端 (Front End) 核心职责: 理解源代码。…

黑马Java进阶教程,全面剖析Java多线程编程,并发和并行,笔记02

黑马Java进阶教程&#xff0c;全面剖析Java多线程编程&#xff0c;并发和并行&#xff0c;笔记02 一、并发和并行 并发&#xff1a;在同一时刻&#xff0c;有多个指令在单个CPU上交替执行 并行&#xff1a;在同一时刻&#xff0c;有多个指令在多个CPU上同时执行 二、为什么有…

20250908 背包DP总结

引子 ~ 我们都有一个家&#xff0c;名字叫背包 ~ 背包DP 顾名思义&#xff0c;背包DP是用来解决背包最值问题的。题目会给出背包的容量&#xff0c;以及几个物品的属性&#xff0c;比如重量&#xff0c;价值&#xff0c;限额等等&#xff0c;具体是什么看题目。 01背包 01…

Redis持久化之RDB:快照机制原理、配置与最佳实践

Redis持久化之RDB&#xff1a;快照机制原理、配置与最佳实践 1. RDB持久化概述 1.1 什么是RDB RDB&#xff08;Redis Database&#xff09;是Redis的默认持久化方式&#xff0c;它在指定的时间间隔内生成数据集的快照&#xff08;snapshot&#xff09;&#xff0c;并将快照保…

daily notes[44]

文章目录基础references基础 hello,world是几乎所有编程语言的第一例子&#xff0c;rust也不例外。但和其它语言不一样&#xff0c;Rust的源码最好拥有自己的项目目录。 $ mkdir ~/pro $ cd ~/pro $ mkdir helloWorld $ cd helloWorld源代码文件名为main.rs&#xff0c;内容如…

JavaScript对象创建方式完全指南:从原始到现代的演进之路

前言 作为一名前端开发者&#xff0c;JavaScript中对象创建是很重要。在JavaScript这门基于原型的语言中&#xff0c;对象几乎无处不在。今天&#xff0c;我将带领大家回顾JavaScript对象创建的7种方式&#xff0c;从最原始的字面量到现代的ES6 class&#xff0c;每一步演进都解…

基于单片机的无线水塔监控系统设计(论文+源码)

本设计为基于单片机的无线水塔监控系统设计&#xff0c;主要由以下几部分组成&#xff1a;均采用STC89C52RC单片机为主控&#xff1b;主机&#xff1a;NRF24L01无线通讯模块&#xff0c;1602LCD液晶显示屏。从机&#xff1a;NRF24L01无线通讯模块&#xff0c;水位传感器&#x…