torch.from_numpy() function (pytorch version)

torch.from_numpyThe function of (ndarray) is to convert the generated array (array) into a tensor Tensor.
This method is equivalent to torch.Tensor(ndarray).

for example:

Naive torch.from_numpy(ndarray) method.

import numpy
import torch

data1 = numpy.array([5, 6, 9])
print('data1的数据类型为:', type(data1))
print('data1的值为:', data1)

data2 = torch.from_numpy(data1)
print('data2的数据类型为:', type(data2))
print('data2的值为:', data2)

data2[1] = 3
print('data2的数据类型为:', type(data2))
print('data2的值为:', data2)

Result output: 

data1的数据类型为: <class 'numpy.ndarray'>
data1的值为: [5 6 9]
data2的数据类型为: <class 'torch.Tensor'>
data2的值为: tensor([5, 6, 9], dtype=torch.int32)
data2的数据类型为: <class 'torch.Tensor'>
data2的值为: tensor([5, 3, 9], dtype=torch.int32)

Use the torch.Tensor(ndarray) method:

import numpy
import torch

data1 = numpy.array([5, 6, 9])
print('data1的数据类型为:', type(data1))
print('data1的值为:', data1)

data3 = torch.Tensor(data1)
print('data3的数据类型为:', type(data3))
print('data3的值为:', data3)

Output result: 

data1的数据类型为: <class 'numpy.ndarray'>
data1的值为: [5 6 9]
data2的数据类型为: <class 'torch.Tensor'>
data2的值为: tensor([5., 6., 9.])

Guess you like

Origin blog.csdn.net/m0_48241022/article/details/132801775