官术网_书友最值得收藏!

Basic building blocks

Such as TensorFlow, PyTorch represents data in tensor form. Torch tensors are defined as standard data types, such as torch.FloatTensor() , torch.charTensor(), and torch.intTensor(). As mentioned, operations in PyTorch are highly Pythonic. To repeat the exact same multiplication operation that we performed in preceding TensorFlow: 

import torch 
x = torch.IntTensor([4])
y = torch.IntTensor([5])
product = x * y

As a result of it native Python feel, PyTorch allows for easy interaction between standard numpy arrays and PyTorch tensors. It's easy to switch back and forth between the two:

import torch 
import numpy as np

## Create a numpy array
numpy_array = np.random.randn(20,20)

##Convert the numpy array to a pytorch tensor
pytorch_tensor = torch.from_numpy(numpy_array)

## Convert it back to Numpy
numpy_again = pytorch_tensor.numpy()

PyTorch tensors can easily be indexed and sliced in a Pythonic way as well. For instance, let's say that we want to access a particular value of a tensor in PyTorch; we can easily do that with NumPy-like indexing: 

tensor = torch.FloatTensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

## print the third element of the 2nd row of the tensor
print(tensor[1][2])

Likewise, we can easily manipulate the contents of the tensor in a NumPy-like manner:

## replace the second value of the first tensor
tensor[0][1] = 1
print(tensor)

Like TensorFlow, PyTorch runs on the concept of variables, which are values that are intended to change and be updated during training processes. To create a variable in PyTorch, we wrap a tensor with the Variable function:

from torch.autograd import Variable
tensor_two = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
variable = Variable(tensor_two)

If you'd like to gain access to the tensor that's inside of the variable wrapper, you can call .data on the variable:

variable.data

## Returns:
tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

While PyTorch is relatively new and still developing, its Python-like structure is leading to fast adoption rates in the community. 

主站蜘蛛池模板: 诸城市| 精河县| 怀集县| 扎赉特旗| 闽侯县| 瑞昌市| 长乐市| 隆尧县| 牙克石市| 东乌珠穆沁旗| 顺平县| 固原市| 弥渡县| 定安县| 阿荣旗| 马尔康县| 筠连县| 宁远县| 子长县| 格尔木市| 台东县| 资中县| 兴和县| 平顶山市| 青海省| 荥阳市| 元江| 平度市| 达尔| 阳城县| 高陵县| 石林| 莒南县| 富平县| 格尔木市| 镇安县| 泰顺县| 砀山县| 济南市| 开远市| 综艺|