Pytorch中tensor的数据类型显示和转换方法

1.显示pytorch中tensor的数据类型:

import torch


x=torch.Tensor([1,2])
print('x: ',x)
print('type(x): ',x.size() )  # 查看tensor的维度是什么样,查看tensor的shape
print('x.dtype: ',x.dtype)  # 这个才是查看tensor中数据的具体类型是什么

pytorch: 获取 tensor 维度的方法:shape 和 size()_Caesar6666的博客-CSDN博客_查看tensor的shape

2. 如何转换tensor中数据的数据类型

x = torch.tensor(x, dtype=torch.float64)

将数据类型转换成:float64类型。

会提示一个warning : UserWarning: To copy construct from a tensor, it is recommended to use sourceTensor.clone().detach() or sourceTensor.clone().detach().requires_grad_(True), rather than torch.tensor(sourceTensor). 

但是不用管,,,

3,一些疑惑待解决:

PS:但有的教程给出了还要将x = variable(x) 的方式,不是很明白。但是链接放在这:

Pytorch的Variable详解_Miss_zhuo_的博客-CSDN博客_pytorch variable

【pytorch错误】:Pytorch RuntimeError: “host_softmax” not implemented for 'torch.cuda.LongTensor'_suyunzzz的博客-CSDN博客

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要将一个tensor转换为不同的数据类型,可以使用torch提供的不同的方法。以下是一些常见的类型转换方法: 1. 使用`torch.long()`将tensor转换为长整型(long)类型。例如: `img = tensor.long()` 2. 使用`torch.half()`将tensor转换为半精度浮点类型。例如: `img = tensor.half()` 3. 使用`torch.int()`将tensor转换为整型(int)类型。例如: `img = tensor.int()` 4. 使用`torch.double()`将tensor转换为双精度浮点类型。例如: `img = tensor.double()` 5. 使用`torch.float()`将tensor转换为浮点类型。例如: `img = tensor.float()` 6. 使用`torch.char()`将tensor转换为字符类型(char)。例如: `img = tensor.char()` 7. 使用`torch.byte()`将tensor转换为字节类型(byte)。例如: `img = tensor.byte()` 8. 使用`torch.short()`将tensor转换为短整型(short)。例如: `img = tensor.short()` 请根据你的需求选择合适的转换方法,并用相应的代码将tensor转换为目标类型。注意,在转换的过程tensor的值可能会发生改变,所以请确保你的转换是正确的和适合你的需求。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Tensor类型之间的相互转换](https://blog.csdn.net/wangshuhuan1/article/details/126057080)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [Tensorflow笔记(一)Tensor数据类型转换](https://blog.csdn.net/qq_64746121/article/details/127293000)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值