Pytorch学习笔记(1):What is PyTorch?

2020-03-16  本文已影响0人  银色尘埃010

tips:对PyTorch官网60分钟教程的一个翻译,主要是自己记录学习
What is PyTorch?

Pytorch是什么

它是一个基于python的科学计算包,针对两类用户:

Tensors

张量类似于NumPy的ndarrays,此外,张量还可以用于GPU来加速计算。

导入

from __future__ import print_function
import torch

构建一个5*3的矩阵,未初始化(uninitialized)

x = torch.Tensor(5, 3)
print(x)

# print 
tensor([[ 0.0000e+00, -2.0000e+00,  9.1207e+33],
        [ 1.5849e+29,  1.1210e-44,  0.0000e+00],
        [ 0.0000e+00,  0.0000e+00,  0.0000e+00],
        [ 0.0000e+00,  0.0000e+00,  0.0000e+00],
        [ 0.0000e+00,  0.0000e+00,  0.0000e+00]])

构建一个5*3的矩阵,初始化(initialized)

x = torch.rand(5, 3)
print(x)

#print
tensor([[0.8586, 0.6059, 0.1719],
        [0.7450, 0.0525, 0.8670],
        [0.1077, 0.9654, 0.5176],
        [0.4116, 0.4207, 0.9021],
        [0.4519, 0.2707, 0.2742]])

构建一个全0矩阵,而且是 dtype long

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

直接从数据构建或者从numpy

a = np.random.random((5,3))
x = torch.from_numpy(a)
print(x)

x2 = torch.Tensor([1.0,2.0])

获得Tensor的size

print(x.size())

返回一个元祖tuple

Operations: 加法操作

x = torch.rand(5, 3)
y = torch.rand(5, 3)
# syntax1
print(x+y)
# syntax2
print(torch.add(x, y))
# syntax3 给出一个output
result = torch.empty(5, 3)
torch.add(x, y, out=result)
print(result)
# syntax4 : in-place,add x to y
y.add_(x) # 在Pytorch 中大部分xxx_都表示原地操作
print(y)

像Numpy一样对Tensor使用索引

print(x[:, 1])

Resizing: Reshape或者Resize一个Tensor

使用torch.view()

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.size(), z.size())

numpy array 与 torch Tensor的相互转换

Tensor转为array

a = torch.ones(5)
print(a)
# convert from tensor to Array
b = a.numpy()
print(b)

# share the same memory
a.add_(1)
print(a)
print(b)

Array 转为 Tensor

import numpy as np
a = np.ones(5)
# convert from array to Tensor
b = torch.from_numpy(a)
np.add(a, 1, out=a)

# share the same memory
print(a)
print(b)

CUDA Tensors

if torch.cuda.is_available():
    device = torch.device("cuda")          # a CUDA device object
    y = torch.ones_like(x, device=device)  
    x = x.to(device)                      
    z = x + y
    print(z)
    print(z.to("cpu", torch.double)) 

#比较常用的一句话
DEVICE= torch.device("cuda" if torch.cuda.is_available() else "cpu")
x.to(DEVICE)
model.to(DEVICE) 

更多

在Pytorch的文档中可以找到关于Tensor的操作,例如转置, 索引,切片,数学计算等都可以在更多Tensor操作中找到。

上一篇下一篇

猜你喜欢

热点阅读