一、函数
1、
torch.linspace (start, end, steps=100, out=None) → Tensor
返回 start 和 end 之间等间隔 steps 点的一维 Tensor.
输出 是尺寸 steps 为一维 tensor
参数:
start (float) – 点集合的起始值
end (float) – 点集合的结束值
steps (int) – 在 start 和 end 之间的样本数
out (Tensor, 可选) – 输出结果的 Tensor
>>> torch.linspace(3, 10, steps=5)
3.0000
4.7500
6.5000
8.2500
10.0000
[torch.FloatTensor of size 5]
2、
torch.normal(means, std, out=None)
返回一个随机数张量, 随机数从给定平均值和标准差的离散正态分布中抽取.
参数 means 是一个包含每个输出元素的正态分布均值的张量.
参数 std 是一个包含每个输出元素的正态分布标准差的张量.
其中 means 和 std 的形状不需要匹配, 但是每个张量中的元素总数需要相同.
注解:
当形状不匹配时, means 的形状将作为返回输出张量的形状.
参数:
means (Tensor) – 均值
std (Tensor) – 标准差
out (Tensor, 可选) – 输出张量
>>> torch.normal(mean=0.5, std=torch.arange(1, 6))
0.5723
0.0871
-0.3783
-2.5689
10.7893
[torch.FloatTensor of size 5]
3、
torch.randn(sizes, out=None) → Tensor
返回标准正态分布的Tensor
sizes:定义形状
4、
torch.mm (a , b)
矩阵a与矩阵b相乘,a的列数与b的行数相等
或
a.mm(b)
5、
torch.mul(a,b)
矩阵a与矩阵b进行元素相乘,a与b的维度必须相等
6、
torch.clamp(input, min, max, out=None)
将input中的元素压缩至[min,max]
input = min (if input < min)
input = max (if input > max)
input = input (if min < input < max)
7
item()
返回元素的数值,但只能返回一个元素的值
import torch
a=torch.randn(2,3)
b=a[0][0].item()
print(b)
>>>
0.9108635187149048
8、
torch.max(input, dim) 函数
参数:
input是softmax函数输出的一个tensor
dim是max函数索引的维度0/1,0是每列的最大值,1是每行的最大值
二、方法
1.自动求导机制
import torch
x=torch.tensor(1.,requires_grad=True) #新版本需对所需要求梯度的变量
w=torch.tensor(2.,requires_grad=True) #进行requires_grad=True
b=torch.tensor(3.,requires_grad=True)
y=w*x+b #y=2*1+3
y.backward() #对y进行回溯
print(x.grad)
print(w.grad)
print(b.grad)
>>>
tensor(2.)
tensor(1.)
tensor(1.)
x = torch.rand(5, 3)
y = torch.rand(5, 3)
#第一种
print(x + y)
#第二种
print(torch.add(x, y))
#第三种
result = torch.empty(5, 3)
torch.add(x, y, out=result)
print(result)
#第四种
y.add_(x)
print(y)