本文介紹了PyTorch中的Tensor類,它相似於Numpy中的ndarray,它構成了在PyTorch中構建神經網絡的基礎。編程
咱們已經知道張量究竟是什麼了,而且知道如何用Numpy的ndarray來表示它們,如今咱們看看如何在PyTorch中表示它們。網絡
自從Facebook在2017年初將PyTorch開源以來,它已經在機器學習領域取得了使人矚目的成績。它可能沒有像TensorFlow那樣被普遍採用 --- 它的最初發布時間早於PyTorch一年,背後有Google的支持,而且當神經網絡工具迎來新的潮流時,它已經將本身確立爲了金牌標準。但PyTorch在研究領域受到了普遍的關注,這種關注大部分來自與Torch自己的關係,以及它的動態計算圖。dom
儘管最近個人注意力都在PyTorch上,但這篇文章並非PyTorch的教程。它更多地是介紹PyTorch的Tensor類,這與Numpy的ndarray相似。機器學習
張量基礎工具
讓咱們來看一下PyTorch的張量基礎知識,從建立張量開始(使用Tensor類):學習
import torch # Create a Torch tensor t = torch.Tensor([[1, 2, 3], [4, 5, 6]]) t tensor([[ 1., 2., 3.], [ 4., 5., 6.]])
你可使用兩種方式轉置一個張量:code
# Transpose t.t() # Transpose (via permute) t.permute(-1,0)
二者都會產生以下輸出結果:orm
tensor([[ 1., 4.], [ 2., 5.], [ 3., 6.]])
請注意,兩種方式都不會致使原始張量的改變。對象
用view從新塑造張量:blog
# Reshape via view t.view(3,2) tensor([[ 1., 2.], [ 3., 4.], [ 5., 6.]])另外一個例子:
# View again... t.view(6,1) tensor([[ 1.], [ 2.], [ 3.], [ 4.], [ 5.], [ 6.]])很明顯,Numpy所遵循的數學約定延續到了PyTorch張量中(我具體指的是行和列的標記符號)。
建立一個張量並用零填充(你能夠用ones()來完成相似的操做):
# Create tensor of zeros t = torch.zeros(3, 3) t tensor([[ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.]])從正態分佈中隨機取數並建立張量:
# Create tensor from normal distribution randoms t = torch.randn(3, 3) t tensor([[ 1.0274, -1.3727, -0.2196], [-0.7258, -2.1236, -0.8512], [ 0.0392, 1.2392, 0.5460]])
Tensor對象的形狀、維度和數據類型:
# Some tensor info print('Tensor shape:', t.shape) # t.size() gives the same print('Number of dimensions:', t.dim()) print('Tensor type:', t.type()) # there are other types Tensor shape: torch.Size([3, 3]) Number of dimensions: 2 Tensor type: torch.FloatTensor除了在數學概念上,ndarray和Tensor在編程和實例化上也有類似之處。
你能夠像切片ndarrays同樣切片PyTorch張量,任何使用其餘Python結構的人應該都熟悉這一點: