Tensor 与 Pytorch 的关联就类似於 Array 与 Python,就是一个元素,不用想太多
在开始运用 Tensor 之前,当然要学会创建一个 Tensor 来使用,所以一开始我们先来看看怎麽创建一个 Tensor
创建空的 tensor torch.empty()
x = torch.empty(2)
print(x)
# tensor([5.2430e+33, 5.4511e-43])
x = torch.empty(2, 3)
print(x)
# tensor([[0., 0., 0.],
# [0., 0., 0.]])
创建 0 tensor torch.zeros()
x = torch.zeros(2, 3)
print(x)
# tensor([[0., 0., 0.],
# [0., 0., 0.]])
创建 random tensor torch.rand()
x = torch.rand(2, 3)
print(x)
# tensor([[0.6430, 0.0116, 0.1679],
# [0.8597, 0.1615, 0.4508]])
empty
跟 zeros
的差别在 zeros
是创建零元素,empty
则是单纯宣告记忆体区块,并没有初始化参数,因此里面的参数可以是任何值
创建 1 tensor torch.ones()
x = torch.ones(2, 3)
print(x)
# tensor([[1., 1., 1.],
# [1., 1., 1.]])
资料型态 torch.dtype
x = torch.ones(2, 3)
print(x.dtype)
# torch.float32
torch.float32
x = torch.ones(2, 3, dtype=torch.int)
print(x.dtype)
# torch.int
资料大小 torch.size()
x = torch.ones(2, 3)
print(x.size())
# torch.Size([2, 3])
也可以直接赋值
x = torch.tensor([2, 3])
print(x)
# tensor([2, 3])
print(x.size())
# torch.Size([2])
+
-
*
/
ans = x1 + x2
ans = torch.add(x1, x2)
x1
加到 x2
中
x2.add_(x1)
ans = x1 - x2
ans = torch.sub(x1, x2)
ans = x1 * x2
ans = torch.mul(x1, x2)
ans = x1 / x2
ans = torch.div(x1, x2)
array
或是 list
的时候往往也会选取部分资料,那如何取得 Tensor 之中的 items 呢?下面我们会基於
x = torch.rand(5, 3)
print(x)
# tensor([[0.8033, 0.7967, 0.0952],
# [0.0960, 0.2553, 0.9135],
# [0.5835, 0.1997, 0.4466],
# [0.7153, 0.9609, 0.7458],
# [0.1914, 0.5431, 0.2532]])
来介绍各种资料的取法,那由於中文的那个 row column 的行列问题,我们这边就直接用英文表示print(x[0, :])
# tensor([0.8033, 0.7967, 0.0952])
print(x[:, 0])
# tensor([0.8033, 0.0960, 0.5835, 0.7153, 0.1914])
print(x[0, 0])
# tensor(0.8033)
print(x[0, 0].item())
# 0.8032872080802917
y = x.view(15)
print(y)
# tensor([0.8033, 0.7967, 0.0952, 0.0960, 0.2553, 0.9135, 0.5835, 0.1997, 0.4466,
# 0.7153, 0.9609, 0.7458, 0.1914, 0.5431, 0.2532])
y = x.view(-1, 5)
print(y.size())
# torch.Size([3, 5])
a = torch.ones(5)
print(a)
b = a.numpy()
print(b)
# tensor([1., 1., 1., 1., 1.])
# [1. 1. 1. 1. 1.]
a = np.ones(5)
print(a)
b = torch.from_numpy(a)
print(b)
# [1. 1. 1. 1. 1.]
# tensor([1., 1., 1., 1., 1.], dtype=torch.float64)
a
跟 Numpy b
会共享同一个 memory address ,所以操作会被同步,要特别注意==
a.add_(1)
print(a)
print(b)
# tensor([2., 2., 2., 2., 2.])
# [2. 2. 2. 2. 2.]
a += 1
print(a)
print(b)
# [2. 2. 2. 2. 2.]
# tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
torch.cuda.is_available()
来检查是否可以使用 GPU cuda
if torch.cuda.is_available():
device = torch.device("cuda")
x = torch.ones(5, device=device)
y = torch.ones(5)
y = y.to(device)
z = x + y
print(z)
z = z.to("cpu")
z = z.numpy()
今天介绍的State Pattern与昨天的Strategy Pattern非常的相似,不过它们...
我们今天终於要进到Flutter的世界,大家应该都准备好了吧!还没安装完成的小夥伴也不要紧张,可以参...
In this series, I want to introduce some concepts ...
DBA Bootcamp 前一阵子,发现一台 SQL Server 的 compute 效能好像不如...
今日练习档 ԅ( ¯་། ¯ԅ) 大家好呀 ٩(ˊ〇ˋ*)و 列印我相信也是很多人会使用的一个功能,...