torch 和numpy的相互转化
import mathimport torchimport numpy as npimport pandas as pdA = np.array([[1,2,3],[6,5,3]])print(A, '\n')B = torch.from_numpy(A)#将numpy 转换化为 tensorprint(B)C = B.numpy()#tensor 转换化为 numpy 但是对该numpy进行修改
·
import math
import torch
import numpy as np
import pandas as pd
A = np.array([[1,2,3],[6,5,3]])
print(A, '\n')
B = torch.from_numpy(A) #将numpy 转换化为 tensor
print(B)
C = B.numpy()#tensor 转换化为 numpy 但是对该numpy进行修改会改变其他的的值
# 对C该表 A,B 都会相应的改变
C[1] = 0
print(A, '\n')
print(B)
print(C)
import torch
import numpy as np
#创建一个numpy array的数组
array = np.array([1,2,3,4])
#将numpy array转换为torch tensor
tensor = torch.tensor(array)
Tensor = torch.Tensor(array)
as_tensor = torch.as_tensor(array)
from_array = torch.from_numpy(array)
print(array.dtype) #int32
#查看torch默认的数据类型
print(torch.get_default_dtype()) #torch.float32
#对比几种不同方法之间的异同
print(tensor.dtype) #torch.int32
print(Tensor.dtype) #torch.float32
print(as_tensor.dtype) #torch.int32
print(from_array.dtype) #torch.int32
array[0] = 10
print(tensor) # tensor([1, 2, 3, 4], dtype=torch.int32)
print(Tensor) # tensor([1., 2., 3., 4.])
print(as_tensor) #tensor([10, 2, 3, 4], dtype=torch.int32)
print(from_array) #tensor([10, 2, 3, 4], dtype=torch.int32)
# 后面两种数据改变,前面不变
tensor 转化为numpy 只有找到 a.numpy
更多推荐
已为社区贡献1条内容
所有评论(0)