import torch
import numpy as np
np_data = np.arange(6).reshape((2, 3)) # [[0 1 2], [3 4 5]]
torch_from_numpy = torch.from_numpy(np_data)
numpy_from_torch = torch_from_numpy.numpy()
print('numpy array:', np_data)
print('torch tensor:', torch_from_numpy)
print('tensor to numpy array:', numpy_from_torch)
輸出結果
numpy array: [[0 1 2]
[3 4 5]]
torch tensor: tensor([[0, 1, 2],
[3, 4, 5]], dtype=torch.int32)
tensor to numpy array: [[0 1 2]
[3 4 5]]
data = [-1, -2, -3, -4]
tensor = torch.FloatTensor(data) # 轉換32位元浮點數tensor
print('abs絕對值')
print('numpy: ', np.abs(data))
print('torch: ', torch.abs(tensor))
print('sin三角函數')
print('numpy: ', np.sin(data))
print('torch: ', torch.sin(tensor))
print('mean平均數')
print('numpy: ', np.mean(data))
print('torch: ', torch.mean(tensor))
輸出結果
abs絕對值
numpy: [1 2 3 4]
torch: tensor([1., 2., 3., 4.])
sin三角函數
numpy: [-0.84147098 -0.90929743 -0.14112001 0.7568025 ]
torch: tensor([-0.8415, -0.9093, -0.1411, 0.7568])
mean平均數
numpy: -2.5
torch: tensor(-2.5000)
data = [[1,2], [3,4]]
tensor = torch.FloatTensor(data) # 轉換32位元浮點數tensor
#正確方法
print('matrix multiplication 矩陣相乘')
print('numpy: ', np.matmul(data, data))
print('torch: ', torch.mm(tensor, tensor))
#torch使用dot問題
data = np.array(data)
print('matrix multiplication (使用dot)')
print('numpy: ', data.dot(data)) # numpy 中可行
#print('torch: ', tensor.dot(tensor)) # torch 不可行
輸出結果
matrix multiplication 矩陣相乘
numpy: [[ 7 10]
[15 22]]
torch: tensor([[ 7., 10.],
[15., 22.]])
matrix multiplication (使用dot)
numpy: [[ 7 10]
[15 22]]