Home Machine Learning Optimizing Your PyTorch Code: A Guide to Argmin()

# Optimizing Your PyTorch Code: A Guide to Argmin()

## This article will dive into the specifics of argmin(), demonstrating its syntax, usage, and practical examples to help you get the most from this function.

PyTorch is a scientific computing toolkit built on Python to run deep learning algorithms. On the other hand, a tensor is a number, a vector, or a matrix. Matrix and tensors are frequently used interchangeably. On the flip side, tensors are broader versions of vectors. Although all arrays are arrays, not all arrays are tensors. Now that we are done laying down that foundation let’s explore a fascinating PyTorch function argmin(), especially now that we have a foundational understanding of both.

This article explores the argmin() function of PyTorch’s library. The latter is an open-source framework for the Python programming language and is famously called PyTorch. The data is transformed into a Tensor with PyTorch. Data is stored in multidimensional arrays called tensors. Therefore, we must import the torch module to use a tensor.

The argmin() function is solely responsible for returning the indices of the flattened tensor’s minimal value(s) along a dimension. It is the second value that torch.min() has returned. Additionally, the precise semantics of this technique are described in this article piece-wise. Also, note that the indices of the first minimal value are returned if there are several minimal values.

Tensor() is the method used to build a tensor.

A multi-dimensional matrix with only one data type per element is what torch.tensor() contains. The definition of a tensor can be an integer, a floating-point number, or a boolean value. Torch defines nine tensor types. Note how using a floating-point type is recommended over an integer type.

## PyTorch -argmin()

The syntax is as follows:

```torch.tensor(var_data)
```

Where the var_data is an array with several dimensions.

```# working example

var_tensor_one =torch.tensor(1)
var_tensor_two =torch.tensor(1.)
var_tbool =torch.tensor(True)
print(f'var_tensor_one has type {var_tensor_one.dtype}\n var_tensor_two has type{var_tensor_two.dtype}\n\
var_tbool has type{tbool.dtype}')```

A list can also define tensors as an array or a vector. From t5 and t6, we can see that mixing integer, float, and boolean values yield a tensor with a float data type. With the use of Python’s indexing and slicing notation, one may retrieve a tensor’s contents.

```# Working example two
var_t3 =torch.tensor([2., 3., 4.])
var_t4 =torch.tensor([[5.,6.],[7.,8.],[9.,10.]])
var_t5 =torch.tensor([[True,1.][1,14]])

print(f'var_t3 has type {var_t3.dtyp}\n var_t4 has type {var_t4.dtype}\n\
var_t5 has type {var_t5.dtype}\n var_t6 has type {var_t6.dtype}')
var_t5[1]```

Tensors must consist of an equal number of elements. Here, in a similar pattern, we can see that whereas t7[0] has two elements, t7[1] has three. This results in the ValueError: anticipated sequence of length two at dim one being returned (got 3). We can either add another element from t7[0] or remove an element from t7[1] to correct this.

To declare an object as a tensor object, use the torch.tensor() method. After that, you can use that object as an input to built-in PyTorch methods. Torch.tensor() always transfers the data by default.

### argmin()

The index of the minimum value of every element in the input tensor is returned by PyTorch’s argmin() function.

Syntax:

`torch.argmin(tensor,dim,keepdim)`

Where:

The input tensor is the tensor.

Dim means to make something smaller, in this case, the dimension.
If dim=0 is used, a column comparison will be performed to determine the index for the minimum value along the column. If dim=1, a row comparison will determine the index for the minimum value along the row. KeepDim determines whether or not the output tensor’s dimension(dim) has been preserved.

```var_tensor = torch.randn(4, 4)
var_tensor
torch.argmin(var_tensor)
torch.argmin(var_tensor, dim=1)
torch.argmin(var_tensor, dim=1, keepdim=True)```

There’s a lot of similarity between argmin() in PyTorch and Numpy’s argmin(). Further, both libraries have compatriots for computing the maximum elements in a specified tensor and similarly share the name argmax(). Let’s illustrate the argmax() and argmin() use here with an example to help drive the point home.

```import torch
var_tensor=torch.randn(10)
# view the resultant tensor
var_tensor
tensor([ 1.0062,  1.0328,  0.1764, -0.5594, -0.0861,  0.4747,  0.1676,  1.7200,
-2.5906, -0.6808])
torch.argmax(var_tensor)
tensor(7)
torch.argmin(var_tensor)
tensor(8)```

