Los tensores se comunican con NumPy
Convierta entre tensores de torch y arrays de NumPy
Los tensores se comunican con NumPy es una lección gratuita de Deep Learning Academy en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Deep Learning Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Deep Learning Academy incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
Two Worlds, One Bridge
Lots of data starts life as a NumPy array. PyTorch makes it easy to move between arrays and tensors in both directions.
NumPy Arrays Are Like Tensors
A NumPy array also stores numbers in a shape, just without GPU support or autograd. Tensors add those superpowers.
import numpy as np
a = np.array([1, 2, 3])
print(a.shape) # (3,)From NumPy with from_numpy
Turn an array into a tensor with torch.from_numpy. It is the standard entry point for existing NumPy data.
a = np.array([1, 2, 3])
t = torch.from_numpy(a)
print(t) # tensor([1, 2, 3])Back to NumPy with .numpy
Going the other way, call .numpy on a tensor. Great for plotting or handing data to other libraries.
t = torch.tensor([1, 2, 3])
a = t.numpy()
print(type(a)) # numpy.ndarrayThey Share the Same Memory
By default the array and tensor share one block of memory. Changing one quietly changes the other.
a = np.array([1, 2, 3])
t = torch.from_numpy(a)
a[0] = 99
print(t[0]) # tensor(99)Copy to Break the Link
Want independent data? Call .clone on the tensor so edits stay separate from the original array.
a = np.array([1, 2, 3])
t = torch.from_numpy(a).clone()
a[0] = 99
print(t[0]) # tensor(1)Dtypes Carry Across
The dtype follows the data over the bridge. A float64 array becomes a float64 tensor unless you cast it.
a = np.array([1.0, 2.0])
t = torch.from_numpy(a)
print(t.dtype) # torch.float64Watch the Float64 Trap
NumPy defaults to float64, but models want float32. Cast after conversion to avoid mismatched dtype errors.
a = np.array([1.0, 2.0])
t = torch.from_numpy(a).float()
print(t.dtype) # torch.float32GPU Tensors Need a Trip Home
You can't call .numpy on a GPU tensor directly. Move it back with .cpu() first, then convert.
t = torch.tensor([1, 2, 3])
a = t.cpu().numpy()
print(a) # [1 2 3]Detach Before Converting Grads
If a tensor tracks gradients, call .detach before .numpy so you grab the values without the autograd graph.
t = torch.tensor([1.0], requires_grad=True)
a = t.detach().numpy()
print(a) # [1.]A Clean Conversion Recipe
The safe pattern for any tensor is detach then cpu then numpy. It works whether or not grads or GPUs are involved.
t = torch.tensor([1.0, 2.0])
a = t.detach().cpu().numpy()
print(a) # [1. 2.]Quick Check
One question about the array and tensor connection.
Recap: Tensors Talk to NumPy
You can bridge both ways with from_numpy and .numpy, watch the shared-memory trap, and use detach-cpu-numpy for a safe export. 🌉
Preguntas frecuentes
¿La lección «Los tensores se comunican con NumPy» es gratis?
Sí — el texto completo de «Los tensores se comunican con NumPy» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Deep Learning Academy, actualiza a CoddyKit PRO. El curso de Deep Learning Academy incluye 4 lecciones en total.
¿Qué aprenderé en «Los tensores se comunican con NumPy»?
Convierta entre tensores de torch y arrays de NumPy Practicas Deep Learning Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Deep Learning Academy?
No se requiere experiencia previa. Deep Learning Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.
¿Cuánto tiempo toma la lección «Los tensores se comunican con NumPy»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Deep Learning Academy?
Sí. Cada lección de Deep Learning Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Formas, dtypes e indexación
- Reshape, view, squeeze y unsqueeze
- Reglas de broadcasting que le ahorran bucles
- Los tensores se comunican con NumPy