pytorch在 gpu安装指南

附:很重要

查看GPU计算能力,,
https://developer.nvidia.com/zh-cn/cuda-gpus#compute
一定要 安装与计算力相符合的 cuda

1. 下载和安装nvidia显卡驱动 —— 一般可以省略

cmd 
nvidia-smi 或 nvidia –smi

如果有,则显示信息
如果没有, 查看 设备管理器 gpu版本和型号,去官网下载驱动
NVIDIA 驱动下载链接:
https://www.nvidia.cn/Download/index.aspx?lang=cn
下载对应你的英伟达显卡驱动。

2. 检查电脑是否有cuda —— 一般也可以省略

cmd 
nvcc-V

如果有,会显示cuda 版本信息
若没有,则安装cuda
NVIDIA CUDA各版本下载链接(包括最新11版本和以往10.2版本)
https://developer.nvidia.com/cuda-downloads
cuda 11.3自动配置环境变量

3. 下载对应cuda版本的cuDNN

https://developer.nvidia.com/rdp/cudnn-download
150****@163.com inu****123…

4. 安装anaconda

Just me
默认即可

5. 安装pytorch

之前的博客

https://blog.csdn.net/Inuyasha_1314/article/details/124958908

测试代码

import torch
# from torch.utils.tensorboard import SummaryWriter
import torchvision
from torch.utils.data import DataLoader
from torch import nn
from torch.nn import Sequential, Conv2d, MaxPool2d, Flatten, Linear
import time

# 定义设备(新增加)
device = torch.device("cuda")


# 准备数据及
train_data = torchvision.datasets.CIFAR10('./cifar10', True, transform=torchvision.transforms.ToTensor(),download=False)
test_data = torchvision.datasets.CIFAR10('./cifar10', False, transform=torchvision.transforms.ToTensor(),download=False)


# 求长度
train_data_size = len(train_data)
test_data_size = len(test_data)
print("训练数据及长度:{}".format(train_data_size))
print("测试数据集长度:{}".format(test_data_size))

# 加载数据及
train_dataloader = DataLoader(train_data, batch_size=64)
test_dataloader = DataLoader(test_data, batch_size=64)


# 搭建网络
class Lyy(nn.Module):
    def __init__(self):
        super(Lyy, self).__init__()
        self.model1 = Sequential(
            Conv2d(3, 32, 5, padding=2),
            MaxPool2d(2),
            Conv2d(32, 32, 5, padding=2),
            MaxPool2d(2),
            Conv2d(32, 64, 5, padding=2),
            MaxPool2d(2),
            Flatten(),
            Linear(1024, 64),
            Linear(64, 10)
        )

    def forward(self, x):
        x = self.model1(x)
        return x


# 创建网络模型(有更改)
lyy = Lyy()
lyy = lyy.to(device)

# 创建损失函数(有更改)
loss_fn = nn.CrossEntropyLoss()
loss_fn = loss_fn.to(device)

# 优化器
learning_rate = 1e-2
optimizer = torch.optim.SGD(lyy.parameters(),lr=learning_rate)


# 设置训练网络参数
total_train_step = 0
total_test_step = 0
epoch = 10


# 添加tensorboard
# writer = SummaryWriter("logs")


start_time = time.time()
for i in range(epoch):
    print("-----第{}轮训练开始了-----".format(i+1))

    # 训练步骤开始
    for data in train_dataloader:
        imgs, tragets = data

        imgs = imgs.to(device)
        tragets = tragets.to(device)

        output = lyy(imgs)
        loss = loss_fn(output, tragets)

        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        total_train_step += 1
        if total_train_step % 100 == 0:
            end_time = time.time()
            print("训练次数:{},Loss:{}, time:{}".format(total_train_step, loss.item(), end_time - start_time))
            # writer.add_scalar("train_loss", loss.item(), total_train_step)

    # 测试步骤开始
    total_test_loss = 0
    total_accuracy = 0

    with torch.no_grad():
        for data in test_dataloader:
            imgs, tragets = data

            imgs = imgs.to(device)
            tragets = tragets.to(device)

            output = lyy(imgs)
            loss = loss_fn(output, tragets)
            total_test_loss += loss

            accuracy = (output.argmax(1) -- tragets).sum()
            total_accuracy += accuracy

    print("整体测试机上误差:{}".format(total_test_loss))
    print("整体测试机上的正确率:{}".format(total_accuracy/test_data_size))
    # writer.add_scalar("test_loss", total_test_loss, total_test_step)
    # writer.add_scalar("test_accuracy", total_accuracy/total_test_step)
    total_test_step += 1

    # torch.save(lyy, "lyy_{}.pth".format(i))
    # print("模型已保存")


# writer.close()

你可能感兴趣的:(机器学习,pytorch,深度学习,人工智能)