Start learning free

LESSON 135 OF 165 · MACHINE LEARNING: DEEP LEARNING WITH PYTORCH

Tensors

Practice

PyTorch keeps its numbers in a tensor. A tensor is numpy's array with one more power: it can also work out gradients for you, which is the next lesson. torch.tensor(a_list) gives back a tensor that holds the same numbers in the same order. Its .shape gives the size of each dimension, and its .dtype gives the type of its numbers. Numbers written with a dot become torch.float32, and whole numbers become torch.int64.

Math on a tensor works on every number at once, with no loop. .tolist() gives back a plain Python list for printing. Here it is on other numbers:

weights = torch.tensor([1.5, 4.0, 0.5])
print(weights.shape)            # torch.Size([3])
print((weights * 2).tolist())   # [3.0, 8.0, 1.0]

A list of rows gives a 2-D tensor. Its shape lists the rows first, then the columns. A @ v is the matrix product, as in numpy: each row of A is multiplied by v number by number and added up, so you get one number per row.

The four prices are 12.0, 7.0, 29.0 and 2.0. Each of the two order rows counts how many of each product was bought. Your program must print the lines below (the last two come from the lesson's check):

Shape: torch.Size([4]) Type: torch.float32
Half price: [6.0, 3.5, 14.5, 1.0]
Orders shape: torch.Size([2, 4])
Order totals: [37.0, 50.0]
numpy gives the same totals: True
torch.tensor([2, 1]) holds torch.int64

Your task: turn price_list into the tensor prices, then print its shape, its dtype and the half prices. Then turn order_rows into the tensor orders and print its shape and the order totals orders @ prices.


Assignment
Follow the Coding Tutorial to make two tensors and print their shapes, the half prices and one total per order.


Hint
Put parentheses around the math before you call .tolist(), as in (weights * 2).tolist(). Without them, Python tries to call .tolist() on the number alone, and that fails.


STEP 1 OF 6
    Ctrl + Enter to check