数据操作

1 import torch
2
3 torch.manual_seed(0)
4 torch.cuda.manual_seed(0)
5 print(torch.__version__)  # 1.3.1

创建tensor

1 # 创建一个5x3的未初始化的tensor
2 x = torch.empty(5, 3)
3 print(x)
4
5 # tensor([[1.3563e-19, 1.3563e-19, 7.9717e-10],
6 #        [5.8270e-10, 5.8270e-10, 4.9153e-14],
7 #        [1.3563e-19, 1.8578e-01, 3.9157e-02],
8 #        [4.7429e+30, 2.2639e+35, 1.8971e+31],
9 #        [1.4587e-19, 1.1703e-19, 1.5637e-01]])
# 随机初始化的tensor
x = torch.rand(5, 3)
print(x)

# tensor([[0.4963, 0.7682, 0.0885],
#         [0.1320, 0.3074, 0.6341],
#         [0.4901, 0.8964, 0.4556],
#         [0.6323, 0.3489, 0.4017],
#         [0.0223, 0.1689, 0.2939]])
# 创建一个long型全0的tensor
x = torch.zeros(5, 3, dtype=torch.long)
print(x)
# tensor([[0, 0, 0],
#         [0, 0, 0],
#         [0, 0, 0],
#         [0, 0, 0],
#         [0, 0, 0]])
# 直接数据初始化
x = torch.tensor([5.5, 3])
print(x)

# tensor([5.5000, 3.0000])
# 通过现有的tensor来创建
x = x.new_ones(5, 3, dtype=torch.float64) # 返回的tensor默认具有相同的torch.dtype和torch.device
print(x)

x = torch.randn_like(x, dtype=torch.float) # 指定新的数据类型
print(x)

# tensor([[1., 1., 1.],
#         [1., 1., 1.],
#         [1., 1., 1.],
#         [1., 1., 1.],
#         [1., 1., 1.]], dtype=torch.float64)
# tensor([[ 0.6035,  0.8110, -0.0451],
#         [ 0.8797,  1.0482, -0.0445],
#         [-0.7229,  2.8663, -0.5655],
#         [ 0.1604, -0.0254,  1.0739],
#         [ 2.2628, -0.9175, -0.2251]])
# 通过shape或size()来获取tensor形状
print(x.size())
print(x.shape)
# torch.Size([5, 3])
# torch.Size([5, 3])

运算 

# 加法1:
y = torch.rand(5, 3)
print(x + y)
# 加法2:
print(torch.add(x, y)) 
# 指定输出
result = torch.empty(5, 3)
torch.add(x, y, out=result)
print(result)
# 加法3:inplace
# adds x to y
y.add_(x)
print(y)

索引

attension:索引出来的结果与原数据共享内存,即修改一个,另一个也被修改了

y = x[0, :] # 矩阵x的第一行
y += 1
print(y)
print(x[0, :]) # 原tensor也被修改了
# 改变形状 view()
y = x.view(15)
z = x.view(-1, 5)
print(x.size(), y.size(), z.size())

attension: view()返回的新tensor与原tensor共享内存

# 若不想共享内存,先用clone创造一个副本,再用view
x_cp = x.clone().view(15)
x -= 1
print(x)
print(x_cp)
# item()函数将一个标量tensor转换为一个Python number
x = torch.randn(1)
print(x)
print(x.item())

广播机制

# 两个不同形状tensor可能会引起广播机制
x = torch.arange(1, 3).view(1, 2)
print(x)
y = torch.arange(1, 4).view(3, 1)
print(y)
print(x + y)

tensor和NumPy相互转换

 numpy()和from_numpy()产生的tensor和NumPy array实际使用的相同的内存

# tensor --> numpy
a = torch.ones(5)
b = a.numpy()
print(a, b)

a += 1
print(a, b)
b += 1
print(a, b)
# numpy --> tensor
import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)
print(a, b)

a += 1
print(a, b)
b += 1
print(a, b)
# 直接用torch.tensor()将NumPy数组转换成tensor,该方法是将数据拷贝,返回的tensor和原来的数据不再共享内存
# 用torch.tensor()转换时不会共享内存
c = torch.tensor(a)
a += 1
print(a, c)

测试是否是GPU版的Pytorch

# 只会在GPU版本运行
if torch.cuda.is_available():
    device = torch.device("cuda")   # GPU
    y = torch.ones_like(x, device=device)  # 创建一个在GPU上的tensor
    x = x.to(device)    # 等价与x.to("cuda")
    z = x + y
    print(z)
    print(z.to("cpu", torch.double))
12-27 14:08