Ваш первый torch.tensor
Создайте тензор и выведите его форму и тип данных
«Ваш первый torch.tensor» — бесплатный урок Deep Learning Academy на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Deep Learning Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Deep Learning Academy содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Meet the Tensor
A tensor is PyTorch's core data container, a grid of numbers much like a NumPy array but ready to run on a GPU. 🧮
Create One from a List
The simplest way to make a tensor is torch.tensor from a Python list. PyTorch copies your numbers into a fast numerical grid.
x = torch.tensor([1, 2, 3])Print It Out
Printing a tensor shows its values wrapped in tensor(...), so you always know you are looking at PyTorch data, not a plain list.
print(x)Shape Describes Structure
The shape tells you the size along each dimension. A flat list of three values has a shape of three.
print(x.shape)Build a 2D Tensor
Nest lists to make a grid. This matrix has two rows and three columns, so its shape reads as two by three.
m = torch.tensor([[1, 2, 3], [4, 5, 6]])Dtype Is the Number Type
Every tensor has a dtype, the kind of number it stores. Whole numbers become int64, decimals become float32 by default.
print(x.dtype)Floats for Training
Networks learn with decimals, so most model data is float32. Add a decimal point and PyTorch picks the float type for you.
y = torch.tensor([1.0, 2.0, 3.0])Set the Dtype Yourself
You can request a type directly with the dtype argument, which is handy when you need floats from integer input.
z = torch.tensor([1, 2], dtype=torch.float32)Tensors Full of Zeros
Need a blank tensor of a given size? torch.zeros fills the shape you ask for with zeros, perfect as a starting buffer.
torch.zeros(2, 3)Random Tensors
Model weights often start random. torch.rand gives a tensor of the shape you choose, filled with values between zero and one.
torch.rand(2, 3)Count the Dimensions
The number of dimensions is the tensor's rank. Read it with .ndim: a vector is rank one, a matrix is rank two.
print(m.ndim)Quick Check
Reason about the shape of a nested-list tensor.
Recap
You created tensors from lists, read their shape and dtype, and made zeros and random grids. This is the data deep learning runs on. ✅
Часто задаваемые вопросы
Урок «Ваш первый torch.tensor» бесплатный?
Да — полный текст урока «Ваш первый torch.tensor» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Deep Learning Academy, подпишись на CoddyKit PRO. Курс Deep Learning Academy содержит 4 уроков всего.
Чему я научусь в уроке «Ваш первый torch.tensor»?
Создайте тензор и выведите его форму и тип данных Ты практикуешь Deep Learning Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Deep Learning Academy?
Предыдущий опыт не требуется. Deep Learning Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.
Сколько времени занимает урок «Ваш первый torch.tensor»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Deep Learning Academy?
Да. Каждый урок Deep Learning Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Установите PyTorch и проверьте импорт
- CPU, GPU или MPS: выберите устройство
- Ноутбуки, скрипты и воспроизводимые начальные значения
- Ваш первый torch.tensor