Tensores Conversam com NumPy
Converta entre tensores do PyTorch e matrizes do NumPy
Tensores Conversam com NumPy é uma aula grátis de Deep Learning Academy no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Deep Learning Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Deep Learning Academy inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em 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. 🌉
Perguntas Frequentes
A aula “Tensores Conversam com NumPy” é grátis?
Sim — o texto completo de “Tensores Conversam com NumPy” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Deep Learning Academy, atualize para CoddyKit PRO. O curso de Deep Learning Academy inclui 4 aulas no total.
O que vou aprender em “Tensores Conversam com NumPy”?
Converta entre tensores do PyTorch e matrizes do NumPy Você pratica Deep Learning Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Deep Learning Academy?
Nenhuma experiência prévia é necessária. Deep Learning Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.
Quanto tempo leva a aula “Tensores Conversam com NumPy”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Deep Learning Academy?
Sim. Cada aula de Deep Learning Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Formas, Tipos de Dados e Indexação
- Redimensionar, View, Squeeze e Unsqueeze
- Regras de Broadcasting que Economizam Loops
- Tensores Conversam com NumPy