PyThorch是深度学习的框架,主要有2个核心功能:
高效率的张量计算, 同时支持强大的 GPU 加速计算功能。
搭建深度神经网络, 构建在自动求导系统之上的网络结构。
import torch as t
import warnings
warnings.filterwarnings("ignore")
#设定数据类型
t.set_default_tensor_type("torch.DoubleTensor")
t.Tensor().dtype
#还原类型
t.set_default_tensor_type("torch.FloatTensor")
t.Tensor().dtype
#创建数据
t.Tensor([1, 2, 3])
#通过numpy创建
import numpy as np
t.Tensor(np.random.randn(3))
查看数据形状
t.Tensor([[1, 2], [3, 4], [5, 6]]).shape
#查看数据大小
torch.Size([3,2])
其它创建方法
a = t.Tensor([[1, 2], [3, 4]])
b = t.Tensor([[5, 6], [7, 8]])
print(a + b)
print(a - b)
# 对 a 求列平均
a.mean(dim=0)
# a 中的每个元素求平方
a.pow(2)
# a 中的每个元素传入 sigmoid 函数
a.sigmoid()
注意,很多时候我们都需要通过 dim=
参数去指定操作的维度,正如 NumPy 中的 axis=
参数。
c = t.rand(5, 4)
# 取第 1 行
c[0]
# 取第 2, 3 行与 3, 4 列
c[1:3, 2:4]
c.reshape(4, 5)
c.view(4, 5)
Tensor 的 size 属性改变,但是 Storge 则不会改变。
全部评论