Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a list or numpy array to a 1d torch tensor?

Tags:

pytorch

torch

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.

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.

like image 859
Wasi Ahmad Avatar asked Mar 20 '17 02:03

Wasi Ahmad


People also ask

How do you convert a list into a tensor?

To convert a Python list to a tensor, we are going to use the tf. convert_to_tensor() function and this function will help the user to convert the given object into a tensor. In this example, the object can be a Python list and by using the function will return a tensor.

How do you make a one direction tensor in PyTorch?

Creating one-dimensional Tensor tensor() method. Syntax of creating one dimensional tensor is as follows: n= torch. tensor([Tensor elements])

How do you make a torch tensor?

There are a few main ways to create a tensor, depending on your use case. To create a tensor with pre-existing data, use torch.tensor() . To create a tensor with specific size, use torch.* tensor creation ops (see Creation Ops).


1 Answers

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)
like image 57
Kashyap Avatar answered Sep 26 '22 18:09

Kashyap