Pytorch 转换为tensor类型数据格式

将numpy转为tensor数据类型Tensor、tensor、from_numpy、as_tensor

data = np.array([[1, 2, 3],[4,5,6]])

Tensor = torch.Tensor(data)
tensor = torch.tensor(data)
from_numpy = torch.from_numpy(data)
from_numpy_type = torch.from_numpy(data).type(torch.float32)
as_tensor = torch.as_tensor(data)


print('Tensor:', Tensor, ',dtype =', Tensor.dtype)
print('tensor:', tensor, ',dtype =', tensor.dtype)
print('from_numpy:', from_numpy, ',dtype =', from_numpy.dtype)
print('from_numpy_type:', from_numpy_type, ',dtype =', from_numpy_type.dtype)
print('as_tensor:', as_tensor, ',dtype =', as_tensor.dtype)

 

 改变numpy原数组的数据,观察tensor数据的变化

data[0][0] = 0
print('改变后:')
print('Tensor:', Tensor, ',dtype =', Tensor.dtype)
print('tensor:', tensor, ',dtype =', tensor.dtype)
print('from_numpy:', from_numpy, ',dtype =', from_numpy.dtype)
print('from_numpy_type:', from_numpy_type, ',dtype =', from_numpy_type.dtype)
print('as_tensor:', as_tensor, ',dtype =', as_tensor.dtype)

 改变tensor数据后观察numpy原数组的变化

from_numpy_type[0][1] = 23
print('from_numpy_type', data)
tensor[0][1] = 23
print('tensor', data)
Tensor[0][1] = 23
print('Tensor', data)
as_tensor[0][1] = 23
print('as_tensor', data)
from_numpy[0][1] = 24
print('from_numpy', data)

 创建一个简单的网络

class Tudui(nn.Module):

    def __init__(self):
        super().__init__()
        self.linear = nn.Linear(3, 1)

    def forward(self, input):
        input = input+1
        return input
tudui = Tudui()
data = np.array([[1,2,3],[4,5,6]])
x = torch.tensor(data,dtype=torch.float32)
output = tudui(x)
print(output)
print(x)
print(data)
tudui = Tudui()
data = np.array([[1,2,3],[4,5,6]])
x = torch.from_numpy(data).type(torch.float32)
output = tudui(x)
print(output)
print(x)
print(data)
tudui = Tudui()
data = np.array([[1,2,3],[4,5,6]])
x = torch.from_numpy(data)
output = tudui(x)
print(output)
print(x)
print(data)

 

class Tudui(nn.Module):

    def __init__(self):
        super().__init__()
        self.linear = nn.Linear(3, 1)

    def forward(self, input):
        input += 1
        return input
tudui = Tudui()
data = np.array([[1,2,3],[4,5,6]])
x = torch.from_numpy(data).type(torch.float32)
output = tudui(x)
print(output)
print(x)
print(data)

 

tudui = Tudui()
data = np.array([[1,2,3],[4,5,6]])
x = torch.from_numpy(data)
output = tudui(x)
print(output)
print(x)
print(data)

tudui = Tudui()
data = np.array([[1,2,3],[4,5,6]])
x = torch.tensor(data,dtype=torch.float32)
output = tudui(x)
print(output)
print(x)
print(data)

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值