pytorch使用-tensor基本操作
一、tensor加减乘除
加法操作
import torch
x = torch.randn(2, 3)
y = torch.randn(2, 3)
z = x + y
print(z)
z = torch.add(x, y)
print(z)
y.add_(x)
print(y)
其他操作类似:减法:sub(-), 乘法:mul(*), 除法:div(/)
二、tensor矩阵运算
a = torch.full([2, 2], 3, dtype=torch.long)
b = torch.ones(2, 2, dtype=torch.long)
print(a)
print(b)
print(torch.mm(a, b))
a = torch.rand(1, 1, 3, 2)
b = torch.rand(1, 1, 2, 4)
c = torch.matmul(a, b)
print(a)
print(b)
print(c)
pow
a = torch.full([2, 2], 6)
print(a.pow(3))
a = torch.full([2, 2], 6)
print(a**2)
sqrt: 平方根
rsqrt: 平方根倒数
a = torch.full([2, 2], 1024)
print(a.sqrt())
print(a.rsqrt())
print(a**0.5)
exp log
a = torch.ones(2, 2)
print(torch.exp(a))
print(torch.log(a))
print(torch.log2(a))
.floor()——往下近似
.ceil()——往上近似
.trunc()——裁剪为整数部分
.frac()——裁剪成小数部分
a = torch.tensor(3.1415926)
print(a.floor())
print(a.ceil())
print(a.trunc())
print(a.frac())
torch.round()——四舍五入
a = torch.tensor(3.1415926)
print(a.round())
.item() 转化为python number
x = torch.randn(1)
print(x)
print(x.item())
四、tensor切片操作
a = torch.randn(4, 3)
print(a)
print(a[:, 1])
print(a[:, :2])
五、tensor改变形状
x = torch.randn(4, 4)
y = x.view(16)
z = x.view(-1, 8)
print(x)
print(y)
print(z)
六、tensor 和 numpy.array相互转换
x = torch.ones(5)
print(x)
y = x.numpy()
print(y)
x.add_(1)
print(y)
import numpy as np
x = np.ones(5)
y = torch.from_numpy(x)
print(y)
七、tensor 转到GPU上
if torch.cuda.is_available():
device = torch.device("cuda")
x = torch.randn(2, 3)
print(x)
y = x.to(device)
print(y)
z = torch.randn(2, 3, device="cuda")
print(z)
print(y + z)
print(z.to("cpu"))
Original: https://blog.csdn.net/xu624735206/article/details/123929030
Author: 大虾飞哥哥
Title: pytorch使用-tensor基本操作
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/758250/
转载文章受原作者版权保护。转载请注明原作者出处!