torch.from_numpy()
Tensor data converted to torch
torch_data.numpy()
Convert torch data to numpy data
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,
)
operation result:
numpy for absolute value: np.abs(data)
torch finds the absolute value: torch.abs(tensor)
numpy 求 sin : np.sin (data)
torch求sin:torch.sin(tensor)
numpy average: np.mean(data)
torch average: 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]
)
Calculation result:
Multiplication of numpy matrix: np.matmul(data1, data1)
Multiplication of torch tensor form matrix: 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)
)
Run screenshot: