基本张量类型的转换

Tensor类型的转换

Pytorch数据类型的转换可以通过三个方式:

1)调用Tensor成员函数long(),int(),double(),float(),byte()

2)调用Tensor成员函数type(),传入数据类型

3)调用Tensor成员函数type_as(),传入实例对象

示例文件 test.py

import torch

a = torch.randn(2, 3)
print(a.type())

b = a.int()
c = a.type(torch.LongTensor)
print(b.type())
print(c.type())

a.type_as(b)
print(a.type())

终端命令行及运行结果

<user>python test.py
torch.FloatTensor
torch.IntTensor
torch.LongTensor
torch.FloatTensor

Tensor类型与ndarray类型的转换

1)Numpy转化为Tensor:torch.from_numpy(ndarray)

2)Tensor转化为numpy:Tensor.numpy()

示例文件 test.py

import torch
import numpy as np

torch_a = torch.randn(3, 2)
numpy_a = torch_a.numpy()
print(torch_a)
print(type(numpy_a))
print(numpy_a)

numpy_b = np.array([[1, 2], [3, 4], [5, 6]])
torch_b = torch.from_numpy(numpy_b)
print(type(numpy_b))
print(numpy_b)
print(torch_b)

终端命令行及运行结果

<user>python test.py
tensor([[-0.2467,  0.4057],
        [-1.3399,  1.4803],
        [-0.6589, -0.0156]])
<class 'numpy.ndarray'>
[[-0.2466862   0.4057195 ]
 [-1.3398814   1.4803079 ]
 [-0.6588639  -0.01563702]]
<class 'numpy.ndarray'>
[[1 2]
 [3 4]
 [5 6]]
tensor([[1, 2],
        [3, 4],
        [5, 6]], dtype=torch.int32)
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值