pytorch张量转换

import torch
import numpy as np

# 创建一个随机初始化矩阵
x = torch.rand(5, 3)
print(x)
# 构造一个填满 0 且数据类型为 long 的矩阵
x = torch.zeros(5, 6, dtype=torch.long)
print(x)
# 获取张量的形状
print(x.size())
# 改变形状
z = x.view(-1, 2, 3)  # the size -1 is inferred from other dimensions
print(z)

print('将 torch 的 Tensor 转换为 NumPy 数组')
torch_a = torch.rand(5, 6)
print(torch_a)
numpy_a = torch_a.numpy()
print(numpy_a)

print('将 NumPy 数组转化为Torch张量')
troch_b = torch.from_numpy(numpy_a)
print(troch_b)

print('list 转 Tensor')
list_a = [1, 2, 3]
print(list_a)
torch_a = torch.tensor(list_a)
print(torch_a)

print('list 转 bumpy')
list_a = [1, 2, 3]
print(list_a)
numpy_a = np.asarray(list_a)
print(numpy_a)

print('numpy 转 list')
print(numpy_a)
print(numpy_a.tolist())

你可能感兴趣的:(pytorch,python,pytorch,numpy,python)