torch.from_numpy()
轉換成torch的tensor資料
torch_data.numpy()
把torch資料轉換為numpy資料
import torch
import numpy as np
# 把numpy資料轉換為torch資料
np_data = np.arange(6).reshape(2, 3)
torch_data = torch.from_numpy(np_data) # 轉換成torch的tensor資料
# 把torch資料轉換為numpy資料
tensor2array = torch_data.numpy()
print(
'\nnumpy', np_data,
'\ntorch', torch_data,
'\ntensor2array', tensor2array,
)
運行結果:

numpy求絕對值:np.abs(data)
torch求絕對值:torch.abs(tensor)
numpy求sin:np.sin(data)
torch求sin:torch.sin(tensor)
numpy求均值:np.mean(data)
torch求均值:torch.mean(tensor)
import torch
import numpy as np
# abs
data = [-1, -2, 1, 2]
tensor = torch.FloatTensor(data) # 轉換為32bit的tensor浮點型
print(
'\nnbs',
'\nnumpy:', np.abs(data), # [1 2 1 2]
'\ntorch:', torch.abs(tensor) # [1 2 1 2]
)
# sin
print(
'\nsin',
'\nnumpy:', np.sin(data), # [1 2 1 2]
'\ntorch:', torch.sin(tensor) # [1 2 1 2]
)
# mean
print(
'\nmean',
'\nnumpy:', np.mean(data), # [1 2 1 2]
'\ntorch:', torch.mean(tensor) # [1 2 1 2]
)
運算結果:

numpy矩陣的乘法:np.matmul(data1, data1)
torch張量形式矩陣的乘法:torch.mm(tensor1, tensor1)
import torch
import numpy as np
# 矩陣形式的運算
data1 = [[1, 2], [3, 4]]
tensor1 = torch.FloatTensor(data1)
print(
'\nnumpy:', np.matmul(data1, data1),
'\ntorch:', torch.mm(tensor1, tensor1)
)
運行截圖:

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/251682.html
標籤:AI
