栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

pytorch(1) —— 安装

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

pytorch(1) —— 安装

        编译darknet时已经安装了cuda、cudnn

Start Locally | PyTorch An open source machine learning framework that accelerates the path from research prototyping to production deployment.https://pytorch.org/get-started/locally/        

PyTorch Build : Stable (1.12.0)

Your OS : Linux

Package : Pip

Language : Python

Compute Platform : CUDA 11.6(安装的是11.7)

Run this Command:

pip3 install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu116

sudo apt install python3-pip

pip3 install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu116

        这样就安装好了,没有windows版安装那么复杂。

        测试,找了网上的测试代码

        编写 test.py
import torch
import time
# 查看torch版本
print(torch.__version__)
# 定义矩阵a和b,随机值填充
a = torch.randn(10000, 1000)
b = torch.randn(1000, 2000)
# 记录开始时间
t0 = time.time()
# 计算矩阵乘法
c = torch.matmul(a, b)
# 记录结束时间
t1 = time.time()
# 打印结果和运行时间
print(a.device, t1 - t0, c.norm(2))   # 这里的c.norm(2)是计算c的L2范数

# 使用GPU设备
device = torch.device('cuda')
# 将ab搬到GPU
a = a.to(device)
b = b.to(device)
# 运行,并记录运行时间
t0 = time.time()
c = torch.matmul(a, b)
t1 = time.time()
# 打印在GPU上运行所需时间
print(a.device, t1 - t0, c.norm(2))

# 再次运行,确认运行时间
t0 = time.time()
c = torch.matmul(a, b)
t1 = time.time()
print(a.device, t1 - t0, c.norm(2))


# 定义a b c x的值,abc指定为需要求导requires_grad=True
x = torch.tensor(2.)
a = torch.tensor(1., requires_grad=True)
b = torch.tensor(2., requires_grad=True)
c = torch.tensor(3., requires_grad=True)
# 定义y函数
y = a * x ** 2 + b * x + c;
# 使用autograd.grad自定求导
grads = torch.autograd.grad(y, [a, b, c])
# 打印abc分别的导数值(带入x的值)
print('after', grads[0],grads[1],grads[2])

        执行python3 test.py

1.12.0+cu116
cpu 0.168928861618042 tensor(141292.)
cuda:0 0.36303186416625977 tensor(141435.6250, device='cuda:0')
cuda:0 0.00019240379333496094 tensor(141435.6250, device='cuda:0')
after tensor(4.) tensor(2.) tensor(1.)

        那篇文章解释了运行结果,第一次CUDA运行,需要初始化环境,所以执行时间比CPU长,第二次就是正常的了。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1011858.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号