NumPy 标准差函数

NumPyNumPyBeginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

介绍

在本实验中,我们将介绍 NumPy 库中的 numpy.std() 函数。我们将了解标准差(standard deviation)的含义,并学习如何使用 numpy.std() 来计算数组的标准差。

虚拟机使用提示

虚拟机启动完成后,点击左上角切换到 Notebook 标签页,以访问 Jupyter Notebook 进行练习。

有时,你可能需要等待几秒钟,直到 Jupyter Notebook 完成加载。由于 Jupyter Notebook 的限制,操作验证无法自动化。

如果你在学习过程中遇到问题,可以随时向 Labby 寻求帮助。实验结束后请提供反馈,我们将及时为你解决问题。

理解标准差

标准差(Standard Deviation)是衡量一组数值变化或离散程度的指标。从数学上讲,标准差定义为与均值的平方偏差的平均值的平方根。让我们来看一下标准差的公式:

std = \sqrt{\frac{\sum_{i=1}^{n} (x_i-\bar{x})^2}{n}}

其中,\bar{x} 是数组元素的均值,x_i 是数组的第 i 个元素,n 是数组中元素的数量。

numpy.std() 的语法

使用 numpy.std() 函数所需的语法如下:

numpy.std(a, axis=None, dtype=None, out=None)

参数:

  • a: 输入数组
  • axis: 计算标准差的轴。默认情况下,计算的是展平后的数组。
  • dtype: 返回输出的期望数据类型
  • out: 存储输出的数组

返回值:

返回数组的标准差,或沿指定轴的标准差值数组。

示例

让我们来看一个使用 numpy.std() 的简单示例。

import numpy as np

## 创建 2D 数组
a = np.array([[11, 2], [13, 44]])
print("The array is:\n",a)

## 计算展平数组的标准差
print("Standard Deviation is :")
print(np.std(a))

## 计算沿轴 0 的标准差
print("Standard Deviation along axis 0:")
print(np.std(a, axis=0))

## 计算沿轴 1 的标准差
print("Standard Deviation along axis 1:")
print(np.std(a, axis=1))

输出:

The array is:
[[11  2]
 [13 44]]
Standard Deviation is :
15.850867484147358
Standard Deviation along axis 0:
[ 1. 21.]
Standard Deviation along axis 1:
[ 4.5 15.5]

精度

让我们来看一个示例,其中我们可以为输出指定数据类型。

import numpy as np

inp = [22, 2, 17, 11, 34]

print("The input array is : ")
print(inp)

## 计算标准差
print("The standard deviation of the Input Array is: ")
print(np.std(inp))

## 使用 float32 获得更高精度
print("\nTo get More precision with float32")
print("Thus std of array is : ", np.std(inp, dtype=np.float32))

## 使用 float64 获得更高准确性
print("\nTo get More accuracy with float64")
print("The std of array is : ", np.std(inp, dtype=np.float64))

输出:

The input array is:
[22, 2, 17, 11, 34]
The standard deviation of the Input Array is:
10.721940122944167

To get More precision with float32
Thus std of array is : 10.72194

To get More accuracy with float64
The std of array is: 10.721940122944167

注意:为了更准确地计算标准差,使用了 dtype float64

总结

在本实验中,我们学习了 numpy.std() 函数,它用于计算数组沿指定轴的标准差。此外,我们了解了 numpy.std() 的语法以及可以传递的不同参数。最后,我们通过一些示例理解了 numpy.std() 的工作原理。