1.Pytorch 学习 基础

本文详细介绍PyTorch中张量的基本操作,包括创建张量、数据类型转换、形状改变、算术运算及GPU加速等核心功能。同时,文章还展示了如何在PyTorch中实现张量与NumPy数组之间的相互转换,以及如何利用GPU进行高效计算。

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

import torch
import numpy as np

print(torch.empty(5,3))
print(torch.rand(5,3))
print(torch.zeros(5,3,dtype=torch.long))
print(torch.zeros(5,3).long())
print(torch.tensor([5.5,3]))
x = torch.tensor([5.5,3])  #tensor([5.5000, 3.0000])
print(x.shape) #torch.Size([2])  列,行
y = x.new_ones(5,3)
print(y.type()) #torch.FloatTensor
y = x.new_ones(5,3,dtype=torch.double)
print(y)
y = torch.rand_like(x, dtype=torch.float)
print(y) #tensor([0.0698, 0.3707])

x = torch.rand(5,3)
y = torch.rand_like(x)
print('x:{} \n y:{}'.format(x,y))
print(x+y)
print(torch.add(x,y))

y.add_(x)
print(y)

print(y.shape) #torch.Size([5, 3])
y = y.view(15)  #变成了一行
print(y)
print(y.shape) #torch.Size([15])

x =torch.randn(1)
print(x) #tensor([-0.4526])
print(x.data) #tensor([-0.4526])
print(x.grad)
print(x.item()) # 获取元素  -0.4526430666446686

# y是一维的
y = y.view(3,-1)
print(y.shape) #torch.Size([3, 5])
y = y.transpose(1,0)
print(y.shape) #torch.Size([5, 3])

#####################################################

a = torch.ones(5)
b = a.numpy()
print(a,',',b) #tensor([1., 1., 1., 1., 1.]) , [1. 1. 1. 1. 1.]
b[1] = 2
print(a)  #tensor([1., 2., 1., 1., 1.])


a = np.ones(5)
b = torch.from_numpy(a)
np.add(a,1,out=a)
print(a,',',b) #[2. 2. 2. 2. 2.] , tensor([2., 2., 2., 2., 2.], dtype=torch.float64)

x = torch.randn(5)
if torch.cuda.is_available():
    device = torch.device("cuda")
    y = torch.ones_like(x,device=device)
    x = x.to(device=device)
    z = torch.add(x,y)
    print(z)  #tensor([0.6030, 1.5045, 0.7795, 1.5226, 2.0471], device='cuda:0')
    print(z.to('cpu', torch.double)) # 返还到cpu
    print(z.cpu())
    #tensor([0.6030, 1.5045, 0.7795, 1.5226, 2.0471], dtype=torch.float64)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值