pytorch安装

python3.6

pip3 install torchvision==0.2.0

MNIST手写数字0-9训练集下载
链接:https://pan.baidu.com/s/1kUiARaVTdFNAfJoS5xx6pw
提取码:xttr

错误

raise NotSupportedError(base.range(), "slicing multiple dimensions at the sa

借用一下其他大佬的测试代码

import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import datasets, transforms


# 设置网络结构
class Net(nn.Module):
    def __init__(self, in_features, out_features):
        super(Net, self).__init__()
        self.dnn1 = nn.Linear(in_features, 512)  # 第一层全连接层
        self.dnn2 = nn.Linear(512, out_features)  # 第二层全连接层

    def forward(self, x):
        x = F.relu(self.dnn1(x))  # relu激活
        x = self.dnn2(x)
        return x


net = Net(28 * 28, 10)

# 加载MNIST数据集
train_dataset = datasets.MNIST('../data/MNIST', train=True, download=False, transform=transforms.ToTensor())
test_dataset = datasets.MNIST('../data/MNIST', train=False, download=False, transform=transforms.ToTensor())

train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=128, shuffle=True)
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=128, shuffle=False)
# print(net)

# 开始训练
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(net.parameters(), lr=0.02)

for epoch in range(5):
    running_loss, running_acc = 0.0, 0.0
    for i, data in enumerate(train_loader):
        img, label = data
        img = img.reshape(-1, 28 * 28)
        out = net(img)
        loss = criterion(out, label)

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

        running_loss += loss.item() * label.size(0)
        _, predicted = torch.max(out, 1)
        running_acc += (predicted == label).sum().item()
        print('Epoch [{}/5], Step [{}/{}], Loss: {:.6f}, Acc: {:.6f}'.format(
            epoch + 1, i + 1, len(train_loader), loss.item(), (predicted == label).sum().item() / 128))
    # 测试
    test_loss, test_acc = 0.0, 0.0
    for i, data in enumerate(test_loader):
        img, label = data
        img = img.reshape(-1, 28 * 28)
        out = net(img)
        loss = criterion(out, label)

        test_loss += loss.item() * label.size(0)
        _, predicted = torch.max(out, 1)
        test_acc += (predicted == label).sum().item()

    print("Train {} epoch, Loss: {:.6f}, Acc: {:.6f}, Test_Loss: {:.6f}, Test_Acc: {:.6f}".format(
        epoch + 1, running_loss / (len(train_dataset)), running_acc / (len(train_dataset)),
        test_loss / (len(test_dataset)), test_acc / (len(test_dataset))))

效果

在这里插入图片描述

以下是几种常见的PyTorch安装方法: #### 使用Anaconda安装 1. 在清华源等镜像网站,查询PythonPyTorch对应版本[^1]。 2. 使用Anaconda创建虚拟环境,并指定Python版本。例如创建一个名为`pytorch_env`,Python版本为3.8的虚拟环境,命令如下: ```bash conda create -n pytorch_env python=3.8 ``` 3. 激活虚拟环境: ```bash conda activate pytorch_env ``` 4. 在虚拟环境中安装CUDA驱动(如果需要使用GPU加速),可通过`nvcc -v`查看已安装的CUDA版本,根据该版本在清华源找到配套的PyTorch [^1][^2]。 5. 配置清华源以加速下载,运行以下命令: ```bash conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/pytorch/ conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/ conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/ conda config --set show_channel_urls yes ``` 6. 安装PyTorch,注意要删除`-c pytorch`,使安装走清华镜像的channel [^4]。具体安装命令可根据所需的CUDA版本、PyTorch版本等在PyTorch官网获取。例如安装支持CUDA 11.3的PyTorch: ```bash conda install pytorch torchvision torchaudio cudatoolkit=11.3 ``` #### 本地安装安装 如果使用本地安装包,安装包格式通常为`tar.gz`。在安装PyTorch的时候要先安装指定的驱动、CUDA、CUDNN等。例如安装的是CUDA 10.1(可通过`nvcc -v`查看),则需在清华源找到配套的PyTorch [^2]。 #### 安装后测试 安装完成后,可通过以下代码测试PyTorch是否安装成功: ```python import torch print(torch.__version__) print(torch.cuda.is_available()) # 如果使用GPU,检查CUDA是否可用 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

BigData-0

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值