pytorch tensor转array,numpy.ndarray转str,str转numpy.ndarray

1.1 list 转 numpy

ndarray = np.array(list)

1.2 numpy 转 list

list = ndarray.tolist()

2.1 list 转 torch.Tensor

tensor=torch.Tensor(list)

2.2 torch.Tensor 转 list

先转numpy,后转list

list = tensor.numpy().tolist()

3.1 torch.Tensor 转 numpy

ndarray = tensor.numpy()

*gpu上的tensor不能直接转为numpy

ndarray = tensor.cpu().numpy()

3.2 numpy 转 torch.Tensor

tensor = torch.from_numpy(ndarray)

4.1 numpy.ndarray转str,str转numpy.ndarray

原数组

>>> data
array([[ 79, 203, 231, 106,  17],
       [ 38, 114,  21, 251, 187],
       [222, 145,  59, 158, 211],
       [133, 150, 172,   5,  84],
       [166, 181, 171, 152, 197]])

转换为字符串

>>> data_str = ' '.join(map(str, data.ravel().tolist()))
上面已转换完成,下面仅为了显示字符串
>>> np.fromstring(data_str, sep=' ')
array([ 79., 203., 231., 106.,  17.,  38., 114.,  21., 251., 187., 222.,
       145.,  59., 158., 211., 133., 150., 172.,   5.,  84., 166., 181.,
       171., 152., 197.])

转换回numpy数组

>>> data_shape = data.shape
>>> np.fromstring(data_str, sep=' ').reshape(data_shape)
array([[ 79., 203., 231., 106.,  17.],
       [ 38., 114.,  21., 251., 187.],
       [222., 145.,  59., 158., 211.],
       [133., 150., 172.,   5.,  84.],
       [166., 181., 171., 152., 197.]])

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