9951 explained code solutions for 126 technologies


python-pytorchHow can I calculate the mean value using Python and PyTorch?


Calculating the mean value using Python and PyTorch is relatively simple. To do this, you will need to import the torch library and create a tensor with the values you want to calculate the mean of.

import torch

# Create a tensor with values
values = torch.tensor([1.0, 2.0, 3.0, 4.0])

# Calculate the mean
mean_val = torch.mean(values)

# Print the mean
print(mean_val)

Output example

tensor(2.5000)

The code above consists of:

  1. Importing the torch library: This imports the torch library so that it can be used in the code.
  2. Creating a tensor with values: This creates a tensor with the values you want to calculate the mean of.
  3. Calculating the mean: This uses the torch.mean() function to calculate the mean of the values in the tensor.
  4. Printing the mean: This prints the mean value.

For more information and examples, please refer to the following links:

Edit this code on GitHub