Learn practical skills, build real-world projects, and advance your career

Assignment 1

torch.tensor CLASS and its Methods

An short introduction about PyTorch and about the chosen functions.

  • torch.tensor.item()
  • torch.new_x (x=[tensor, full, empty, zeros, ones])
  • torch.addx() (x=[,bmm,cdiv,cmul,mm,mv,r])
  • function 4
  • function 5
# Import torch and other required modules
import torch

Function 1 - torch.tensor.item()

This method returns a python "num" value from a single-value tensor

# Example 1 - working
# Declare a tensor with a single value. Dimensions don't matter

# INT
x = torch.tensor([[1]]) 
# Two-dimensional tensor declaration with single element
print("[int x]   Tensor with 2-dimensions: ",x)
print("[int x]   Python Number from the tensor: ",x.item())

# FLOAT
y = torch.tensor([[1.832]]) 
# Two-dimensional tensor declaration with single element
print("[float y] Tensor with 2-dimensions: ",y)
print("[float y] Python Number from the tensor: ",y.item())
[int x] Tensor with 2-dimensions: tensor([[1]]) [int x] Python Number from the tensor: 1 [float y] Tensor with 2-dimensions: tensor([[1.8320]]) [float y] Python Number from the tensor: 1.8320000171661377

The torch.tensor.item() has known issues in the framework. The conversion doesn't return the exact value