pytorch学习笔记(一)

from future import print_function # 必须放在程序开头
import torch

x = torch.empty(5, 3) # 创建未初始化矩阵

print(x)

x = torch.rand(5, 3) # 创建一个随机初始化矩阵

print(x)

构造一个填满0且数据类型为long的矩阵

x = torch.zeros(5, 3, dtype=torch.long)

print(x)

直接从数据构造张量

x = torch.tensor([5.5, 3])

print(x)

x = x.new_ones(5, 3, dtype=torch.double) # new_* methods take in sizes

print(x)

x = torch.randn_like(x, dtype=torch.double) # 重载 dtype!

print(x) # 结果size一致

运算

y = torch.rand(5, 3)

print(x + y)

print(torch.add(x, y))

加法:给定一个输出张量作为参数

result = torch.empty(5, 3)

print(result)

torch.add(x, y, out=result)

print(torch.add(x, y))

print(torch.add(x, y, out=result))

print(result)

加法:原位/原地操作(in-place)

adds x to y

y.add_(x)

print(y)

print(y[:, 1])

print(y[1, :])

改变形状

x = torch.randn(4, 4)

print(x)

y = x.view(16)
z = x.view(-1, 8) # the size -1 is inferred from other dimensions

print(x.size(), y.size(), z.size())

print(z)

如果是仅包含一个元素的tensor,可以使用.item()来得到对应的python数值

x = torch.randn(1)

print(x)

print(x.item())

tensor 和 numpy数组内存的公用

a = torch.ones(5)

print(a)

b = a.numpy()

print(b)

a.add_(1)

print(a)

print(b)

numpy数组转为torch张量

import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)
np.add(a, 1, out=a)

print(a)

print(b)

当GPU可用时,我们可以运行以下代码

我们将使用torch.device来将tensor移入和移出GPU

if torch.cuda.is_available():
device = torch.device(“cuda”) # a CUDA device object
y = torch.ones_like(x, device=device) # 直接在GPU上创建tensor
x = x.to(device) # 或者使用.to("cuda")方法
z = x + y
print(z)
print(z.to(“cpu”, torch.double)) # .to也能在移动时改变dtype

你可能感兴趣的:(python学习杂记,深度学习,python)