#### Example: Generating a two-dimensional tensor

In this example, we’ll generate a two-dimensional tensor with six rows and eight columns, and we’ll use argmin() to reduce the size of the rows and columns.

```# commence by importing the needed libraries
#import torch module
import torch

#creation of a tensor containing two dimensions (6 * 8)
#using elements that are explicitly random via randn() function
var_data = torch.randn(6,8)

#view the data
print(var_data)

#establish the minimum index along columns by employing the argmin function
print(torch.argmin(var_data, dim=0))

#determine the minimum index along the rows with the functionargmin
print(torch.argmin(var_data, dim=1))```

#### Example: Creation of a tensor via an argmin()

In this demo, we will use an eight-by-eight matrix, create a tensor, then use argmin().

```# commence by importing the libraries you need
#import torch module
import torch

#creation of a tensor having two dimensions (8 * 8)
#using randn() function and random  elements
var_data = torch.randn(8,8)

#viewing the data
print(var_data)

#fetch the  minimum index along columns having the function argmin
print(torch.argmin(var_data, dim=0))

#display the minimum index of rows with argmin
print(torch.argmin(var_data, dim=1))```

### Utilizing a CPU

We must create a tensor with a cpu() function to execute an argmin() function on the CPU. It will operate on a computer with a CPU. We can now use the cpu() method to create a tensor. Consequently, the syntax for this utility is as follows:

`torch.tensor(var_data).cpu()`

#### Example: Creating a two-dimensional tensor with five rows and eight columns

In this example, we’ll build a two-dimensional tensor with five rows and eight columns on the CPU and use argmin() to reduce the size of the rows and columns.

```#add the torch module.
import torch

#2 dimensional (5 * 8) tensor creation
#using the cpu() function and randn() with random elements
var_data = torch.randn(5,8).cpu()

#viewing the data
print(var_data)

#with argmin, get the minimum index along the columns.
print(torch.argmin(var_data, dim=0))

#argmin returns the minimum index along the rows.
print(torch.argmin(var_data, dim=1))```

#### Example: create a tensor with an eight-by-eight matrix

In this demo, we will create a tensor with an eight-by-eight matrix on the CPU using the function- argmin().

```#start by importing the torch library and other necessary modules
import torch

#With the randn() method, generate a tensor with two dimensions (8* 8)
#and random elements.
var_data = torch.randn(8,8).cpu()

#showing the data
print(var_data)

#with argmin, get the minimum index along the columns.
print(torch.argmin(var_data, dim=0))

#argmin returns the minimum index along the rows.
print(torch.argmin(var_data, dim=1))```

#### Example: Comparing the Performance of argmax and argmin

In this example, we demonstrate how the argmax compares with the argmin function of PyTorch’s module.

```# Step 1 - Import Library

import torch

# Step 2 - Take Sample data

var_sample = torch.randn(3,3)

# viewing the sample data
var_sample

tensor([[-0.3292, -0.3550, -0.5400],
[-0.3573,  1.9466, -0.5090],
[-0.1529, -1.1344,  0.3330]])

# Step 3 - Perform argmax and argmin

var_max = torch.argmax(var_sample)

var_min = torch.argmin(var_sample)

print("This is the input tensor's maximum value. :",var_max)

print("This is the input tensor's lowest value. :",var_min)```

#### Example: Torch.argmin()

Torch.argmin() returns the indices of the smallest values for all of the input tensor’s elements as illustrated below:

```# working example
import torch
tmin = torch.randn([3,4])

# show the tensor
tmin
tensor([[2.2760, -0.4069, 0.7879, 0.2231],
[0.1047, 0.8693, 2.0053, 1.6365],
[0.1030, 1.1026, 0.3360, 0.2702]])

torch.argmin(tmin)
tensor(0)```

Index 0 is given by torch.argmax() as the index with the highest value, which, upon inspection, equals 0.1030. Further, a torch is also present. The function argmin() returns the lowest value index, as a tensor is an input. The function will fail when an invalid tensor is supplied with the same case utilizing torch.isnan().

## Conclusion

In this PyTorch tutorial, we learned what argmin() is and how to use it to retrieve the indices of the minimum values across columns and rows in a tensor. We also dived deeper to express the variation with argmax() and similar functions in Numpy that do the same tasks.