【ML】windows 安装使用pytorch

news2024/9/21 5:46:53

使用pytorch需要python环境,建议是直接装anaconda ,IDE用visual studio

anaconda安装

Anaconda 是一个用于科学计算的 Python 发行版,支持 Linux, Mac, Windows, 包含了众多流行的科学计算、数据分析的 Python 包
官网链接anaconda
本人下载:Anaconda3-2023.03-1-Windows-x86_64.exe 内置python 3.10
双击exe一键安装,安装好后可以通过anaconda navigator查看已安装的包
在这里插入图片描述
可以通过 Start - Anaconda3 - Anaconda PowerShell Prompt查看安装版本
check

pytorch 安装

官网
quick start guide

在这里插入图片描述
按需选择配置获取安装cmd,推荐windows下配置如下
PyTorch build – stable.
Your OS – Windows
Package – Conda
Language – Python
Compute Platform – CPU, 或者根据你Cuda版本选择合适的compute platform
cuda版本可以点nvdia系统配置从driver处看,比如下图第三行显示是11.6
在这里插入图片描述
也可以命令行运行nvdia-smi获取信息。

在 Anaconda prompt 命令窗口中输入cmd 开始安装 eg: conda install pytorch torchvision torchaudio pytorch-cuda=11.7 -c pytorch -c nvidia

安装结束确认
在这里插入图片描述

pytorch 使用

以图片分类demo为例使用pytorch

  1. visual studio 创建新project
    在这里插入图片描述

  2. 点Create a new project后选择Python Application,新建python项目,(直接运行项目等上传后贴链接 点击这里)

  3. 配置环境,添加环境选现有环境,如果默认没出来anaconda,就自定义环境,把anaconda所在路径添加进去,vs会自动识别,确认添加即可
    在这里插入图片描述

  4. demo正文开始,先load 数据集
    load CIFAR10, 第一次加载需要比较多的时间

from torchvision.datasets import CIFAR10
from torchvision.transforms import transforms
from torch.utils.data import DataLoader

# Loading and normalizing the data.
# Define transformations for the training and test sets
transformations = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])

# CIFAR10 dataset consists of 50K training images. We define the batch size of 10 to load 5,000 batches of images.
batch_size = 10
number_of_labels = 10 

# Create an instance for training. 
# When we run this code for the first time, the CIFAR10 train dataset will be downloaded locally. 
train_set =CIFAR10(root="./data",train=True,transform=transformations,download=True)

# Create a loader for the training set which will read the data within batch size and put into memory.
train_loader = DataLoader(train_set, batch_size=batch_size, shuffle=True, num_workers=0)
print("The number of images in a training set is: ", len(train_loader)*batch_size)

# Create an instance for testing, note that train is set to False.
# When we run this code for the first time, the CIFAR10 test dataset will be downloaded locally. 
test_set = CIFAR10(root="./data", train=False, transform=transformations, download=True)

# Create a loader for the test set which will read the data within batch size and put into memory. 
# Note that each shuffle is set to false for the test loader.
test_loader = DataLoader(test_set, batch_size=batch_size, shuffle=False, num_workers=0)
print("The number of images in a test set is: ", len(test_loader)*batch_size)

print("The number of batches per epoch is: ", len(train_loader))
classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')

再定义CNN网络,(也可以用别的网络,以CNN为例)
Conv -> BatchNorm -> ReLU -> Conv -> BatchNorm -> ReLU -> MaxPool -> Conv -> BatchNorm -> ReLU -> Conv -> BatchNorm -> ReLU -> Linear.

import torch
import torch.nn as nn
import torchvision
import torch.nn.functional as F

