跟着无神学Pytorch系列Day2

引子

Pytorch是科学论文中火热的深度学习框架之一,想从事深度学习方向,有学术意愿的小伙伴们不要迟疑,关注无神一起学主流框架Pytorch。

基础操作

确定安装好Pytorch包以后,用import进行导入,

import torch
import numpy as np

此后的篇章为了简便,自动忽略此类语句,以凸显核心的操作教学作用。

初始化

1.从字面值直接创建

data = [[1, 2], [3, 4]]
x_data = torch.tensor(data)

2.从numpy的ndarray使用torch.from_numpy函数进行转换(要import numpy)

np_array = np.array(data)
x_np = torch.from_numpy(np_array)

3.从其他tensor进行初始化,分为保留原数据和随机覆盖

x_ones = torch.ones_like(x_data) # retains the properties of x_data
print(f"Ones Tensor: \n {x_ones} \n")

x_rand = torch.rand_like(x_data, dtype=torch.float) # overrides the datatype of x_data
print(f"Random Tensor: \n {x_rand} \n")

4.按照特定的形状,随机或指定常数值创建

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 attributes describe their shape, datatype, and the device on which they are stored.

张量的属性描述其形状、数据单元的数据类型、设备(CPU、GPU)

tensor = torch.rand(3, 4)

print(f"Shape of tensor: {tensor.shape}")
print(f"Datatype of tensor: {tensor.dtype}")
print(f"Device tensor is stored on: {tensor.device}")

.x 即为取其成员函数,也就是其中的一个属性,如上述的三行代码分别所示。

张量的其他操作

Over 100 tensor operations, including transposing, indexing, slicing, mathematical operations, linear algebra, random sampling, and more

有超过一百种,包括转置(学过线性代数的伙伴们应该了解,也是AI和图形学的基础)、索引、切片、数学操作、线性代数、随机抽样等。

1.转换设备。

如果有计算资源(GPU),比如使用学校的云服务器或者华为云腾讯云等等、亦或是自己购买的算力,执行以下操作可以转为使用GPU,速度快一大截

# We move our tensor to the GPU if available
if torch.cuda.is_available():
  tensor = tensor.to('cuda')
  print(f"Device tensor is stored on: {tensor.device}")

2.切片赋值

tensor = torch.ones(4, 4)
tensor[:,1] = 0
print(tensor)

运行结果:

tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]])

3.张量拼接

t1 = torch.cat([tensor, tensor, tensor], dim=1)
print(t1)

结果为:

tensor([[1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
        [1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
        [1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
        [1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.]])

4.tensor转为numpy

相互转换,很方便吧,没错,有前人造的轮子我们不需要懂得怎样实现,会用API进行调用就可以了

t = torch.ones(5)
print(f"t: {t}")
n = t.numpy()
print(f"n: {n}")

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值