Torch,Numpy,Pandas转换

1.torch在cuda和cpu下相同操作的不同函数

import torch
data = torch.tensor([[1,2,3],[4,5,6]])
data.reshape(2,3)
data = data.cuda()
data.view(2,3)

output:

[1,2],[3,4],[5,6]
  1. torch和numpy转换
torch.from_numpy(ndarray) → Tensor
>>> a = numpy.array([1, 2, 3])
>>> t = torch.from_numpy(a)
>>> t
tensor([ 1,  2,  3])
>>> t[0] = -1
>>> a
array([-1,  2,  3])

torch.numpy()
  1. pandas和numpy
data = pd.DataFrame([[1,2,3],[4,5,6]])
data.values
numpydata = np.array([[[1,2,3],[4,5,6]]])
pd.DataFrame(numpydata )

4.torch转置

torch.t(input) → Tensor
Expects input to be <= 2-D tensor and transposes dimensions 0 and 1.

>>> x = torch.randn(())
>>> x
tensor(0.1995)
>>> torch.t(x)
tensor(0.1995)
>>> x = torch.randn(3)
>>> x
tensor([ 2.4320, -0.4608,  0.7702])
>>> torch.t(x)
tensor([.2.4320,.-0.4608,..0.7702])
>>> x = torch.randn(2, 3)
>>> x
tensor([[ 0.4875,  0.9158, -0.5872],
        [ 0.3938, -0.6929,  0.6932]])
>>> torch.t(x)
tensor([[ 0.4875,  0.3938],
        [ 0.9158, -0.6929],
        [-0.5872,  0.6932]])

torch.transpose(input, dim0, dim1) → Tensor
Returns a tensor that is a transposed version of input. The given dimensions dim0 and dim1 are swapped.
>>> x = torch.randn(2, 3)
>>> x
tensor([[ 1.0028, -0.9893,  0.5809],
        [-0.1669,  0.7299,  0.4942]])
>>> torch.transpose(x, 0, 1)
tensor([[ 1.0028, -0.1669],
        [-0.9893,  0.7299],
        [ 0.5809,  0.4942]])

你可能感兴趣的:(Python常见报错,Python,numpy,pandas,python)