美文网首页机器学习与计算机视觉
PyTorch入门学习(一):What is PyTorch?

PyTorch入门学习(一):What is PyTorch?

作者: 与阳光共进早餐 | 来源:发表于2018-01-05 20:22 被阅读1429次

未经允许,不得转载,谢谢~~

PyTorch是一个深度学习的框架。
简单记录整理。

Pytorch是什么

基于Python的科学计算包:

  • 代替numpy能使用GPU进行计算
  • 灵活性很高的一个深度学习研究平台

Tensor的基本用法

Tensor(张量)跟numpy的数组很像,但是它可以使用GPU来进行计算的加速。

import packet

from __future__ import print_function
import torch

Construct a 5x3 matrix, uninitialized:

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

Construct a randomly initialized matrix

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

Get its size

print(x.size())

torch.Size本质是元祖tuple

addition of Tensors

以下的运行结果都是一样的。

x=torch.rand(5,3)
y=torch.rand(5,3)
# syntax 1
print(x + y)
# syntax 2
print(torch.add(x, y))
# syntax 3 - giving an output tensor
result = torch.Tensor(5, 3)
torch.add(x, y, out=result)
print(result)
# syntax 4 - in-place
y.add_(x)
print(y)

numpy-like indexing

像numpy一样的用法来索引。

print(x[:, 1])

numpy array 与 torch Tensor的相互转换

  • 这里的转换相对应的array与Tensor共享同一块内存,改变一个也会改变另外一个。
  • 所有还在CPU上运行的Tensor除了CharTensor之外都支持与numpy Array的相互转化。

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

用.cuda函数可以讲张量移到GPU上

if torch.cuda.is_available():
   print ("succ")
    x = x.cuda()
    y = y.cuda()
    x + y

more

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

基本就是对官网的getting started的一个小小翻译,能力有限,权当自己做笔记吧~~~

相关文章

网友评论

    本文标题:PyTorch入门学习(一):What is PyTorch?

    本文链接:https://www.haomeiwen.com/subject/lqgsnxtx.html