pytorch教程之Tensor的值及操作使⽤学习⽬录
1、Tensors
建⽴5*3的矩阵,未初始化
建⽴随机初始化矩阵
建⽴零初始化矩阵,数据类型是Long
建⽴⼀个tensor数据来源于data
获取tensor的size
2、对Tensor的操作
实现加法的四种⽅式
所有原地替换
使⽤标准的numpy操作
使⽤torch.view 改变tensor的形状
tensor转化为numpy的数字,使⽤item
Torch Tensor 和numpy的相互转换
将numpy array转化为pytorch Tensor
CUDA Tensors
1、Tensors
Tensors are similar to NumPy's ndaeeays,不同的是可以在GPU上使⽤和加速计算。
导⼊包
from __future__ import print_function
import torch
建⽴5*3的矩阵,未初始化numpy最详细教程
x = pty(5,3)
print(x)
out
tensor([[ 1.4395e-36,  4.5848e-41,  1.4395e-36],
[ 4.5848e-41,  1.4395e-36,  4.5848e-41],
[ 1.4395e-36,  4.5848e-41,  2.8026e-45],
[-1.9501e+00,  8.5165e+23,  0.0000e+00],
[ 2.5223e-43,  0.0000e+00,  0.0000e+00]])
建⽴随机初始化矩阵
x = torch.rand(5,3)
print(x)
out
tensor([[ 0.8074,  0.9175,  0.8109],
[ 0.3313,  0.5902,  0.9179],
[ 0.6562,  0.3283,  0.9798],
[ 0.8218,  0.0817,  0.4454],
[ 0.5934,  0.0040,  0.3411]])
建⽴零初始化矩阵,数据类型是Long
...
x = s(5,3,dtype = torch.long)
print(x)
...
out
tensor([[ 0,  0,  0],
[ 0,  0,  0],
[ 0,  0,  0],
[ 0,  0,  0],
[ 0,  0,  0]])
建⽴⼀个tensor数据来源于data
x = sor([5.5,3])
print(x)
out
tensor([ 5.5000,  3.0000])
在原有tnesor的基础上形成新的tensor,会继承原有tensor的shapee和dtype等属性,当然我么也可以修改这些属性x = x.new_ones(5,3,dtype = torch.double)
print(x)
x = torch.randn_like(x,dype = torch.float)
print(x)
out
tensor([[ 1.,  1.,  1.],
[ 1.,  1.,  1.],
[ 1.,  1.,  1.],
[ 1.,  1.,  1.],
[ 1.,  1.,  1.]], dtype=torch.float64)
tensor([[-0.0730, -0.0716, -0.8259],
[-1.7004,  0.8790, -0.0659],
[-0.8969,  0.8736, -0.6035],
[-0.1539, -2.9178, -0.7456],
[-0.0245,  0.4075,  1.4904]])
获取tensor的size
print(x.size())
out
torch.Size([5, 3])
torch.size是⼀个元组,⽀持所有元组(tuple)的操作
2、对Tensor的操作
实现加法的四种⽅式
⽅法⼀L
print(x+y)
⽅法⼆
print(torch.add(x,y))
⽅法三:输出给额外的tensor
result = pty(5,3)
torch.add(x,y ,out= result)
print (result)
⽅法四:原地替换-结果存放在y中
print(y)
所有原地替换
所有原地替换tensor的操作都有后缀,⽐如x.copy(y),会改变x
使⽤标准的numpy操作
print(x[:1]
out
tensor([-0.0716,  0.8790,  0.8736, -2.9178,  0.4075])
使⽤torch.view 改变tensor的形状
x = torch.randn(4,4)
y = x.view(16)
z = x.view(-1,8)  # the size -1 is inferred from other dimensions
print (x.size(),y.xize(),z.size())
out
torch.Size([4, 4]) torch.Size([16]) torch.Size([2, 8])
tensor转化为numpy的数字,使⽤item
x = adn(1)
print(x)
print(x.item())
Torch Tensor 和numpy的相互转换
a = s(5)
print (a)
out
tensor([ 1.,  1.,  1.,  1.,  1.])
并且改变tensor的值会同时改变numpy的值
a.add_(1)
print(a)
print(b)
out
tensor([ 2.,  2.,  2.,  2.,  2.])
[ 2.  2.  2.  2.  2.]
将numpy array转化为pytorch Tensor
import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)
np.add(a,1,out = a )
print(a)
print(b)
out
[ 2.  2.  2.  2.  2.]
tensor([ 2.,  2.,  2.,  2.,  2.], dtype=torch.float64)
所有在cpu上的tensor都⽀持numpy转化,除了char形的tensor CUDA Tensors
Tensors 可以被移动到其他设备使⽤.to的⽅法
...
if torch.cuda.is_avaulable():
device = torch.device(“cuda”)
y = s_like(x,device = devcie)
x= x.to(device)
z = x+y
print(z)
(“cpu”,torch.double))
...
out
tensor([-1.0620], device='cuda:0')
tensor([-1.0620], dtype=torch.float64)
以上就是pytorch教程之Tensor学习笔记的详细内容,更多关于pytorch教程的资料请关注其它相关⽂章!