简体   繁体   English

如何在PyTorch中将numpy数组转换为LongTensor类型的变量?

[英]How to convert numpy array into LongTensor type Variable in PyTorch?

I am trying to convert numpy array into PyTorch LongTensor type Variable as follows: 我正在尝试将numpy array转换为PyTorch LongTensor类型的Variable ,如下所示:

import numpy as np
import torch as th

y = np.array([1., 1., 1.1478225, 1.1478225, 0.8521775, 0.8521775, 0.4434675])
yth = Variable(th.from_numpy(y)).type(torch.LongTensor)

However the result I am getting is a rounded off version: 但是我得到的结果是四舍五入的版本:

tensor([ 1,  1,  1,  1,  0,  0,  0])

How can I keep the precision of numpy array while getting LongTensor variable? 如何获取LongTensor变量时保持numpy array的精度?

Expected result should be: 预期结果应为:

tensor([1., 1., 1.1478225, 1.1478225, 0.8521775, 0.8521775, 0.4434675])

LongTensor represents tensors with values of type long / int64 (cf table in doc ). LongTensor表示具有long / int64类型值的张量(参见doc中的表 )。 Your float values are thus converted (ie rounded) to integers. 这样,您的float值将转换(即四舍五入)为整数。

To keep float values, use FloatTensor ( float32 ) or DoubleTensor ( float64 ) instead. 要保留浮点值,请改用FloatTensorfloat32 )或DoubleTensorfloat64 )。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何修复 pytorch 'RuntimeError: Expected object of type torch.cuda.LongTensor but found type torch.LongTensor' - How to fix pytorch 'RuntimeError: Expected object of type torch.cuda.LongTensor but found type torch.LongTensor' 如何将pytorch张量转换为numpy数组? - How to convert a pytorch tensor into a numpy array? 如何在不转换为 Numpy 数组的情况下将 TensorFlow 张量转换为 PyTorch 张量? - How to convert TensorFlow tensor to PyTorch tensor without converting to Numpy array? 为什么PyTorch收集函数需要索引参数为LongTensor类型? - Why does PyTorch gather function require index argument to be of type LongTensor? 如何使用pytorch将系列numpy数组转换为张量 - how to convert series numpy array into tensors using pytorch 将 PyTorch CUDA 张量转换为 Z3B7F949B2343F9E5390​​E29F6EF5E1778Z 数组 - Convert PyTorch CUDA tensor to NumPy array 如何将tensorflow变量转换为numpy数组 - How to convert tensorflow variable to numpy array Pytorch嵌入RuntimeError:类型为torch.LongTensor的预期对象,但为参数#3'索引'找到类型为torch.cuda.LongTensor - Pytorch embedding RuntimeError: Expected object of type torch.LongTensor but found type torch.cuda.LongTensor for argument #3 'index' numpy:如何快速转换数组类型 - numpy : How to convert an array type quickly 如何将tensorflow占位符变量转换为numpy数组? - How to convert tensorflow placerholder variable to numpy array?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM