PyTorch-基本數據操作(Numpy)

PyTorch-基本數據操作(Numpy)

硬件:NVIDIA-GTX1080

軟件:Windows7、python3.6.5、pytorch-gpu-0.4.1

一、基礎知識

1、Torch 爲神經網絡界的 Numpy,torch.from_numpy() torch_data.numpy() 即可完成torch數據和numpy數據的相互轉化

2、Torch 浮點數接收方式,torch.FloatTensor(),數據計算方式和numpy相似,如abs, sin, mean...

3、Torch 矩陣點乘方式,torch.mm(tensor, tensor),與numpy.matmul(data, data) 類似

二、代碼展示

Example1:

import torch
import numpy as np

np_data = np.arange(6).reshape((2, 3))
torch_data = torch.from_numpy(np_data)
tensor2array = torch_data.numpy()
print(
    '\nnumpy array:', np_data,          # [[0 1 2], [3 4 5]]
    '\ntorch tensor:', torch_data,      #  0  1  2 \n 3  4  5    [torch.LongTensor of size 2x3]
    '\ntensor to array:', tensor2array, # [[0 1 2], [3 4 5]]
)

Example2:

import torch
import numpy as np

# abs 絕對值計算
data = [-1, -2, 1, 2]
tensor = torch.FloatTensor(data)  # 轉換成32位浮點 tensor
print(
    '\nabs',
    '\nnumpy: ', np.abs(data),          # [1 2 1 2]
    '\ntorch: ', torch.abs(tensor)      # [1 2 1 2]
)

# sin   三角函數 sin
print(
    '\nsin',
    '\nnumpy: ', np.sin(data),      # [-0.84147098 -0.90929743  0.84147098  0.90929743]
    '\ntorch: ', torch.sin(tensor)  # [-0.8415 -0.9093  0.8415  0.9093]
)

# mean  均值
print(
    '\nmean',
    '\nnumpy: ', np.mean(data),         # 0.0
    '\ntorch: ', torch.mean(tensor)     # 0.0
)

Example3:

import torch
import numpy as np

# matrix multiplication 矩陣點乘
data = [[1,2], [3,4]]
tensor = torch.FloatTensor(data)  # 轉換成32位浮點 tensor
# correct method
print(
    '\nmatrix multiplication (matmul)',
    '\nnumpy: ', np.matmul(data, data),     # [[7, 10], [15, 22]]
    '\ntorch: ', torch.mm(tensor, tensor)   # [[7, 10], [15, 22]]
)

三、參考:

https://morvanzhou.github.io/

 

任何問題請加唯一QQ2258205918(名稱samylee)!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章