---
tags: PyTorch, Python
---
# Pytorch 建立Tensor
### 1. 從`numpy`
> ```python
> a = np.array([[1, 2, 3], [0.1, 0.2, 0.3]])
> '''
> [[1. 2. 3. ]
> [0.1 0.2 0.3]]
> '''
> ```
> ```python
> torch.from_numpy(a)
> '''
> tensor([[1.0000, 2.0000, 3.0000],
> [0.1000, 0.2000, 0.3000]], dtype=torch.float64)
> '''
> ```
### 2. 從`List`創建
> ```python
> torch.FloatTensor([1, 2, 3, 4, 5])
> '''
> tensor([1., 2., 3., 4., 5.])
> '''
> ```
> ```python
> torch.IntTensor([1, 2, 3, 4, 5])
> '''
> tensor([1, 2, 3, 4, 5], dtype=torch.int32)
> '''
> ```
> ```python
> torch.tensor([6, 5, 4, 3, 2])
> '''
> tensor([6, 5, 4, 3, 2])
> '''
> ```
### 3. 創建指定大小的`Tensor`
> ```python
> torch.empty(1, 2)
> '''
> tensor([[2.3694e-38, 1.4013e-45]])
> '''
> ```
> ```python
> torch.FloatTensor(3, 3)
> '''
> tensor([[8.4078e-45, 0.0000e+00, 7.0065e-45],
> [0.0000e+00, 5.6052e-45, 0.0000e+00],
> [4.2039e-45, 0.0000e+00, 2.8026e-45]])
> '''
> ```
### 4. 修改預設`Tensor`類型
> ```python
> print(torch.tensor([1.1, 2.2]).type())
> torch.set_default_tensor_type(torch.DoubleTensor)
> print(torch.tensor([1.1, 2.2]).type())
> '''
> torch.FloatTensor
> torch.DoubleTensor
> '''
> ```
### 5. 隨機值的`Tensor`
> ```python
> a = torch.rand(2, 2)
> '''
> tensor([[0.7367, 0.6800],
> [0.7643, 0.5405]])
> '''
> b = torch.rand_like(a) # 把 a 的 Shape 傳入 b
> '''
> tensor([[0.7268, 0.6479],
> [0.4025, 0.5840]])
> '''
> ```
> ```python
> torch.randint(1, 5, [3, 3])
> '''
> tensor([[3, 4, 3],
> [2, 2, 2],
> [3, 3, 4]])
>
> '''
> torch.randn(2, 2)
> '''
> tensor([[-1.1463, 0.2805],
> [ 1.0364, 0.7610]])
> '''
> ```
### 6. 創建同一個值的`Tensor`
> ```python
> torch.full([2, 2], 10)
> '''
> tensor([[10, 10],
> [10, 10]])
> '''
> ```
### 7. 指定平均值和標準差
> ```python!
> torch.normal(mean=torch.full([10], 0), std=torch.arange(1, 0, -0.1))
> ```
### 8. 創建`arange`
> ```python
> torch.arange(0, 10, 2)
> '''
> tensor([0, 2, 4, 6, 8])
> '''
> ```
### 9. 創建`linspace`
> ```python
> torch.linspace(0, 10, 5) # 在 0 ~ 10 生成 5 個數字
> '''
> tensor([ 0.0000, 2.5000, 5.0000, 7.5000, 10.0000])
> '''
> ```