张量基础

import torch
import numpy as np

(0,1)均匀分布

x = torch.rand(3, 4)
x

正态分布

x = torch.randn(2, 6)
x

全0数组

x = torch.zeros(4, 7)
x

全1数组

x = torch.ones((2, 3, 4), dtype=torch.int32)
x

查看数据维度

x.size()
x.shape
x.size(1)

通过数组创建张量

x = torch.tensor([3, 4, 5], dtype=torch.float64)
x
x.type()

数据类型转换

x.type(torch.int32)

tensor和ndarray类型转换

a = np.random.randn(2, 3)
a

从ndarray转变为tensor

x = torch.from_numpy(a)
x

从tensor转变为ndarray

x.numpy()
x2 = torch.rand(2, 3)
x2

向量相加

x + x2

广播

x2 + 6

原来元素没有改变

x.add(x2)

原来元素发生改变

x.add_(x2)
x.shape

改变张量维度

x.view(3, 2)
x.view(-1, 1)

求平均数

x.mean()

求和

x = x.sum()
x

返回标量

x.item()

张量的自动微分

x = torch.ones(2, 2, requires_grad=True)
x

是否跟踪张量操作

x.requires_grad

张量的值

x.data

张量的梯度

x.grad

是由什么操作得到

x.grad_fn
y = x + 2
y
y.grad_fn
z = y * y + 8
z
out = z.mean()
out

计算张量的微分

out.backward()
x.grad
x.data

不跟踪梯度

with torch.no_grad():
    print((x**2).requires_grad)

跟踪梯度

(x**2).requires_grad

不跟踪梯度(等价于with torch.no_grad():)

y = x.detach()
y
y.requires_grad

如何将张量修改成跟踪梯度

a = torch.tensor([4, 6], dtype=torch.float32)
a.requires_grad
a.requires_grad_(True)
a

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 2621041184@qq.com