|
| 1 | +--- |
| 2 | +Title: '.max()' |
| 3 | +Description: 'Returns the maximum value of a tensor.' |
| 4 | +Subjects: |
| 5 | + - 'Computer Science' |
| 6 | + - 'Data Science' |
| 7 | +Tags: |
| 8 | + - 'Deep Learning' |
| 9 | + - 'Methods' |
| 10 | + - 'PyTorch' |
| 11 | + - 'Tensor' |
| 12 | +CatalogContent: |
| 13 | + - 'intro-to-py-torch-and-neural-networks' |
| 14 | + - 'paths/data-science' |
| 15 | +--- |
| 16 | + |
| 17 | +The **`.max()`** method in PyTorch returns the maximum value from a [tensor](https://www.codecademy.com/resources/docs/pytorch/tensors). It can find the maximum value across the entire tensor. This method is commonly used in data analysis, finding peak values, and various neural network operations. |
| 18 | + |
| 19 | +## Syntax |
| 20 | + |
| 21 | +```pseudo |
| 22 | +torch.max(input) → Tensor |
| 23 | +``` |
| 24 | + |
| 25 | +**Parameters:** |
| 26 | + |
| 27 | +- `input` (Tensor): The input tensor. |
| 28 | + |
| 29 | +**Return value:** |
| 30 | + |
| 31 | +Returns a tensor containing the maximum value from the `input`. |
| 32 | + |
| 33 | +## Example |
| 34 | + |
| 35 | +The following example demonstrates how to use the `.max()` method to find the maximum value in a tensor: |
| 36 | + |
| 37 | +```py |
| 38 | +import torch |
| 39 | + |
| 40 | +# Create a tensor with various values |
| 41 | +tensor = torch.tensor([1.5, -2.3, 0.0, 4.8, -1.2]) |
| 42 | + |
| 43 | +# Find the maximum value using the method form |
| 44 | +max_value = tensor.max() |
| 45 | + |
| 46 | +# Alternative: use the functional form |
| 47 | +max_functional = torch.max(tensor) |
| 48 | + |
| 49 | +print("Original Tensor:") |
| 50 | +print(tensor) |
| 51 | + |
| 52 | +print("\nMaximum Value (using .max()):") |
| 53 | +print(max_value) |
| 54 | + |
| 55 | +print("\nMaximum Value (using torch.max()):") |
| 56 | +print(max_functional) |
| 57 | + |
| 58 | +print("\nMaximum as Python number (using .item()):") |
| 59 | +print(max_value.item()) |
| 60 | +``` |
| 61 | + |
| 62 | +This example results in the following output: |
| 63 | + |
| 64 | +```shell |
| 65 | +Original Tensor: |
| 66 | +tensor([ 1.5000, -2.3000, 0.0000, 4.8000, -1.2000]) |
| 67 | + |
| 68 | +Maximum Value (using .max()): |
| 69 | +tensor(4.8000) |
| 70 | + |
| 71 | +Maximum Value (using torch.max()): |
| 72 | +tensor(4.8000) |
| 73 | + |
| 74 | +Maximum as Python number (using .item()): |
| 75 | +4.800000190734863 |
| 76 | +``` |
| 77 | +
|
| 78 | +In this example: |
| 79 | +
|
| 80 | +- The tensor contains five values: `1.5`, `-2.3`, `0.0`, `4.8`, and `-1.2` |
| 81 | +- The `.max()` method identifies `4.8` as the maximum value in the tensor |
| 82 | +- Both `.max()` and `torch.max()` produce identical results: `tensor(4.8000)` |
| 83 | +- The `.item()` method converts the tensor result to a Python float: `4.800000190734863` |
0 commit comments