如何计算 PyTorch 中张量的均值和标准差?

阅读 2062 收藏 0 点赞 0 评论 0

PyTorch 张量就像一个 numpy 数组。唯一的区别是张量利用 GPU 来加速数值计算。使用该方法计算张量的平均值。它返回输入张量中所有元素的平均值。我们还可以按行和列计算平均值,提供合适的轴或暗度。torch.mean()

张量的标准偏差使用 计算。它返回张量中所有元素的标准偏差。像mean一样,我们也可以计算标准偏差,行或列。torch.std()

脚步

  • 导入所需的库。在以下所有 Python 示例中,所需的 Python 库是torch。确保您已经安装了它。

  • 定义一个 PyTorch 张量并打印它。

  • 使用 计算平均值。在这里,输入是应该计算均值的张量,轴(或dim)是维度列表。将计算出的均值分配给一个新变量。torch.mean(input, axis)

  • 使用 计算标准偏差。在这里,输入是张量(或dim)是维度列表。将计算出的标准偏差分配给新变量。torch.std(input, axis)

  • 打印上面计算的平均值和标准偏差。

示例 1

以下 Python 程序展示了如何计算一维张量的均值和标准差。

# Python program to compute mean and standard
# deviation of a 1D tensor
# import the library
import torch

# Create a tensor
T = torch.Tensor([2.453, 4.432, 0.754, -6.554])
print("T:", T)

# Compute the mean and standard deviation
mean = torch.mean(T)
std = torch.std(T)

# Print the computed mean and standard deviation
print("Mean:", mean)
print("标准差:", std)
输出结果
T: tensor([ 2.4530, 4.4320, 0.7540, -6.5540])
Mean: tensor(0.2713)
标准差: tensor(4.7920)

示例 2

下面的 Python 程序展示了如何计算二维张量的均值和标准差,即行列式和列式

# import necessary library
import torch

# create a 3x4 2D tensor
T = torch.Tensor([[2,4,7,-6],
[7,33,-62,23],
[2,-6,-77,54]])
print("T:\n", T)

# compute the mean and standard deviation
mean = torch.mean(T)
std = torch.std(T)
print("Mean:", mean)
print("标准差:", std)

# Compute column-wise mean and std
mean = torch.mean(T, axis = 0)
std = torch.std(T, axis = 0)
print("Column-wise Mean:\n", mean)
print("Column-wise 标准差:\n", std)

# Compute row-wise mean and std
mean = torch.mean(T, axis = 1)
std = torch.std(T, axis = 1)
print("Row-wise Mean:\n", mean)
print("Row-wise 标准差:\n", std)
输出结果
T:
tensor([[ 2., 4., 7., -6.],
         [ 7., 33., -62., 23.],
         [ 2., -6., -77., 54.]])
Mean: tensor(-1.5833)
标准差: tensor(36.2703)
Column-wise Mean:
tensor([ 3.6667, 10.3333, -44.0000, 23.6667])
Column-wise 标准差:
tensor([ 2.8868, 20.2567, 44.7996, 30.0056])
Row-wise Mean:
tensor([ 1.7500, 0.2500, -6.7500])
Row-wise 标准差:
tensor([ 5.5603, 42.8593, 53.8602])

评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号