Course contentsShow
← Machine Learning and Deep Learning
Lesson 776 of 3,53819. PyTorch FundamentalsFree lesson

Creating Tensors from Data

Learn to create tensors from Python lists, NumPy arrays, and other tensors using torch.tensor() and torch.from_numpy().

Creating Tensors from Data

What you'll learn: How to convert your existing data—from Python lists, NumPy arrays, or other tensors—into PyTorch tensors you can use for deep learning.

Why Convert Data to Tensors?

In the previous lesson, you learned that tensors are the fundamental data structure in PyTorch. But your data doesn't start as tensors—it might be a list of numbers, a NumPy array from preprocessing, or data loaded from a file. You need reliable ways to transform that data into tensor format.

Three Common Conversion Patterns

From Python Lists

Use torch.tensor() to convert a Python list directly:

import torch

data_list = [1.0, 2.0, 3.0, 4.0]
tensor_from_list = torch.tensor(data_list)
# Creates: tensor([1., 2., 3., 4.])

This works for nested lists too, creating multi-dimensional tensors from lists of lists.

From NumPy Arrays

If you've been working with NumPy (common in data preprocessing), use torch.from_numpy():

import numpy as np

numpy_array = np.array([1.0, 2.0, 3.0, 4.0])
tensor_from_numpy = torch.from_numpy(numpy_array)

Important detail: torch.from_numpy() shares memory with the original NumPy array—changes to one affect the other. Use .clone() if you need independence.

From Other Tensors

You can create new tensors based on existing ones using torch.tensor() on another tensor (this copies the data).

Quick Comparison

  • torch.tensor(): Always copies data, works with lists and arrays
  • torch.from_numpy(): Shares memory with NumPy arrays, more efficient but linked

Key Takeaway: Use torch.tensor() for Python lists and when you need data copies; use torch.from_numpy() for efficient NumPy-to-tensor conversion when memory sharing is acceptable.