医疗保健网站前置审批文件,南京外贸网站建设,网上做石材去哪个网站,怎么举报app软件原文作者#xff1a;我辈李想 版权声明#xff1a;文章原创#xff0c;转载时请务必加上原文超链接、作者信息和本声明。 文章目录 前言一、Anaconda 中安装 PyTorch 和 CUDA二、检查PyTorch和CUDA版本三、PyTorch的基本使用四、PyTorch调用cuda五、Matplotlib绘制Pytorch损… 原文作者我辈李想 版权声明文章原创转载时请务必加上原文超链接、作者信息和本声明。 文章目录 前言一、Anaconda 中安装 PyTorch 和 CUDA二、检查PyTorch和CUDA版本三、PyTorch的基本使用四、PyTorch调用cuda五、Matplotlib绘制Pytorch损失函数和准确率六、tesorbrand显示图像七、用Pytorch写一个卷积神经网络八、用Pytorch写一个目标检测模型 前言
PyTorch是一个开源的Python深度学习框架可以用于构建各种类型的神经网络模型。
一、Anaconda 中安装 PyTorch 和 CUDA 首先下载并安装适用于您系统的 Anaconda 版本。 打开 Anaconda Prompt 或命令行工具并创建一个名为“pytorch”或任何其他您喜欢的环境此处假设您使用的是 Anaconda 4.5 或更高版本
conda create -n pytorch python3.7 anaconda激活新环境
conda activate pytorch安装 PyTorch
conda install pytorch torchvision torchaudio cudatoolkit11.1 -c pytorch -c nvidia此命令将安装适用于 CUDA 11.1 的 PyTorch 和 TorchVision以及适用于 CUDA 11.1 的 CUDA 工具包。
验证 PyTorch 安装是否成功
python -c import torch; print(torch.__version__)如果成功安装这将打印 PyTorch 的版本号。
二、检查PyTorch和CUDA版本
可以使用以下命令
import torchprint(torch.__version__)
print(torch.version.cuda)这将打印出您正在使用的PyTorch和CUDA版本。
三、PyTorch的基本使用 示例 PyTorch是一个开源的Python深度学习框架可以用于构建各种类型的神经网络模型。要使用PyTorch您需要首先安装它。可以使用以下命令在终端中安装PyTorch
pip install torch然后您可以在Python脚本中导入PyTorch并开始使用它。例如要构建一个简单的全连接神经网络可以使用以下代码
import torch
import torch.nn as nn# Define the neural network model
class Net(nn.Module):def __init__(self):super(Net, self).__init__()self.fc1 nn.Linear(784, 256)self.fc2 nn.Linear(256, 10)def forward(self, x):x x.view(-1, 784)x torch.relu(self.fc1(x))x self.fc2(x)return x# Instantiate the model and define the loss function and optimizer
net Net()
criterion nn.CrossEntropyLoss()
optimizer torch.optim.SGD(net.parameters(), lr0.01)# Load the data and train the model
for epoch in range(10):for i, (inputs, labels) in enumerate(train_loader, 0):optimizer.zero_grad()outputs net(inputs)loss criterion(outputs, labels)loss.backward()optimizer.step()# Evaluate the trained model on the test set
correct 0
total 0
with torch.no_grad():for inputs, labels in test_loader:outputs net(inputs)_, predicted torch.max(outputs.data, 1)total labels.size(0)correct (predicted labels).sum().item()
print(Accuracy: %d %% % (100 * correct / total))在这个例子中我们定义了一个简单的全连接神经网络使用MNIST数据集进行训练和测试。我们使用PyTorch内置的nn.Module类来定义神经网络模型并在forward方法中定义正向传播的操作。我们使用交叉熵损失函数和随机梯度下降SGD优化器来训练模型。我们使用训练数据集中的数据来更新模型参数并使用测试数据集来评估模型的准确性。
四、PyTorch调用cuda
在PyTorch中使用CUDA可以大大加速训练和推理过程。以下是使用CUDA的几个步骤
检查CUDA是否可用
import torchif torch.cuda.is_available():device torch.device(cuda) # 如果GPU可用则使用CUDA
else:device torch.device(cpu) # 如果GPU不可用则使用CPU将模型和数据加载到CUDA设备
model.to(device)
inputs, labels inputs.to(device), labels.to(device)将数据转换为CUDA张量
inputs inputs.cuda()
labels labels.cuda()在训练过程中使用CUDA加速计算
for inputs, labels in dataloader:inputs, labels inputs.to(device), labels.to(device)optimizer.zero_grad()outputs model(inputs)loss criterion(outputs, labels)loss.backward()optimizer.step()请注意在使用CUDA时您需要确保您的计算机具有兼容的GPU和正确的CUDA和cuDNN版本。您可以在PyTorch的官方文档中找到更多详细信息。
五、Matplotlib绘制Pytorch损失函数和准确率
在Pytorch中我们可以使用Matplotlib来绘制训练过程中的损失函数曲线、准确率曲线等。下面是一个简单的示例
import matplotlib.pyplot as plt# 定义损失函数和准确率列表
train_losses [0.1, 0.08, 0.05, 0.03, 0.02]
train_accs [90, 92, 95, 97, 98]# 绘制损失函数曲线
plt.plot(train_losses, labelTrain Loss)
plt.xlabel(Epoch)
plt.ylabel(Loss)
plt.legend()
plt.show()# 绘制准确率曲线
plt.plot(train_accs, labelTrain Accuracy)
plt.xlabel(Epoch)
plt.ylabel(Accuracy)
plt.legend()
plt.show()运行后会分别显示训练过程中的损失函数曲线和准确率曲线。我们可以根据自己的需要调整图表的样式和参数例如修改线条颜色、线条宽度、坐标轴范围等。
六、tesorbrand显示图像
PyTorch下的Tensorboard 使用
七、用Pytorch写一个卷积神经网络
下面是一个简单的卷积神经网络CNN的实现用PyTorch框架来训练MNIST手写数字识别数据集。
首先您需要导入所需的库和模块如下所示
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torchvision import datasets, transforms接下来您需要定义网络的架构。这个CNN有两个卷积层一个最大池化层和两个全连接层。代码如下
class Net(nn.Module):def __init__(self):super(Net, self).__init__()# 输入为28*28*1self.conv1 nn.Conv2d(1, 10, kernel_size5)# 输入为24*24*10self.conv2 nn.Conv2d(10, 20, kernel_size5)# 输入为20*20*20self.mp nn.MaxPool2d(2)# 输入为10*10*20self.fc1 nn.Linear(320, 50)self.fc2 nn.Linear(50, 10)def forward(self, x):x F.relu(self.mp(self.conv1(x)))x F.relu(self.mp(self.conv2(x)))x x.view(-1, 320)x F.relu(self.fc1(x))x self.fc2(x)return F.log_softmax(x, dim1)现在您需要定义训练函数和测试函数。训练函数将会用来训练模型而测试函数将会用来测试模型。代码如下
def train(model, device, train_loader, optimizer, epoch):model.train()for batch_idx, (data, target) in enumerate(train_loader):data, target data.to(device), target.to(device)optimizer.zero_grad()output model(data)loss F.nll_loss(output, target)loss.backward()optimizer.step()if batch_idx % 100 0:print(Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}.format(epoch, batch_idx * len(data), len(train_loader.dataset),100. * batch_idx / len(train_loader), loss.item()))def test(model, device, test_loader):model.eval()test_loss 0correct 0with torch.no_grad():for data, target in test_loader:data, target data.to(device), target.to(device)output model(data)test_loss F.nll_loss(output, target, reductionsum).item()pred output.argmax(dim1, keepdimTrue)correct pred.eq(target.view_as(pred)).sum().item()test_loss / len(test_loader.dataset)print(\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n.format(test_loss, correct, len(test_loader.dataset),100. * correct / len(test_loader.dataset)))接下来您需要加载数据集和定义训练和测试参数。代码如下
batch_size 64train_transforms transforms.Compose([transforms.ToTensor(),transforms.Normalize((0.1307,), (0.3081,))
])test_transforms transforms.Compose([transforms.ToTensor(),transforms.Normalize((0.1307,), (0.3081,))
])train_dataset datasets.MNIST(./data, trainTrue, downloadTrue, transformtrain_transforms)
test_dataset datasets.MNIST(./data, trainFalse, transformtest_transforms)train_loader torch.utils.data.DataLoader(train_dataset, batch_sizebatch_size, shuffleTrue)
test_loader torch.utils.data.DataLoader(test_dataset, batch_sizebatch_size, shuffleFalse)use_cuda torch.cuda.is_available()
device torch.device(cuda if use_cuda else cpu)model Net().to(device)
optimizer optim.SGD(model.parameters(), lr0.01, momentum0.5)最后您需要在循环中训练和测试模型。代码如下
epochs 10for epoch in range(1, epochs 1):train(model, device, train_loader, optimizer, epoch)test(model, device, test_loader)这是一个简单的CNN的实现用PyTorch训练MNIST数据集。您可以调整模型的超参数例如学习率、动量等来提高模型的准确性和性能。
八、用Pytorch写一个目标检测模型
下面是一个基于PyTorch的目标检测模型的实现使用Faster R-CNN网络并使用COCO数据集进行训练和测试。
首先您需要导入所需的库和模块如下所示
import torch
import torchvision
import torchvision.transforms as transforms
import torch.utils.data
import numpy as np
import matplotlib.pyplot as plt
import time
import os
import json
import torch.utils.data as data
from torchvision.datasets import CocoDetection
import torchvision.transforms.functional as F
import torch.nn as nn
import torch.optim as optim
from torchvision.models.detection import FasterRCNN
from torchvision.models.detection.rpn import AnchorGenerator
from torchvision.models.detection.backbone_utils import resnet_fpn_backbone
from torchvision.ops import MultiScaleRoIAlign接下来您需要定义数据转换和数据集类以加载和预处理COCO数据集。代码如下
class Compose(object):def __init__(self, transforms):self.transforms transformsdef __call__(self, img, target):for t in self.transforms:img, target t(img, target)return img, targetclass RandomHorizontalFlip(object):def __init__(self, probability0.5):self.probability probabilitydef __call__(self, img, target):if np.random.rand() self.probability:img F.hflip(img)target[boxes][:, [0, 2]] img.width - target[boxes][:, [2, 0]]return img, targetclass Resize(object):def __init__(self, max_size900, min_size600):self.max_size max_sizeself.min_size min_sizedef __call__(self, img, target):w, h img.sizesize self.min_sizeif w h and max(h, w * size / w) self.max_size:size int(w * size / w)elif max(h, w * size / h) self.max_size:size int(h * size / h)img F.resize(img, (size, size))target[boxes][:, :4] * size / self.min_sizereturn img, targetclass ToTensor(object):def __call__(self, img, target):img F.to_tensor(img)return img, targetclass COCODataset(data.Dataset):def __init__(self, data_dir, set_nametrain, transformNone):super().__init__()self.data_dir data_dirself.images_dir os.path.join(data_dir, set_name)self.set_name set_nameself.transform transformself.coco CocoDetection(self.images_dir, os.path.join(data_dir, f{set_name}.json))def __getitem__(self, index):image, target self.coco[index]image_id self.coco.ids[index]if self.transform is not None:image, target self.transform(image, target)return image, target, image_iddef __len__(self):return len(self.coco)接下来您需要定义模型的架构。这个Faster R-CNN网络使用ResNet-50 FPN作为骨干网络。代码如下
class FasterRCNNResNetFPN(nn.Module):def __init__(self, num_classes):super(FasterRCNNResNetFPN, self).__init__()self.num_classes num_classesbackbone resnet_fpn_backbone(resnet50, pretrainedTrue)anchor_generator AnchorGenerator(sizes((32, 64, 128, 256, 512),),aspect_ratios((0.5, 1.0, 2.0),))roi_pooler MultiScaleRoIAlign(featmap_names[0, 1, 2, 3],output_size7,sampling_ratio2)self.model FasterRCNN(backbone,num_classesnum_classes 1,rpn_anchor_generatoranchor_generator,box_roi_poolroi_pooler)def forward(self, x, targetsNone):if self.training and targets is None:raise ValueError(In training mode, targets should be passed)elif not self.training and targets is not None:raise ValueError(In inference mode, targets should not be passed)else:return self.model(x, targets)现在您需要设置训练和测试的超参数并进行模型训练。代码如下
batch_size 2
num_workers 2
num_epochs 10data_dir /path/to/cocotrain_transforms Compose([Resize(min_size600, max_size900),RandomHorizontalFlip(),ToTensor()])
test_transforms Compose([Resize(min_size800, max_size1333),ToTensor()])train_dataset COCODataset(data_dir, set_nametrain, transformtrain_transforms)
test_dataset COCODataset(data_dir, set_nameval, transformtest_transforms)train_loader data.DataLoader(train_dataset, batch_sizebatch_size, shuffleTrue, num_workersnum_workers, collate_fnlambda x: tuple(zip(*x)))
test_loader data.DataLoader(test_dataset, batch_sizebatch_size, shuffleFalse, num_workersnum_workers, collate_fnlambda x: tuple(zip(*x)))num_classes 80device torch.device(cuda if torch.cuda.is_available() else cpu)model FasterRCNNResNetFPN(num_classesnum_classes).to(device)optimizer optim.SGD(model.parameters(), lr0.01, momentum0.9, weight_decay0.0005)def train_one_epoch(model, optimizer, data_loader, device, epoch):model.train()train_loss 0.0start_time time.time()for step, (images, targets, image_ids) in enumerate(data_loader):images [img.to(device) for img in images]targets [{k: v.to(device) for k, v in t.items()} for t in targets]loss_dict model(images, targets)losses sum(loss_dict.values())train_loss losses.item()optimizer.zero_grad()losses.backward()optimizer.step()if step % 10 0:print(fEpoch: [{epoch}/{num_epochs}] Step: [{step}/{len(data_loader)}] Loss: {losses.item()})train_loss / len(data_loader)end_time time.time()print(fTraining Loss: {train_loss} Time: {end_time - start_time})def evaluate(model, data_loader, device):model.eval()results []for images, targets, image_ids in data_loader:images [img.to(device) for img in images]targets [{k: v.to(device) for k, v in t.items()} for t in targets]with torch.no_grad():outputs model(images)for i, (output, target) in enumerate(zip(outputs, targets)):result {image_id: image_ids[i],boxes: output[boxes].detach().cpu().numpy(),scores: output[scores].detach().cpu().numpy(),labels: output[labels].detach().cpu().numpy(),}target {image_id: image_ids[i],boxes: target[boxes].cpu().numpy(),labels: target[labels].cpu().numpy(),}results.append((result, target))return resultsfor epoch in range(num_epochs):train_one_epoch(model, optimizer, train_loader, device, epoch)results evaluate(model, test_loader, device)这是一个使用PyTorch实现的目标检测模型的示例使用Faster R-CNN网络和COCO数据集进行训练和测试。您可以根据需要调整模型的超参数以提高模型的准确性和性能。 文章转载自: http://www.morning.tmxfn.cn.gov.cn.tmxfn.cn http://www.morning.xbmwm.cn.gov.cn.xbmwm.cn http://www.morning.jrbyz.cn.gov.cn.jrbyz.cn http://www.morning.rshkh.cn.gov.cn.rshkh.cn http://www.morning.eronghe.com.gov.cn.eronghe.com http://www.morning.hsflq.cn.gov.cn.hsflq.cn http://www.morning.bndkf.cn.gov.cn.bndkf.cn http://www.morning.qzpkr.cn.gov.cn.qzpkr.cn http://www.morning.prsxj.cn.gov.cn.prsxj.cn http://www.morning.kwpnx.cn.gov.cn.kwpnx.cn http://www.morning.ngmjn.cn.gov.cn.ngmjn.cn http://www.morning.rmyqj.cn.gov.cn.rmyqj.cn http://www.morning.ftntr.cn.gov.cn.ftntr.cn http://www.morning.cwgpl.cn.gov.cn.cwgpl.cn http://www.morning.rfljb.cn.gov.cn.rfljb.cn http://www.morning.cwnqd.cn.gov.cn.cwnqd.cn http://www.morning.xpzkr.cn.gov.cn.xpzkr.cn http://www.morning.dfckx.cn.gov.cn.dfckx.cn http://www.morning.fbjnr.cn.gov.cn.fbjnr.cn http://www.morning.dshxj.cn.gov.cn.dshxj.cn http://www.morning.gnzsd.cn.gov.cn.gnzsd.cn http://www.morning.hnkkf.cn.gov.cn.hnkkf.cn http://www.morning.slwfy.cn.gov.cn.slwfy.cn http://www.morning.tsmcc.cn.gov.cn.tsmcc.cn http://www.morning.krkwp.cn.gov.cn.krkwp.cn http://www.morning.mntxalcb.com.gov.cn.mntxalcb.com http://www.morning.htjwz.cn.gov.cn.htjwz.cn http://www.morning.ymdhq.cn.gov.cn.ymdhq.cn http://www.morning.gwgjl.cn.gov.cn.gwgjl.cn http://www.morning.gtxrw.cn.gov.cn.gtxrw.cn http://www.morning.wflsk.cn.gov.cn.wflsk.cn http://www.morning.yrbqy.cn.gov.cn.yrbqy.cn http://www.morning.lynkz.cn.gov.cn.lynkz.cn http://www.morning.snmth.cn.gov.cn.snmth.cn http://www.morning.hrzky.cn.gov.cn.hrzky.cn http://www.morning.xmjzn.cn.gov.cn.xmjzn.cn http://www.morning.zrwlz.cn.gov.cn.zrwlz.cn http://www.morning.lbqt.cn.gov.cn.lbqt.cn http://www.morning.msgrq.cn.gov.cn.msgrq.cn http://www.morning.xqxlb.cn.gov.cn.xqxlb.cn http://www.morning.slfmp.cn.gov.cn.slfmp.cn http://www.morning.zlfxp.cn.gov.cn.zlfxp.cn http://www.morning.tkkjl.cn.gov.cn.tkkjl.cn http://www.morning.pjxw.cn.gov.cn.pjxw.cn http://www.morning.xkwyk.cn.gov.cn.xkwyk.cn http://www.morning.dnzyx.cn.gov.cn.dnzyx.cn http://www.morning.gqbtw.cn.gov.cn.gqbtw.cn http://www.morning.nrfqd.cn.gov.cn.nrfqd.cn http://www.morning.qwgct.cn.gov.cn.qwgct.cn http://www.morning.hxcuvg.cn.gov.cn.hxcuvg.cn http://www.morning.cfhwn.cn.gov.cn.cfhwn.cn http://www.morning.ckzjl.cn.gov.cn.ckzjl.cn http://www.morning.jpgfq.cn.gov.cn.jpgfq.cn http://www.morning.zxcny.cn.gov.cn.zxcny.cn http://www.morning.fqtdz.cn.gov.cn.fqtdz.cn http://www.morning.jkszt.cn.gov.cn.jkszt.cn http://www.morning.spnky.cn.gov.cn.spnky.cn http://www.morning.qzpw.cn.gov.cn.qzpw.cn http://www.morning.pghfy.cn.gov.cn.pghfy.cn http://www.morning.pqhgn.cn.gov.cn.pqhgn.cn http://www.morning.prmbb.cn.gov.cn.prmbb.cn http://www.morning.qpfmh.cn.gov.cn.qpfmh.cn http://www.morning.wqtzs.cn.gov.cn.wqtzs.cn http://www.morning.mwhqd.cn.gov.cn.mwhqd.cn http://www.morning.zxfr.cn.gov.cn.zxfr.cn http://www.morning.shxmr.cn.gov.cn.shxmr.cn http://www.morning.ynlpy.cn.gov.cn.ynlpy.cn http://www.morning.mqtzd.cn.gov.cn.mqtzd.cn http://www.morning.xqbbc.cn.gov.cn.xqbbc.cn http://www.morning.kdnbf.cn.gov.cn.kdnbf.cn http://www.morning.hwprz.cn.gov.cn.hwprz.cn http://www.morning.hlyfn.cn.gov.cn.hlyfn.cn http://www.morning.mszwg.cn.gov.cn.mszwg.cn http://www.morning.jppb.cn.gov.cn.jppb.cn http://www.morning.fbpdp.cn.gov.cn.fbpdp.cn http://www.morning.spdyl.cn.gov.cn.spdyl.cn http://www.morning.nkwgy.cn.gov.cn.nkwgy.cn http://www.morning.chhhq.cn.gov.cn.chhhq.cn http://www.morning.fdfdz.cn.gov.cn.fdfdz.cn http://www.morning.mfmx.cn.gov.cn.mfmx.cn