PyTorch torch.max(): Get Maximum Value from Two Tensors – PyTorch Tutorial

By | May 31, 2022

Pytorch torch.max() function can allow us to get the maximum values from a tensor based on dimension. Here is the tutorial:

Understand PyTorch torch.max(): Return the Maximum Value of a Tensor – PyTorch Tutorial

However, if we plan to create a new tensor based on the maximum values from two tensors. How to do? In this tutorial, we will use torch.max() function to implement it.

For example:

import torch
import torch.nn as nn

cosine = torch.randn(5,5)
label = torch.randn(5,5)
print(cosine)
print(label)
print(torch.max(cosine, label))

In this code, we will use the maximum value from cosine and label tensor to create a new tensor.

Run this code, we will see:

PyTorch torch.max() Get Maximum Value from Two Tensors - PyTorch Tutorial

Can we use three tensors?

For example:

print(torch.max(cosine, label, label))

We will get an error:

TypeError: max() received an invalid combination of arguments – got (Tensor, Tensor, Tensor),

It means we only can pass two tensors to torch.max().

Leave a Reply