PyTorch快速入门

一、官方Tutorials

第一部分是快速阅读官方链接:官方tutorials,前提是已经知道numpy和基础的python知识。接下来是对官方文档做的阅读笔记,持续更新

张量(Tensors)

1.张量是特殊数据类型,可以在GPU或其他硬件加速器上运行,用于表示在PyTorch中的数据。
2.和Numpy的数组相似,张量和数组可以共用底部内存
3.自动微分

张量的初始化、shape、张量的属性、张量的操作(矩阵乘法、点乘,索引切片、数组与张量间的转换、CPU转移到GPU)见下面程序

import torch
import numpy as np

#初始化张量的方法
#数据
data = [[1,2],[3,4]]
x_data = torch.tensor(data)
#数组
np_array = np.array(data)
x_np = torch.from_numpy(np_array)
#其他张量
x_ones = torch.ones_like(x_data)
print(f'Ones Tensor: \n {x_ones} \n')
x_rand = torch.rand_like(x_data,dtype=torch.float)
print(f'Random Tensor: \n {x_rand} \n')

# shape——张量的维度
shape = (2,3,)
rand_tensor = torch.rand(shape)
ones_tensor = torch.ones(shape)
zeros_tensor = torch.zeros(shape)
print(f"Random Tensor: \n {rand_tensor} \n")
print(f"Ones Tensor: \n {ones_tensor} \n")
print(f"Zeros Tensor: \n {zeros_tensor}")

# 张量的属性
tensor = torch.rand(3,4)
print(f'Shape pf tensor:{tensor.shape}')
print(f'Datatype of tensor:{tensor.dtype}')
print(f'Device tensor is stored on{tensor.device}')

# We move our tensor to the GPU if available
if torch.cuda.is_available():
    tensor = tensor.to('cuda')
#与numpy中数组相同的索引和切片
tensor = torch.ones(4, 4)
print('First row: ',tensor[0])
print('First column: ', tensor[:, 0])
print('Last column:', tensor[..., -1])
tensor[:,1] = 0
print(tensor)
#连接多个张量
t1 = torch.cat([tensor, tensor, tensor], dim=1)
print(t1)
# 矩阵乘法运算:三种方法
y1 = tensor @ tensor.T

y2 = tensor.matmul(tensor.T)

y3 = torch.rand_like(tensor)
torch.matmul(tensor, tensor.T, out=y3)
# 点乘羽=运算:三种方法
z1 = tensor * tensor

z2 = tensor.mul(tensor)

z3 = torch.rand_like(tensor)
torch.mul(tensor, tensor, out=z3)

# 单个张量转换为python数值
agg = tensor.sum()
agg_item = agg.item()
print(agg_item, type(agg_item))
#In-place operations:不推荐
print(tensor, "\n")
tensor.add_(5)
print(tensor)

# 在CPU上的张量和数组间的转换,共享一个内存,任何一个改变都会引起两者变化
# 张量变数组 tensor.numpy()
t = torch.ones(5)
print(f"t: {t}")
n = t.numpy()
print(f"n: {n}")
# 数组到张量 torch.from_numpy(narray)
n = np.ones(5)
t = torch.from_numpy(n)

np.add(n, 1, out=n)
print(f"t: {t}")
print(f"n: {n}")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值