0
0
PytorchHow-ToBeginner · 3 min read

How to Create Tensor from NumPy in PyTorch: Simple Guide

To create a tensor from a NumPy array in PyTorch, use torch.from_numpy(). This function converts the NumPy array into a tensor sharing the same memory, so changes in one reflect in the other.
📐

Syntax

The basic syntax to create a tensor from a NumPy array is:

  • torch.from_numpy(ndarray): Converts a NumPy ndarray to a PyTorch tensor.

This tensor shares memory with the original NumPy array, so modifying one affects the other.

python
import torch
import numpy as np

numpy_array = np.array([1, 2, 3])
tensor = torch.from_numpy(numpy_array)
💻

Example

This example shows how to convert a NumPy array to a PyTorch tensor and how changes in one affect the other.

python
import torch
import numpy as np

# Create a NumPy array
numpy_array = np.array([10, 20, 30])

# Convert to PyTorch tensor
tensor = torch.from_numpy(numpy_array)

print('Original NumPy array:', numpy_array)
print('Converted tensor:', tensor)

# Modify the tensor
tensor[0] = 100

print('Modified tensor:', tensor)
print('NumPy array after tensor change:', numpy_array)
Output
Original NumPy array: [10 20 30] Converted tensor: tensor([10, 20, 30]) Modified tensor: tensor([100, 20, 30]) NumPy array after tensor change: [100 20 30]
⚠️

Common Pitfalls

1. Data type mismatch: PyTorch tensors and NumPy arrays must have compatible data types. For example, torch.from_numpy() does not support NumPy arrays with dtype=object.

2. Memory sharing: Since the tensor and NumPy array share memory, modifying one changes the other. If you want an independent tensor, use tensor.clone() or torch.tensor(numpy_array) instead.

python
import torch
import numpy as np

# Wrong way: modifying shared memory unintentionally
numpy_array = np.array([1, 2, 3])
tensor = torch.from_numpy(numpy_array)
tensor[0] = 10
print('NumPy array after tensor change:', numpy_array)  # Changed unexpectedly

# Right way: create independent tensor
independent_tensor = torch.tensor(numpy_array)
independent_tensor[0] = 100
print('NumPy array after independent tensor change:', numpy_array)  # Unchanged
Output
NumPy array after tensor change: [10 2 3] NumPy array after independent tensor change: [1 2 3]
📊

Quick Reference

Summary tips for creating tensors from NumPy arrays:

  • Use torch.from_numpy() for zero-copy conversion (shared memory).
  • Use torch.tensor() to create a new tensor with copied data.
  • Check data types to avoid errors.
  • Remember that modifying one affects the other when using torch.from_numpy().

Key Takeaways

Use torch.from_numpy() to convert a NumPy array to a PyTorch tensor sharing memory.
Modifying the tensor or NumPy array affects the other when using torch.from_numpy().
Use torch.tensor() to create an independent tensor copy from a NumPy array.
Ensure the NumPy array has a compatible data type before conversion.
Check if you need shared memory or independent data to choose the right method.