如何将列表或 numpy 数组转换为一维火炬张量? [英] How to convert a list or numpy array to a 1d torch tensor?
问题描述
我有一个浮点值列表(或一个 numpy 数组).我想创建一个包含所有这些值的一维火炬张量.我可以创建火炬张量并运行一个循环来存储值.
I have a list (or, a numpy array) of float values. I want to create a 1d torch tensor that will contain all those values. I can create the torch tensor and run a loop to store the values.
但我想知道有没有什么办法,我可以用列表或数组中的初始值创建一个火炬张量?还建议我在 pytorch 中工作时是否有任何 pythonic 方法来实现这一点.
But I want to know is there any way, I can create a torch tensor with initial values from a list or array? Also suggest me if there is any pythonic way to achieve this as I am working in pytorch.
推荐答案
这些是 pytorch 中的常规操作,可在文档中找到.PyTorch 允许与 numpy 轻松交互.有一种名为 from_numpy
的方法,文档可用 这里
These are general operations in pytorch and available in the documentation. PyTorch allows easy interfacing with numpy. There is a method called from_numpy
and the documentation is available here
import numpy as np
import torch
array = np.arange(1, 11)
tensor = torch.from_numpy(array)
这篇关于如何将列表或 numpy 数组转换为一维火炬张量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!