[arbre.dl--003]在anaconda安装pytorch

本文详细介绍了如何搭建PyTorch1.5.1的虚拟环境,包括使用conda创建环境、安装CPU版本的PyTorch及测试安装是否成功的方法。此外,还提供了一个简单的线性回归模型训练的例子,用于验证PyTorch的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.官网 https://pytorch.org/get-started/locally/

2.创建pytorch1.5.1的虚拟环境,python版本3.6

conda create -n pytorch1.5.1 python=3.6

3.根据官网说明生成安装命令,安装不需要cuda支持的pytorch1.5.1 cpu版:

conda install pytorch torchvision cpuonly -c pytorch

4.测试安装结果

import torch

print(torch.__version__)

输出为‘1.5.1’,表明安装成功。

5.一个最小的测试例子a.py

# -*- coding: utf-8 -*-
 
import torch
 
 
dtype = torch.float
device = torch.device("cpu")
# device = torch.device("cuda:0") # Uncomment this to run on GPU
 
# N is batch size; D_in is input dimension;
# H is hidden dimension; D_out is output dimension.
N, D_in, H, D_out = 64, 1000, 100, 10
 
# Create random input and output data
x = torch.randn(N, D_in, device=device, dtype=dtype)
y = torch.randn(N, D_out, device=device, dtype=dtype)
 
# Randomly initialize weights
w1 = torch.randn(D_in, H, device=device, dtype=dtype)
w2 = torch.randn(H, D_out, device=device, dtype=dtype)
 
learning_rate = 1e-6
for t in range(500):
    # Forward pass: compute predicted y
    h = x.mm(w1)
    h_relu = h.clamp(min=0)
    y_pred = h_relu.mm(w2)
 
    # Compute and print loss
    loss = (y_pred - y).pow(2).sum().item()
    print(t, loss)
 
    # Backprop to compute gradients of w1 and w2 with respect to loss
    grad_y_pred = 2.0 * (y_pred - y)
    grad_w2 = h_relu.t().mm(grad_y_pred)
    grad_h_relu = grad_y_pred.mm(w2.t())
    grad_h = grad_h_relu.clone()
    grad_h[h < 0] = 0
    grad_w1 = x.t().mm(grad_h)
 
    # Update weights using gradient descent
    w1 -= learning_rate * grad_w1
    w2 -= learning_rate * grad_w2

输出结果:

0 29138108.0
1 23484640.0
2 20555388.0
...

496 3.662774179247208e-05
497 3.607522012316622e-05
498 3.569219552446157e-05
499 3.529985042405315e-05
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值