1. 什么是tensor
在神經(jīng)網(wǎng)絡(luò)的計(jì)算中,數(shù)據(jù)都是以tensor(張量)的形式進(jìn)行傳遞和運(yùn)算的.
tensor是對(duì)一類數(shù)學(xué)概念的一個(gè)概括:
- 0維tensor = 數(shù)字 = 標(biāo)量
- 1維tensor = 序列 = 向量
- 2維tensor = 2維序列 = 矩陣
- ……
- n維tensor = n維序列
其中n也代表了訪問tensor中某個(gè)元素所需要的indexs的數(shù)量,例如對(duì)于一個(gè)2維的tensor:
a = [
[1, 2],
[3, 4]
]
當(dāng)我們想要訪問3這個(gè)元素時(shí)候需要輸入:
a[1][0]
3
可以看到,需要2個(gè)indexs.
2. pytorch生成tensor
- 可以使用torch的construct function 和factory function 生成
import torch
import numpy as np
data = np.array([1, 2, 3])
print(type(data)) # <class 'numpy.ndarray'>
print(torch.Tensor(data)) # tensor([1., 2., 3.]) construct function copy
print(torch.tensor(data)) # tensor([1, 2, 3]) factory function copy mostly used
print(torch.as_tensor(data)) # tensor([1, 2, 3]) factory function share
print(torch.from_numpy(data)) # tensor([1, 2, 3]) factory function share
output:
<class 'numpy.ndarray'>
tensor([1., 2., 3.])
tensor([1, 2, 3])
tensor([1, 2, 3])
tensor([1, 2, 3])
以上幾種生成方式的區(qū)別如下:
- torch.Tensor()屬于construct function,可以輸入list或numpy.ndarry,tensor的數(shù)據(jù)格式為float,生成的方式為copy,即對(duì)原數(shù)據(jù)進(jìn)行復(fù)制,因此當(dāng)原數(shù)據(jù)改動(dòng)時(shí),生成的tensor不會(huì)隨之改變
- torch.tensor()屬于factory function,可以輸入list或numpy.ndarry,tensor的數(shù)據(jù)格式與輸入數(shù)據(jù)類型相同,生成的方式為copy,即對(duì)原數(shù)據(jù)進(jìn)行復(fù)制,因此當(dāng)原數(shù)據(jù)改動(dòng)時(shí),生成的tensor不會(huì)隨之改變,最常使用
- torch.as_tensor()屬于factory function,可以輸入list或numpy.ndarry,tensor的數(shù)據(jù)格式與輸入數(shù)據(jù)類型相同,生成的方式為share,因此當(dāng)原數(shù)據(jù)改動(dòng)時(shí),生成的tensor也會(huì)隨之改變
- torch.from_numpy()屬于factory function,只能輸入numpy.ndarry,tensor的數(shù)據(jù)格式與輸入數(shù)據(jù)類型相同,生成的方式為share,因此當(dāng)原數(shù)據(jù)改動(dòng)時(shí),生成的tensor也會(huì)隨之改變
- 也可以使用torch的函數(shù)生成特定張量
print(torch.eye(2)) # 生成階數(shù)為2的單位矩陣
print(torch.zeros(2, 2)) # 生成2*2的全0矩陣
print(torch.ones(2, 2)) # 生成2*2的全1矩陣
print(torch.rand(2, 2)) # 生成2*2的隨機(jī)矩陣
output:
tensor([[1., 0.],
[0., 1.]])
tensor([[0., 0.],
[0., 0.]])
tensor([[1., 1.],
[1., 1.]])
tensor([[0.6819, 0.8327],
[0.8718, 0.5971]])
3. tensor的屬性
tensor主要有3個(gè)屬性:rank, axes和shape
- rank: tensor的indexs數(shù)目,axes的數(shù)目,維度,shape的長度
- axes: tensor的軸,一個(gè)axes對(duì)應(yīng)n維tensor的一個(gè)維度,例如2維tensor就有2個(gè)axes,可以形成一個(gè)平面. axes的數(shù)目就等于rank
- shape: tensor的shape用來描述每個(gè)axes的長度,而shape的長度就等于rank(因?yàn)橐枋鰊個(gè)axes的長度)
舉個(gè)栗子:
t = torch.tensor([
[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3]
], dtype=torch.float32)
print(t.shape)
print('rank of tensor: %d' % len(t.shape))
print('number of elements: %d' % torch.tensor(t.shape).prod())
print('number of elements: %d' % t.numel())
output:
torch.Size([3, 4])
rank of tensor: 2
number of elements: 12
number of elements: 12
因?yàn)閠這個(gè)tensor是2維的,rank就是2.
t有2個(gè)axes,第一個(gè)axis的長度為3,第二個(gè)axis為4,因此shape就是(3,4)
最后兩行都可以用來計(jì)算tensor中元素的個(gè)數(shù)