# Define a convolution neural network
class Network(nn.Module):
    def __init__(self):
        super(Network, self).__init__()
        
        self.conv1 = nn.Conv2d(in_channels=3, out_channels=12, kernel_size=5, stride=1, padding=1)
        self.bn1 = nn.BatchNorm2d(12)
        self.conv2 = nn.Conv2d(in_channels=12, out_channels=12, kernel_size=5, stride=1, padding=1)
        self.bn2 = nn.BatchNorm2d(12)
        self.pool = nn.MaxPool2d(2,2)
        self.conv4 = nn.Conv2d(in_channels=12, out_channels=24, kernel_size=5, stride=1, padding=1)
        self.bn4 = nn.BatchNorm2d(24)
        self.conv5 = nn.Conv2d(in_channels=24, out_channels=24, kernel_size=5, stride=1, padding=1)
        self.bn5 = nn.BatchNorm2d(24)
        self.fc1 = nn.Linear(24*10*10, 10)

    def forward(self, input):
        output = F.relu(self.bn1(self.conv1(input)))      
        output = F.relu(self.bn2(self.conv2(output)))     
        output = self.pool(output)                        
        output = F.relu(self.bn4(self.conv4(output)))     
        output = F.relu(self.bn5(self.conv5(output)))     
        output = output.view(-1, 24*10*10)
        output = self.fc1(output)

        return output

# Instantiate a neural network model 
model = Network()

定义loss function

from torch.optim import Adam
 
# Define the loss function with Classification Cross-Entropy loss and an optimizer with Adam optimizer
loss_fn = nn.CrossEntropyLoss()
optimizer = Adam(model.parameters(), lr=0.001, weight_decay=0.0001)

训练function,可以自定义运行平台和训练参数

from torch.autograd import Variable

# Function to save the model
def saveModel():
    path = "./myFirstModel.pth"
    torch.save(model.state_dict(), path)

# Function to test the model with the test dataset and print the accuracy for the test images
def testAccuracy():
    
    model.eval()
    accuracy = 0.0
    total = 0.0
    
    with torch.no_grad():
        for data in test_loader:
            images, labels = data
            # run the model on the test set to predict labels
            outputs = model(images)
            # the label with the highest energy will be our prediction
            _, predicted = torch.max(outputs.data, 1)
            total += labels.size(0)
            accuracy += (predicted == labels).sum().item()
    
    # compute the accuracy over all test images
    accuracy = (100 * accuracy / total)
    return(accuracy)


# Training function. We simply have to loop over our data iterator and feed the inputs to the network and optimize.
def train(num_epochs):
    
    best_accuracy = 0.0

    # Define your execution device
    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
    print("The model will be running on", device, "device")
    # Convert model parameters and buffers to CPU or Cuda
    model.to(device)

    for epoch in range(num_epochs):  # loop over the dataset multiple times
        running_loss = 0.0
        running_acc = 0.0

        for i, (images, labels) in enumerate(train_loader, 0):
            
            # get the inputs
            images = Variable(images.to(device))
            labels = Variable(labels.to(device))

            # zero the parameter gradients
            optimizer.zero_grad()
            # predict classes using images from the training set
            outputs = model(images)
            # compute the loss based on model output and real labels
            loss = loss_fn(outputs, labels)
            # backpropagate the loss
            loss.backward()
            # adjust parameters based on the calculated gradients
            optimizer.step()

            # Let's print statistics for every 1,000 images
            running_loss += loss.item()     # extract the loss value
            if i % 1000 == 999:    
                # print every 1000 (twice per epoch) 
                print('[%d, %5d] loss: %.3f' %
                      (epoch + 1, i + 1, running_loss / 1000))
                # zero the loss
                running_loss = 0.0

        # Compute and print the average accuracy fo this epoch when tested over all 10000 test images
        accuracy = testAccuracy()
        print('For epoch', epoch+1,'the test accuracy over the whole test set is %d %%' % (accuracy))
        
        # we want to save the model if the accuracy is the best
        if accuracy > best_accuracy:
            saveModel()
            best_accuracy = accuracy

结合数据集进行训练

import matplotlib.pyplot as plt
import numpy as np

# Function to show the images
def imageshow(img):
    img = img / 2 + 0.5     # unnormalize
    npimg = img.numpy()
    plt.imshow(np.transpose(npimg, (1, 2, 0)))
    plt.show()


# Function to test the model with a batch of images and show the labels predictions
def testBatch():
    # get batch of images from the test DataLoader  
    images, labels = next(iter(test_loader))

    # show all images as one image grid
    imageshow(torchvision.utils.make_grid(images))
   
    # Show the real labels on the screen 
    print('Real labels: ', ' '.join('%5s' % classes[labels[j]] 
                               for j in range(batch_size)))
  
    # Let's see what if the model identifiers the  labels of those example
    outputs = model(images)
    
    # We got the probability for every 10 labels. The highest (max) probability should be correct label
    _, predicted = torch.max(outputs, 1)
    
    # Let's show the predicted labels on the screen to compare with the real ones
    print('Predicted: ', ' '.join('%5s' % classes[predicted[j]] 
                              for j in range(batch_size)))

