From af393a2a03b434f79f825ac6da11ccf075ec7c65 Mon Sep 17 00:00:00 2001 From: Mamta Wardhani Date: Thu, 25 Sep 2025 17:27:41 +0530 Subject: [PATCH 1/5] [Edit] Python: Python CLI arguments --- .../command-line-arguments.md | 188 ++++++++++++------ 1 file changed, 132 insertions(+), 56 deletions(-) diff --git a/content/python/concepts/command-line-arguments/command-line-arguments.md b/content/python/concepts/command-line-arguments/command-line-arguments.md index d09f403722a..6c3b74536f5 100644 --- a/content/python/concepts/command-line-arguments/command-line-arguments.md +++ b/content/python/concepts/command-line-arguments/command-line-arguments.md @@ -1,106 +1,182 @@ --- Title: 'Command Line Arguments' -Description: 'Python offers several methods of parsing command line arguments that are used when launching a program.' +Description: 'Provides methods to accept input values when running Python scripts from the terminal' Subjects: + - 'Code Foundations' - 'Computer Science' - - 'Data Science' Tags: - - 'Input' - 'Arguments' - - 'Bash/Shell' - 'Command Line' + - 'Input' + - 'Modules' CatalogContent: - 'learn-python-3' - 'paths/computer-science' --- -Python offers several methods of parsing **command line arguments** that are used when launching a program. The user has the option of passing various parameters to the program by adding them after the program name. These parameters can be accessed through various modules. The parameter names are left up to the programmer. By convention the parameter `-h` or `--help` (and `/h` and `/help` in Windows) is reserved to print a help message to the console listing the various command line options recognized by the program. - -Arguments are passed differently depending on the operating system: +**Command line arguments** are values passed to a Python program when running it from the terminal or command prompt. They allow users to provide input data to a program without modifying the source code, making programs more flexible and reusable by accepting different parameters at runtime. -- Unix-like arguments are a single letter preceded by a dash (`-h`) or a word preceded by two dashes (`--help`). -- Windows arguments are a letter or a whole word preceded by a slash (`/h` or `/help`). +## Ways to Handle Command Line Arguments -## Parsing With `sys.argv` +Python provides several built-in modules to handle command line arguments, each with different levels of complexity and functionality. -The `sys` module offers the most straightforward method of accessing command line arguments, but it also requires the programmer to do most of the work interpreting them. With the `sys` module, the arguments are passed along in a simple list structure named `sys.argv`. +### Using `sys.argv` -The first item in the list, `sys.argv[0]` is the name used to launch the Python program, along with the path used. Each subsequent item is a space-delimited argument from the command line used to launch the program. If an argument requires embedded spaces, it needs to be enclosed in quotes to be parsed correctly. +The `sys.argv` module provides the simplest way to access command line arguments. It stores all arguments passed to the script as a list of strings, where `sys.argv[0]` contains the script name itself. -### Example +#### Example: Basic `sys.argv` Usage -This prints the script name followed by a list of the command line arguments passed on to the program. +This example demonstrates how to access and use Python command line arguments using the `sys` module: ```py import sys -print(f"The program name used to launch me is {sys.argv[0]}.") -print("I was passed the following arguments:") -for arg in sys.argv[1:]: - print(arg) +# Display all command line arguments +print("Script name:", sys.argv[0]) +print("All arguments:", sys.argv) + +# Check if arguments are provided +if len(sys.argv) > 1: + name = sys.argv[1] + print(f"Hello, {name}!") +else: + print("No name provided. Usage: python script.py ") ``` -If this is named `test.py` it can be launched with the following result: +When running this script with `python greet.py Alice`, it produces the following output: -```bash -$ test.py --arg1 --arg2 "arg 3" -The program name used to launch me is test.py. -I was passed the following arguments: ---arg1 ---arg2 -arg 3 +```shell +Script name: greet.py +All arguments: ['greet.py', 'Alice'] +Hello, Alice! ``` -## Parsing With `getopt()` +The `sys.argv` list contains the script name as the first element, followed by all arguments passed from the command line. All arguments are stored as strings, so type conversion is needed for numeric operations. + +### Using `getopt` + +The `getopt` module provides a more structured approach to parsing command line options, similar to the C `getopt()` function. It supports both short options (single letters with a hyphen) and long options (words with double hyphens). -Using `getopt()` requires importing both the `sys` and `getopt` modules to work. With `getopt`, parameter validation is possible. This is done by passing a list of the command line arguments themselves, a string of short (one character) options, and a list of long (full word) options. To indicate that the option requires a value to be passed along with it, the short option is followed by a colon (`:`), and the long option is followed by an equals sign (`=`). +#### Example: File Processing with `getopt` -To set up options for "help", "argument", and a "value" that requires an additional passed value, would look like this: +This example shows how to create a script that processes input and output files with optional help: -- The short options would be a string like `"hav:"`. -- The long options would be a list like `["help","argument","value="]`. +```py +import sys +import getopt + +def main(): + input_file = "" + output_file = "" + + try: + # Parse command line options + opts, args = getopt.getopt(sys.argv[1:], "hi:o:", ["help", "input=", "output="]) + except getopt.GetoptError as err: + print(f"Error: {err}") + print("Usage: python script.py -i -o ") + sys.exit(2) + + for opt, arg in opts: + if opt in ("-h", "--help"): + print("Usage: python script.py -i -o ") + print("Options:") + print(" -i, --input Input file path") + print(" -o, --output Output file path") + print(" -h, --help Show this help message") + sys.exit() + elif opt in ("-i", "--input"): + input_file = arg + elif opt in ("-o", "--output"): + output_file = arg + + # Process the files + if input_file and output_file: + print(f"Processing: {input_file} -> {output_file}") + else: + print("Both input and output files are required") + sys.exit(1) + +if __name__ == "__main__": + main() +``` -### Syntax +Running this script with `python process.py -i data.txt -o result.txt` produces: -```python -options, values = getopt.getopt(arguments, short_options, long_options) +```shell +Processing: data.txt -> result.txt ``` -Where the results of `getopt()` are `options` which is a list of option/value pairs, and `values` which is a list of arguments left after the option list was stripped. The parameters passed to `getopt()` are `arguments`, a list of the arguments as provided by `sys.argv` without the initial program name, the string `short_options` and the list `long_options` as described above. +The `getopt.getopt()` function parses the argument list and returns a tuple containing option-value pairs and remaining arguments. Short options require a colon after the letter if they expect a value. -If `arguments` contains an option that is not in `short_options` or `long_options` then an `getopt.error` exception is thrown. +### Using `argparse` -### Example +The `argparse` module is the most powerful and user-friendly way to handle command line arguments. It automatically generates help messages, handles errors gracefully, and supports various argument types including positional and optional arguments. -This prints the option/value pairs passed as command line arguments. +#### Example: User Greeting with `argparse` + +This example demonstrates creating a user-friendly command line interface: ```py -import sys, getopt +import argparse + +# Create argument parser +parser = argparse.ArgumentParser(description="Greet users with customizable messages") + +# Add positional argument +parser.add_argument("name", help="Name of the person to greet") -arguments = sys.argv[1:] -short_options = "hav:" -long_options = ["help","argument","value="] +# Add optional arguments +parser.add_argument("-g", "--greeting", default="Hello", + help="Greeting message (default: Hello)") +parser.add_argument("-u", "--uppercase", action="store_true", + help="Convert output to uppercase") -options, values = getopt.getopt(arguments, short_options, long_options) +# Parse arguments +args = parser.parse_args() -for o, v in options: - print(f"Option is {o}. Value is {v}.") +# Create greeting message +message = f"{args.greeting}, {args.name}!" + +# Apply uppercase if requested +if args.uppercase: + message = message.upper() + +print(message) ``` -If this is named **test.py** it can be launched with the following results: +When executed with `python greet.py Alice -g "Good morning" --uppercase`, the output is: -```bash -$ test.py -a --value=test -Option is -a. Value is . -Option is --value. Value is test. +```shell +GOOD MORNING, ALICE! ``` -**Note**: Since `-a` wasn't defined as requiring a value passed to it, the corresponding value for the option is empty. +The `argparse` module automatically provides help documentation when using `-h` or `--help`, validates required arguments, and converts values to appropriate types. It handles argument parsing errors by displaying helpful error messages and usage information. + +## Frequently Asked Questions + +### 1. What are command line arguments in Python? + +Command line arguments in Python are values passed to a script when executing it from the terminal. They provide a way to customize program behavior without modifying the source code, making scripts more flexible and reusable. + +### 2. What are the 5 arguments in Python? + +There isn't a fixed set of "5 arguments" in Python. The number and type of command line arguments depend on what the program is designed to accept. However, common argument types include: positional arguments (required values), optional arguments (flags with values), boolean flags (on/off switches), help arguments, and version arguments. + +### 3. How to pass an argument to a Python script from command line? + +To pass arguments to a Python script, include them after the script name when running it: + +- `python script.py argument1 argument2` - passes multiple arguments +- `python script.py --option value` - passes an option with a value +- `python script.py -f --verbose` - passes flags and options + +### 4. What is an example of a command line argument? -## Other Methods of Parsing the Command Line +A simple example is running `python calculator.py 10 5 add`, where: -There are other methods of parsing command line arguments in Python, which add varying functionality to the task. Some examples include: +- `calculator.py` is the script name +- `10` and `5` are numeric arguments +- `add` is an operation argument -- The `argparse` module, that's been available since Python 3.2, validates fixed and optional arguments and offers a default help message displaying the accepted arguments. -- The `docopt` module, which is complex and versatile, provides its own language to describe command line options. -- The `click` module provides arbitrary nesting of commands and automatic help page generation. +The script can access these values using `sys.argv`, `getopt`, or `argparse` to perform the specified calculation. From 17d337a69f88d3daa70f0d35fc233ee77849af8d Mon Sep 17 00:00:00 2001 From: Mamta Wardhani Date: Thu, 25 Sep 2025 17:28:35 +0530 Subject: [PATCH 2/5] Update command-line-arguments.md --- .../command-line-arguments.md | 188 ++++++------------ 1 file changed, 56 insertions(+), 132 deletions(-) diff --git a/content/python/concepts/command-line-arguments/command-line-arguments.md b/content/python/concepts/command-line-arguments/command-line-arguments.md index 6c3b74536f5..d09f403722a 100644 --- a/content/python/concepts/command-line-arguments/command-line-arguments.md +++ b/content/python/concepts/command-line-arguments/command-line-arguments.md @@ -1,182 +1,106 @@ --- Title: 'Command Line Arguments' -Description: 'Provides methods to accept input values when running Python scripts from the terminal' +Description: 'Python offers several methods of parsing command line arguments that are used when launching a program.' Subjects: - - 'Code Foundations' - 'Computer Science' + - 'Data Science' Tags: + - 'Input' - 'Arguments' + - 'Bash/Shell' - 'Command Line' - - 'Input' - - 'Modules' CatalogContent: - 'learn-python-3' - 'paths/computer-science' --- -**Command line arguments** are values passed to a Python program when running it from the terminal or command prompt. They allow users to provide input data to a program without modifying the source code, making programs more flexible and reusable by accepting different parameters at runtime. +Python offers several methods of parsing **command line arguments** that are used when launching a program. The user has the option of passing various parameters to the program by adding them after the program name. These parameters can be accessed through various modules. The parameter names are left up to the programmer. By convention the parameter `-h` or `--help` (and `/h` and `/help` in Windows) is reserved to print a help message to the console listing the various command line options recognized by the program. + +Arguments are passed differently depending on the operating system: -## Ways to Handle Command Line Arguments +- Unix-like arguments are a single letter preceded by a dash (`-h`) or a word preceded by two dashes (`--help`). +- Windows arguments are a letter or a whole word preceded by a slash (`/h` or `/help`). -Python provides several built-in modules to handle command line arguments, each with different levels of complexity and functionality. +## Parsing With `sys.argv` -### Using `sys.argv` +The `sys` module offers the most straightforward method of accessing command line arguments, but it also requires the programmer to do most of the work interpreting them. With the `sys` module, the arguments are passed along in a simple list structure named `sys.argv`. -The `sys.argv` module provides the simplest way to access command line arguments. It stores all arguments passed to the script as a list of strings, where `sys.argv[0]` contains the script name itself. +The first item in the list, `sys.argv[0]` is the name used to launch the Python program, along with the path used. Each subsequent item is a space-delimited argument from the command line used to launch the program. If an argument requires embedded spaces, it needs to be enclosed in quotes to be parsed correctly. -#### Example: Basic `sys.argv` Usage +### Example -This example demonstrates how to access and use Python command line arguments using the `sys` module: +This prints the script name followed by a list of the command line arguments passed on to the program. ```py import sys -# Display all command line arguments -print("Script name:", sys.argv[0]) -print("All arguments:", sys.argv) - -# Check if arguments are provided -if len(sys.argv) > 1: - name = sys.argv[1] - print(f"Hello, {name}!") -else: - print("No name provided. Usage: python script.py ") +print(f"The program name used to launch me is {sys.argv[0]}.") +print("I was passed the following arguments:") +for arg in sys.argv[1:]: + print(arg) ``` -When running this script with `python greet.py Alice`, it produces the following output: +If this is named `test.py` it can be launched with the following result: -```shell -Script name: greet.py -All arguments: ['greet.py', 'Alice'] -Hello, Alice! +```bash +$ test.py --arg1 --arg2 "arg 3" +The program name used to launch me is test.py. +I was passed the following arguments: +--arg1 +--arg2 +arg 3 ``` -The `sys.argv` list contains the script name as the first element, followed by all arguments passed from the command line. All arguments are stored as strings, so type conversion is needed for numeric operations. - -### Using `getopt` - -The `getopt` module provides a more structured approach to parsing command line options, similar to the C `getopt()` function. It supports both short options (single letters with a hyphen) and long options (words with double hyphens). +## Parsing With `getopt()` -#### Example: File Processing with `getopt` +Using `getopt()` requires importing both the `sys` and `getopt` modules to work. With `getopt`, parameter validation is possible. This is done by passing a list of the command line arguments themselves, a string of short (one character) options, and a list of long (full word) options. To indicate that the option requires a value to be passed along with it, the short option is followed by a colon (`:`), and the long option is followed by an equals sign (`=`). -This example shows how to create a script that processes input and output files with optional help: +To set up options for "help", "argument", and a "value" that requires an additional passed value, would look like this: -```py -import sys -import getopt - -def main(): - input_file = "" - output_file = "" - - try: - # Parse command line options - opts, args = getopt.getopt(sys.argv[1:], "hi:o:", ["help", "input=", "output="]) - except getopt.GetoptError as err: - print(f"Error: {err}") - print("Usage: python script.py -i -o ") - sys.exit(2) - - for opt, arg in opts: - if opt in ("-h", "--help"): - print("Usage: python script.py -i -o ") - print("Options:") - print(" -i, --input Input file path") - print(" -o, --output Output file path") - print(" -h, --help Show this help message") - sys.exit() - elif opt in ("-i", "--input"): - input_file = arg - elif opt in ("-o", "--output"): - output_file = arg - - # Process the files - if input_file and output_file: - print(f"Processing: {input_file} -> {output_file}") - else: - print("Both input and output files are required") - sys.exit(1) - -if __name__ == "__main__": - main() -``` +- The short options would be a string like `"hav:"`. +- The long options would be a list like `["help","argument","value="]`. -Running this script with `python process.py -i data.txt -o result.txt` produces: +### Syntax -```shell -Processing: data.txt -> result.txt +```python +options, values = getopt.getopt(arguments, short_options, long_options) ``` -The `getopt.getopt()` function parses the argument list and returns a tuple containing option-value pairs and remaining arguments. Short options require a colon after the letter if they expect a value. +Where the results of `getopt()` are `options` which is a list of option/value pairs, and `values` which is a list of arguments left after the option list was stripped. The parameters passed to `getopt()` are `arguments`, a list of the arguments as provided by `sys.argv` without the initial program name, the string `short_options` and the list `long_options` as described above. -### Using `argparse` +If `arguments` contains an option that is not in `short_options` or `long_options` then an `getopt.error` exception is thrown. -The `argparse` module is the most powerful and user-friendly way to handle command line arguments. It automatically generates help messages, handles errors gracefully, and supports various argument types including positional and optional arguments. +### Example -#### Example: User Greeting with `argparse` - -This example demonstrates creating a user-friendly command line interface: +This prints the option/value pairs passed as command line arguments. ```py -import argparse - -# Create argument parser -parser = argparse.ArgumentParser(description="Greet users with customizable messages") - -# Add positional argument -parser.add_argument("name", help="Name of the person to greet") +import sys, getopt -# Add optional arguments -parser.add_argument("-g", "--greeting", default="Hello", - help="Greeting message (default: Hello)") -parser.add_argument("-u", "--uppercase", action="store_true", - help="Convert output to uppercase") +arguments = sys.argv[1:] +short_options = "hav:" +long_options = ["help","argument","value="] -# Parse arguments -args = parser.parse_args() +options, values = getopt.getopt(arguments, short_options, long_options) -# Create greeting message -message = f"{args.greeting}, {args.name}!" - -# Apply uppercase if requested -if args.uppercase: - message = message.upper() - -print(message) +for o, v in options: + print(f"Option is {o}. Value is {v}.") ``` -When executed with `python greet.py Alice -g "Good morning" --uppercase`, the output is: +If this is named **test.py** it can be launched with the following results: -```shell -GOOD MORNING, ALICE! +```bash +$ test.py -a --value=test +Option is -a. Value is . +Option is --value. Value is test. ``` -The `argparse` module automatically provides help documentation when using `-h` or `--help`, validates required arguments, and converts values to appropriate types. It handles argument parsing errors by displaying helpful error messages and usage information. - -## Frequently Asked Questions - -### 1. What are command line arguments in Python? - -Command line arguments in Python are values passed to a script when executing it from the terminal. They provide a way to customize program behavior without modifying the source code, making scripts more flexible and reusable. - -### 2. What are the 5 arguments in Python? - -There isn't a fixed set of "5 arguments" in Python. The number and type of command line arguments depend on what the program is designed to accept. However, common argument types include: positional arguments (required values), optional arguments (flags with values), boolean flags (on/off switches), help arguments, and version arguments. - -### 3. How to pass an argument to a Python script from command line? - -To pass arguments to a Python script, include them after the script name when running it: - -- `python script.py argument1 argument2` - passes multiple arguments -- `python script.py --option value` - passes an option with a value -- `python script.py -f --verbose` - passes flags and options - -### 4. What is an example of a command line argument? +**Note**: Since `-a` wasn't defined as requiring a value passed to it, the corresponding value for the option is empty. -A simple example is running `python calculator.py 10 5 add`, where: +## Other Methods of Parsing the Command Line -- `calculator.py` is the script name -- `10` and `5` are numeric arguments -- `add` is an operation argument +There are other methods of parsing command line arguments in Python, which add varying functionality to the task. Some examples include: -The script can access these values using `sys.argv`, `getopt`, or `argparse` to perform the specified calculation. +- The `argparse` module, that's been available since Python 3.2, validates fixed and optional arguments and offers a default help message displaying the accepted arguments. +- The `docopt` module, which is complex and versatile, provides its own language to describe command line options. +- The `click` module provides arbitrary nesting of commands and automatic help page generation. From 10578df419be463cf76952beb5b94d172adaa256 Mon Sep 17 00:00:00 2001 From: Mamta Wardhani Date: Wed, 5 Nov 2025 16:24:59 +0530 Subject: [PATCH 3/5] [Term Entry] PyTorch Tensor Operations: .log2() --- .../tensor-operations/terms/log2/log2.md | 79 +++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 docs/content/pytorch/concepts/tensor-operations/terms/log2/log2.md diff --git a/docs/content/pytorch/concepts/tensor-operations/terms/log2/log2.md b/docs/content/pytorch/concepts/tensor-operations/terms/log2/log2.md new file mode 100644 index 00000000000..e617fb45add --- /dev/null +++ b/docs/content/pytorch/concepts/tensor-operations/terms/log2/log2.md @@ -0,0 +1,79 @@ +--- +Title: '.log2()' +Description: 'Computes the base-2 logarithm of each element in the input tensor and returns a new tensor with the results.' +Subjects: + - 'Code Foundations' + - 'Computer Science' + - 'Data Science' +Tags: + - 'Elements' + - 'Methods' + - 'PyTorch' + - 'Tensors' +CatalogContent: + - 'learn-python-3' + - 'paths/data-science' +--- + +The **`.log2()`** method in PyTorch returns a new [tensor](https://www.codecademy.com/resources/docs/pytorch/tensors) by computing the logarithm base 2 of each element in the input tensor. This operation is useful in numerous data-science and machine-learning workflows where values are interpreted on a log scale (e.g., information theory, binary magnitude comparisons). + +## Syntax + +```pseudo +torch.log2(input, *, out=None) → Tensor +``` + +**Parameters:** + +- `input` (Tensor): The tensor whose elements are to be transformed by base-2 logarithm. +- `out` (Tensor, optional): A tensor to store the output; must have the same shape as input if provided. + +**Return value:** + +Returns a new tensor of the same shape as `input` where each element is `log₂(input[i])`. + +## Example 1: Basic Usage of `torch.log2()` + +In this example, the base-2 logarithm is computed for a tensor of powers of two: + +```py +import torch + +# Define a tensor +input_tensor = torch.tensor([2.0, 4.0, 8.0, 16.0, 32.0]) + +# Compute base-2 logarithm +output_tensor = torch.log2(input_tensor) + +print(output_tensor) +``` + +The output of this code is: + +```shell +tensor([1., 2., 3., 4., 5.]) +``` + +## Example 2: Applying `torch.log2()` on Random Values + +In this example, a tensor with random positive values is transformed using base-2 logarithm to analyze data on a log scale: + +```py +import torch + +# Generate a tensor of random positive values +data = torch.rand(5) * 10 + 1 + +# Apply log2 transformation +log_tensor = torch.log2(data) + +print(data) +print(log_tensor) +``` + +The output of this code is: + +```shell +tensor([10.5500, 9.2777, 10.9371, 1.3551, 5.2609]) +tensor([3.3992, 3.2138, 3.4512, 0.4384, 2.3953]) +``` From 3502fbb615bfa569c1f365094598a7480209424a Mon Sep 17 00:00:00 2001 From: Mamta Wardhani Date: Wed, 5 Nov 2025 16:37:50 +0530 Subject: [PATCH 4/5] [Term Entry] PyTorch Tensor Operations: .logaddexp() --- .../terms/logaddexp/logaddexp.md | 82 +++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 content/pytorch/concepts/tensor-operations/terms/logaddexp/logaddexp.md diff --git a/content/pytorch/concepts/tensor-operations/terms/logaddexp/logaddexp.md b/content/pytorch/concepts/tensor-operations/terms/logaddexp/logaddexp.md new file mode 100644 index 00000000000..bee3898da6e --- /dev/null +++ b/content/pytorch/concepts/tensor-operations/terms/logaddexp/logaddexp.md @@ -0,0 +1,82 @@ +--- +Title: '.logaddexp()' +Description: 'Computes the element-wise logarithm of the sum of exponentials of two input tensors.' +Subjects: + - 'Code Foundations' + - 'Computer Science' + - 'Data Science' +Tags: + - 'Elements' + - 'Methods' + - 'PyTorch' + - 'Tensors' +CatalogContent: + - 'learn-python-3' + - 'paths/data-science' +--- + +The **`.logaddexp()`** function in PyTorch computes the point-wise value of: + +$$\log(\exp(x) + \exp(y))$$ + +for two input tensors `x` and `y`. This operation is particularly useful for combining log-space values (such as log-probabilities) in a numerically stable way. + +## Syntax + +```pseudo +torch.logaddexp(input, other, *, out=None) → Tensor +``` + +**Parameters:** + +- `input` (Tensor): The first input tensor. +- `other` (Tensor): The second input tensor, broadcastable to the shape of `input`. +- `out` (Tensor, optional): A tensor to store the output; must have the same shape as the broadcasted result if provided. + +**Return value:** + +Returns a new tensor of the same shape as the broadcasted `input` and `other`, where each element is: + +$$\log\left(\exp(\text{input}[i]) + \exp(\text{other}[i])\right)$$ + +## Example 1: Combining log-probabilities + +In this example, two tensors representing log-probabilities are combined using `.logaddexp()`: + +```py +import torch + +x = torch.tensor([ -0.5, -1.2, -3.0 ]) +y = torch.tensor([ -0.2, -0.8, -4.5 ]) + +result = torch.logaddexp(x, y) +print(result) +``` + +The ouput of this code is: + +```shell +tensor([ 0.3544, -0.2870, -2.7986]) +``` + +## Example 2: Broadcasting two tensors of different shapes + +In this example, a tensor and a scalar are combined with broadcasting using `.logaddexp()`: + +```py +import torch + +x = torch.tensor([[ 1.0, 2.0 ,3.0], + [ 4.0, 5.0 ,6.0]]) +y = torch.tensor( 2.0 ) + +result = torch.logaddexp(x, y) +print(result) +``` + +The output of this code is: + +```shell +tensor([[2.3133, 2.6931, 3.3133], + [4.1269, 5.0486, 6.0181]]) +``` From d1bd0c731ac8bf8de1f0eae0921bbde88ef1316a Mon Sep 17 00:00:00 2001 From: Mamta Wardhani Date: Wed, 5 Nov 2025 16:39:00 +0530 Subject: [PATCH 5/5] Delete docs/content/pytorch/concepts/tensor-operations/terms/log2/log2.md --- .../tensor-operations/terms/log2/log2.md | 79 ------------------- 1 file changed, 79 deletions(-) delete mode 100644 docs/content/pytorch/concepts/tensor-operations/terms/log2/log2.md diff --git a/docs/content/pytorch/concepts/tensor-operations/terms/log2/log2.md b/docs/content/pytorch/concepts/tensor-operations/terms/log2/log2.md deleted file mode 100644 index e617fb45add..00000000000 --- a/docs/content/pytorch/concepts/tensor-operations/terms/log2/log2.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -Title: '.log2()' -Description: 'Computes the base-2 logarithm of each element in the input tensor and returns a new tensor with the results.' -Subjects: - - 'Code Foundations' - - 'Computer Science' - - 'Data Science' -Tags: - - 'Elements' - - 'Methods' - - 'PyTorch' - - 'Tensors' -CatalogContent: - - 'learn-python-3' - - 'paths/data-science' ---- - -The **`.log2()`** method in PyTorch returns a new [tensor](https://www.codecademy.com/resources/docs/pytorch/tensors) by computing the logarithm base 2 of each element in the input tensor. This operation is useful in numerous data-science and machine-learning workflows where values are interpreted on a log scale (e.g., information theory, binary magnitude comparisons). - -## Syntax - -```pseudo -torch.log2(input, *, out=None) → Tensor -``` - -**Parameters:** - -- `input` (Tensor): The tensor whose elements are to be transformed by base-2 logarithm. -- `out` (Tensor, optional): A tensor to store the output; must have the same shape as input if provided. - -**Return value:** - -Returns a new tensor of the same shape as `input` where each element is `log₂(input[i])`. - -## Example 1: Basic Usage of `torch.log2()` - -In this example, the base-2 logarithm is computed for a tensor of powers of two: - -```py -import torch - -# Define a tensor -input_tensor = torch.tensor([2.0, 4.0, 8.0, 16.0, 32.0]) - -# Compute base-2 logarithm -output_tensor = torch.log2(input_tensor) - -print(output_tensor) -``` - -The output of this code is: - -```shell -tensor([1., 2., 3., 4., 5.]) -``` - -## Example 2: Applying `torch.log2()` on Random Values - -In this example, a tensor with random positive values is transformed using base-2 logarithm to analyze data on a log scale: - -```py -import torch - -# Generate a tensor of random positive values -data = torch.rand(5) * 10 + 1 - -# Apply log2 transformation -log_tensor = torch.log2(data) - -print(data) -print(log_tensor) -``` - -The output of this code is: - -```shell -tensor([10.5500, 9.2777, 10.9371, 1.3551, 5.2609]) -tensor([3.3992, 3.2138, 3.4512, 0.4384, 2.3953]) -```