1 Pytorch的安裝
1.1 Pytorch的介紹
Pytorch是一款facebook發佈的深度學習框架,由其易用性,友好性,深受廣大用戶青睞。
1.2 Pytorch的安裝
安裝地址介紹:https://pytorch.org/get-started/locally/
import torch
torch.__version__
2 Pytorch中數據-張量
2.1 張量Tensor 張量是一個統稱,其中包含很多類型:
0階張量:標量、常數,
1階張量:向量,
2階張量:矩陣,
3階張量
...
N階張量
2.2 Pytorch中創建張量
a.從已有的數據中創建張量
b.從列表中創建
torch.tensor([[1., -1.], [1., -1.]])
tensor([[ 1.0000, -1.0000], [ 1.0000, -1.0000]])
c.使用numpy中的數組創建tensor
torch.tensor(np.array([[1, 2, 3], [4, 5, 6]]))
tensor([[ 1, 2, 3], [ 4, 5, 6]])
d.創建固定張量
torch.ones([3,4])
e. 創建3行4列的全爲1的tensor
torch.zeros([3,4])
f. 創建3行4列的全爲0的tensor
torch.ones_like(tensor) torch.zeros_like(tensor) 創建與tensor相同形狀和數據類型的值全爲1/0的tensor
g.torch.empty(3,4) 創建3行4列的空的tensor,會用無用數據進行填充(手工填充torch.fill_)
h.在一定範圍內創建序列張量
a. torch.arange(start, end, step) 從start到end以step爲步長取值生成序列
b. torch.linspace(start, end, number_steps) 從start到end之間等差生成number_steps個數字組成序列
c. torch.logspace(start, end, number_steps, base=10)在start到end之間等比生成number_steps個數字組成序列
i.創建隨機張量
a. torch.rand([3,4]) 創建3行4列的隨機值的tensor,隨機值的區間是[0, 1)
>>> torch.rand(2, 3)
tensor([[ 0.8237, 0.5781, 0.6879],
[ 0.3816, 0.7249, 0.0998]])
b. torch.randint(low=0,high=10,size=[3,4]) 創建3行4列的隨機整數的tensor,隨機值的區間是[low, high)
>>> torch.randint(3, 10, (2, 2))
tensor([[4, 5], [6, 7]])
c. torch.randn([3,4]) 創建3行4列的隨機數的tensor,隨機值的分佈式均值爲0,方差爲1
2.3 Pytorch中tensor的屬性
a. 獲取tensor中的數據
tensor.item() 當tensor中只有一個元素時
tensor.numpy() 轉化爲numpy數組
b.獲取形狀:tensor.size() tensor.shape
c.獲取數據類型 tensor.dtype
d.獲取階數: tensor.dim()
2.4 tensor的修改
a.形狀改變:
tensor.view((3,4)) 類似numpy中的reshape
tensor.t() 或 tensor.transpose(dim0, dim1) 轉置
tensor.permute() 變更tensor的軸(多軸轉置)
tensor.unsqueeze(dim) tensor.squeeze() 填充或者壓縮維度
tensor.squeeze() 默認去掉所有長度是1的維度,也可以填入維度的下標,指定去掉某個維度
b.類型的指定或修改 創建數據的時候指定類型
torch.ones([2,3],dtype=torch.float32)
c.改變已有tensor的類型
a.type(torch.float)
a.double()
a.類型()
d.tensor的切片
x[:,1] 第二列所有值
e.切片賦值
x[:,1] = 1
注意:切片數據內存不連續
本作品採用知識共享署名-非商業性使用-相同方式共享 4.0 國際許可協議進行許可,轉載請附上原文出處鏈接和本聲明。
本文鏈接地址:https://www.flyai.com/article/art9df0377c91b48f5b4eab3bf5