看每个class分类准确度,该函数可加可不加

# Function to test what classes performed well
def testClassess():
    class_correct = list(0. for i in range(number_of_labels))
    class_total = list(0. for i in range(number_of_labels))
    with torch.no_grad():
        for data in test_loader:
            images, labels = data
            outputs = model(images)
            _, predicted = torch.max(outputs, 1)
            c = (predicted == labels).squeeze()
            for i in range(batch_size):
                label = labels[i]
                class_correct[label] += c[i].item()
                class_total[label] += 1

    for i in range(number_of_labels):
        print('Accuracy of %5s : %2d %%' % (
            classes[i], 100 * class_correct[i] / class_total[i]))

主函数

if __name__ == "__main__":
    
    # Let's build our model
    train(5)
    print('Finished Training')

    # Test which classes performed well
    testClassess()
    
    # Let's load the model we just created and test the accuracy per label
    model = Network()
    path = "myFirstModel.pth"
    model.load_state_dict(torch.load(path))

    # Test with batch of images
    testBatch()

运行结果如下
在这里插入图片描述
项目已打包:下载

Ref:
https://learn.microsoft.com/zh-cn/visualstudio/python/managing-python-environments-in-visual-studio?view=vs-2022#selecting-and-installing-python-interpreters
https://learn.microsoft.com/en-us/windows/ai/windows-ml/tutorials/pytorch-train-model

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

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

相关文章

(转)maven安装及配置(详细版)

1.下载: 方式一可以从官方下载,下载页面:http://maven.apache.org/download.cgi 方式二:或者题主提供的版本下载maven安装包 提取码:ysns 下载好后是一个压缩文件 2.安装: maven压缩包解压到一个没有中文&a…

AI 编程

