Тензоры взаимодействуют с NumPy
Преобразуйте тензоры torch в массивы NumPy и обратно
«Тензоры взаимодействуют с NumPy» — бесплатный урок Deep Learning Academy на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Deep Learning Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Deep Learning Academy содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
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. 🌉
Часто задаваемые вопросы
Урок «Тензоры взаимодействуют с NumPy» бесплатный?
Да — полный текст урока «Тензоры взаимодействуют с NumPy» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Deep Learning Academy, подпишись на CoddyKit PRO. Курс Deep Learning Academy содержит 4 уроков всего.
Чему я научусь в уроке «Тензоры взаимодействуют с NumPy»?
Преобразуйте тензоры torch в массивы NumPy и обратно Ты практикуешь Deep Learning Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Deep Learning Academy?
Предыдущий опыт не требуется. Deep Learning Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.
Сколько времени занимает урок «Тензоры взаимодействуют с NumPy»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Deep Learning Academy?
Да. Каждый урок Deep Learning Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Формы, типы данных и индексация
- Изменение формы, View, Squeeze и Unsqueeze
- Правила broadcasting, которые избавят от циклов
- Тензоры взаимодействуют с NumPy