Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Challenge: Performing Mathematical Operations | PyTorch Introduction
PyTorch Essentials

book
Challenge: Performing Mathematical Operations

Task

Swipe to start coding

  1. Compute the sum of each row in the given tensor and retain the dimensions of the output.
  2. Calculate the mean of each column in the tensor.
  3. Find the maximum value of each row.
  4. Normalize the tensor by dividing each element by the overall sum of the tensor.

Solution

import torch

tensor = torch.tensor([[3, 7, 1], [2, 5, 9], [8, 6, 4]]).float()
# Compute the sum of each row and retain the dimensions
row_sum = tensor.sum(dim=1, keepdim=True)
# Calculate the mean of each column
column_mean = tensor.mean(dim=0)
# Find the maximum value of each row
row_max = tensor.max(dim=1)[0]
# Normalize the tensor by dividing each element by the overall sum
overall_sum = tensor.sum()
normalized_tensor = tensor / overall_sum
# Print results
print("Original tensor:\n", tensor)
print("Row sum:\n", row_sum)
print("Column mean:\n", column_mean)
print("Row max:\n", row_max)
print("Normalized tensor:\n", normalized_tensor)
Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 1. Chapter 8
single

single

import torch

tensor = torch.tensor([[3, 7, 1], [2, 5, 9], [8, 6, 4]]).float()
# Compute the sum of each row and retain the dimensions
row_sum = tensor.___
# Calculate the mean of each column
column_mean = tensor.___
# Find the maximum value of each row
row_max = tensor.___[0]
# Normalize the tensor by dividing each element by the overall sum
overall_sum = tensor.___
normalized_tensor = ____
# Print results
print("Original tensor:\n", tensor)
print("Row sum:\n", row_sum)
print("Column mean:\n", column_mean)
print("Row max:\n", row_max)
print("Normalized tensor:\n", normalized_tensor)

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

some-alt