GitHub Copilot(收费) 开发者:微软 openAI 2022年8月22日之后开始收费,10美元/月,100美元/年。 CodeGeeX(免费) CodeGeeX 可以根据自然语言注释描述(支持中英文注释&#xff09…

20.$refs

$refs是vue操作DOM用的,每一个vue组件实例上,都包含一个$refs对象,里面存储对应的DOM元素或组件的引用,默认情况下$refs对象为空 目录 1 $refs在哪 2 使用ref操作DOM 3 使用ref操作组件 3.1 使用组件方法 3.2 操作组件…

13 JS04——运算符

目标: 1、运算符 2、算数运算符 3、递增和递减运算符 4、比较运算符 5、逻辑运算符 6、赋值运算符 7、运算符优先级 一、运算符 1、概念 运算符(operator)也被称作操作符,是用于实现赋值、比较和执行算数运算等功能的符号。 2…

解决java普通项目读取不到resouces目录下资源文件的办法

现象如下: 可以看到resources目录已经在idea中标记成了资源目录resources root,而且target/classes目录下也编译出了resources目录下的pci.properties文件,换句话说:java在编译时是读取到了resources下的文件的。 可是为什么new F…

App性能优化方案——布局层级太多怎么优化?

作者:小海编码日记 View整体布局是通过深度优先的方式来进行组织的,整体形似一颗树,所以优化布局层级主要通过三个方向来实施: 降低布局深度:使用merge标签或者布局层级优化等手段来减少View树的深度;布局…

代码随想录算法训练营第四十三天|1049. 最后一块石头的重量 II 、494. 目标和、474.一和零

文章目录 背包问题题型1049. 最后一块石头的重量 II494. 目标和474.一和零 背包问题题型 等和子集 —0-1背包能否装满最后一块石头—0-1背包尽量装满目标和—0-1背包装满,且有多少种装的方式(组合问题) 1049. 最后一块石头的重量 II 题目链…

网页爬虫之WebPack模块化解密(JS逆向)

WebPack打包: webpack是一个基于模块化的打包(构建)工具, 它把一切都视作模块。 概念: webpack是 JavaScript 应用程序的模块打包器,可以把开发中的所有资源(图片、js文件、css文件等)都看成模块,通过loade…

Java中Lambda表达式(面向初学者)

目录 一、Lambda表达式是什么?什么场景下使用Lambda? 1.Lambda 表达式是什么 2.函数式接口是什么 第二章、怎么用Lambda 1.必须有一个函数式接口 2.省略规则 3.Lambda经常用来和匿名内部类比较 第三章、具体使用场景举例() …

水果店(库)管理系统 —— 实现了管理员模式与顾客模式 JAVA

水果店(库)管理系统 1.前言:2.功能简介及部分测试视频:3.本管理系统的构建原理(简介):(1).如何跳转页面:(2).如何让控制台能输出彩色字体:(3).如何稳定存储数据:(4).如何…

误操作清空了回收站文件如何找到文件

我们在删除文件的时候,文件都是先跑到回收站里的,这样的防止我们出现误删的情况,但往往也会出现我们要恢复删除的文件却误操作清空了回收站的情况,那么误操作清空了回收站如何找到呢,下面小编给大家分享误操作清空了回…

window 10 安装node.js时遇到2502 2503错误(已解决)

node安装失败2503的解决办法:1、在WIN搜索框搜索powershell并右击;2、点击使用管理员身份运行powershell命令行工具;3、输入“msiexec /package node”;4、打开安装包,根据提示安装即可。 本文操作环境:Win…

9.Join的应用

1.reduceJoin的应用 案例:将两个表合并成一个新的表 需求分析:通过将关联条件作为Map输出的key(此处指pid),将两表满足Join条件的数据并携带数据所来源的文件信息,发往同一个ReduceTask,在Redu…

汇编小程序解析--3D立方体旋转

汇编小程序解析–3D立方体旋转,源代码如下,是vulture大神于1995年写的,我到现在才基本看懂。 ;本程序由国外的Vulture大哥编写,并公布了源码,这个是他95年的一个作品,可以说是在当时是非常成功的&#xff…

论shell之条件语句-if语句、case语句

目录 一:条件测试 1.文件测试 2.常见的测试操作符 3.整数值比较 ​4.字符串比较 ​5. 逻辑测试 二:if语句 1.单分支结构 2.单分支结构实例 3.双分支结构 4.双分支结构实例 5.多分支结构 6.多分支机构实例 7.嵌套if语句实例 三:case语…

2023企业服务的关键词:做强平台底座

作者 | 曾响铃 文 | 响铃说 4月下旬,软件行业相关的大会紧锣密鼓地开了好几场,不仅有政府主办的2023中国国际软件发展大会、中国软件创新发展大会,也有用友、浪潮等服务商举办的品牌活动,让软件业的话题一直保持热度。 以用友为…

十大排序算法简单总结与对比

假设排序均从小到大排序 排序算法工作原理平均时间复杂度最坏时间复杂度空间复杂度是否稳定排序冒泡排序把相邻元素两两比较,若左侧的元素大于右侧的元素,则交换,否则不交换。(每一轮最大的会跑到最右边)O(&#xff0…

VGA协议实践

文章目录 前言一、VGA接口定义与传输原理1、VGA接口定义2、传输原理3、不同分辨率对应不同参数 二、Verilog编程1、VGA显示彩色条纹2、VGA显示字符3、输出一幅彩色图像4、Quartus操作1、添加PLL核2、添加ROM核 三、全部代码四、总结五、参考资料 前言 VGA的全称是Video Graphi…

VBA最基础的趣味速成练习--VBA资料

很多朋友想学VBA,但是苦于无处入手,我特意花了几天时间,做了一个VBA速成练习表格 能让你快速上手VBA,感受到VBA的神奇之处,相信我们日常使用表格的朋友会非常喜欢它的, 下面是我们的表格界面,…

选择营销自动化软件时的3个常见错误

做出投资营销自动化软件的决定是一个重大决定,可能很难知道从哪里开始,尤其是当市场上有这么多选择时。选择正确的自动化软件可能是拥有良好的营销运营与拥有低效营销团队之间的区别。在这篇博文中,我们将讨论人们在选择营销自动化软件时最常…