人工智能之数据分析 numpy
第九章 数组运算(二)
@
前言
NumPy 提供了丰富的数学与统计函数,覆盖三角、指数对数、舍入、向量运算、概率统计等多个领域。这些函数都是通用函数(ufunc),支持向量化操作,可直接作用于整个数组,无需循环。
本文紧接上一章系统梳理 NumPy 中常用的数学与统计函数。
一、三角函数(Trigonometric Functions)
所有三角函数默认使用弧度作为输入。
| 函数 | 说明 |
|---|---|
np.sin(x),np.cos(x),np.tan(x) |
正弦、余弦、正切 |
np.arcsin(x),np.arccos(x),np.arctan(x) |
反三角函数 |
np.hypot(x, y) |
计算 $\sqrt{x^2 + y^2}$(直角三角形斜边) |
np.deg2rad(x)/np.radians(x) |
角度 → 弧度 |
np.rad2deg(x)/np.degrees(x) |
弧度 → 角度 |
示例:
import numpy as np
angles_deg = np.array([0, 30, 45, 60, 90])
angles_rad = np.deg2rad(angles_deg)
print("sin:", np.sin(angles_rad))
# [0. 0.5 0.70710678 0.8660254 1. ]
# 反函数(注意定义域)
x = np.array([0, 0.5, 1])
print("arcsin (rad):", np.arcsin(x))
print("arcsin (deg):", np.rad2deg(np.arcsin(x)))
# [0. 30. 90.]
⚠️ 注意:
arcsin和arccos的输入必须在 $[-1, 1]$ 范围内,否则返回nan。
二、双曲函数(Hyperbolic Functions)
| 函数 | 说明 |
|---|---|
np.sinh(x),np.cosh(x),np.tanh(x) |
双曲正弦/余弦/正切 |
np.arcsinh(x),np.arccosh(x),np.arctanh(x) |
反双曲函数 |
三、指数与对数函数
| 函数 | 说明 |
|---|---|
np.exp(x) |
$e^x$ |
np.exp2(x) |
$2^x$ |
np.power(x, y) |
$x^y$(支持广播) |
np.log(x) |
自然对数 $\ln x$ |
np.log2(x),np.log10(x) |
以 2 或 10 为底的对数 |
np.log1p(x) |
$\ln(1 + x)$(对小 x 更精确) |
示例:
x = np.array([1, 2, np.e])
print("exp:", np.exp(x)) # [2.718..., 7.389..., 15.154...]
print("log(exp(x)):", np.log(np.exp(x))) # ≈ x
# log1p 避免小数精度损失
small = 1e-10
print(np.log(1 + small)) # 可能为 0.0(精度丢失)
print(np.log1p(small)) # 精确值 ≈ 1e-10
四、舍入函数(Rounding)
| 函数 | 说明 |
|---|---|
np.around(a, decimals=0)/np.round(a) |
四舍五入 |
np.floor(a) |
向下取整(≤ x 的最大整数) |
np.ceil(a) |
向上取整(≥ x 的最小整数) |
np.trunc(a)/np.fix(a) |
截断小数部分(向零取整) |
np.rint(a) |
四舍五入到最近整数(返回 float) |
示例:
x = np.array([-2.7, -2.3, 2.3, 2.7])
print("round :", np.round(x)) # [-3. -2. 2. 3.]
print("floor :", np.floor(x)) # [-3. -3. 2. 2.]
print("ceil :", np.ceil(x)) # [-2. -2. 3. 3.]
print("trunc :", np.trunc(x)) # [-2. -2. 2. 2.]
💡
np.round()遵循“银行家舍入”规则:0.5舍入到最近的偶数(如np.round(2.5) → 2.0)。
五、向量与矩阵函数(线性代数相关)
虽然大部分在线性代数模块 np.linalg,但以下常用函数在主命名空间:
| 函数 | 说明 |
|---|---|
np.dot(a, b) |
点积 / 矩阵乘法 |
np.vdot(a, b) |
共轭点积(主要用于复数) |
np.inner(a, b) |
内积(对高维是逐最后轴求和) |
np.outer(a, b) |
外积(返回矩阵) |
np.cross(a, b) |
向量叉积(仅适用于 3D 或 2D) |
np.linalg.norm(x, ord=2) |
向量/矩阵范数(L2 默认) |
示例:
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print("dot :", np.dot(a, b)) # 32
print("inner :", np.inner(a, b)) # 32
print("outer :\n", np.outer(a, b))
# [[ 4 5 6]
# [ 8 10 12]
# [12 15 18]]
print("norm :", np.linalg.norm(a)) # √14 ≈ 3.7417
六、统计相关函数
1. 基础统计量(支持 axis 参数)
| 函数 | 说明 |
|---|---|
np.sum(a) |
求和 |
np.mean(a) |
均值 |
np.median(a) |
中位数 |
np.std(a) |
标准差(默认除以 N,非 N-1) |
np.var(a) |
方差 |
np.min(a),np.max(a) |
最小/最大值 |
np.argmin(a),np.argmax(a) |
最值索引 |
np.percentile(a, q) |
分位数(q 为 0~100) |
np.quantile(a, q) |
分位数(q 为 0~1) |
🔍 注意:
np.std()默认使用 总体标准差(ddof=0),若需样本标准差,用np.std(a, ddof=1)。
2. 高级统计
| 函数 | 说明 |
|---|---|
np.cov(x, y) |
协方差矩阵 |
np.corrcoef(x, y) |
相关系数矩阵 |
np.histogram(a, bins=10) |
直方图(返回 counts 和 bin_edges) |
np.bincount(x) |
整数数组的频次统计(类似 one-hot 计数) |
np.unique(a, return_counts=True) |
唯一值及出现次数 |
示例:
data = np.array([1, 2, 2, 3, 4, 4, 4])
# 频次统计
values, counts = np.unique(data, return_counts=True)
print("Unique:", values) # [1 2 3 4]
print("Counts:", counts) # [1 2 1 3]
# 相关系数
x = np.array([1, 2, 3, 4])
y = np.array([2, 4, 6, 8])
print("Corr coef:", np.corrcoef(x, y)[0, 1]) # 1.0(完全正相关)
七、特殊函数(SciPy 更全,但 NumPy 有基础)
| 函数 | 说明 |
|---|---|
np.sign(x) |
符号函数(-1, 0, 1) |
np.abs(x)/np.fabs(x) |
绝对值 |
np.sqrt(x) |
平方根 |
np.square(x) |
平方 |
np.clip(a, a_min, a_max) |
限幅(clamp) |
np.where(condition, x, y) |
条件选择 |
np.interp(x, xp, fp) |
一维线性插值 |
示例:限幅与插值
arr = np.array([-2, -1, 0, 1, 2])
clipped = np.clip(arr, -1, 1) # [-1 -1 0 1 1]
# 插值:已知 xp=[0,1,2], fp=[0,1,4],求 x=0.5 处的值
x_new = 0.5
y_new = np.interp(x_new, [0,1,2], [0,1,4]) # 0.5
八、随机数生成(np.random 模块)
虽然属于随机模块,但常用于统计模拟:
# 设置种子(推荐用新式 Generator)
rng = np.random.default_rng(seed=42)
rng.random(5) # 均匀分布 [0,1)
rng.normal(0, 1, 1000) # 正态分布
rng.randint(0, 10, 5) # 整数随机
rng.choice([1,2,3], size=5) # 抽样
✅ 推荐使用
Generator(default_rng)而非旧式np.random.seed()。
九、性能提示
- 所有上述函数都是 ufunc,自动并行化(底层 C 实现)
- 避免在循环中调用,直接作用于整个数组
- 对于超大数组,考虑内存映射或分块处理
十、总结:常用函数速查表
| 类别 | 常用函数 |
|---|---|
| 三角 | sin,cos,tan,arcsin,deg2rad |
| 指数对数 | exp,log,log10,log1p |
| 舍入 | round,floor,ceil,trunc |
| 向量 | dot,norm,cross,outer |
| 统计 | mean,std,median,percentile,unique,corrcoef |
| 实用 | abs,sign,clip,where,interp |
掌握这些函数,你就能高效完成科学计算、数据分析、信号处理、机器学习中的绝大多数数值任务。对于更复杂的统计模型(如假设检验、回归),建议结合 SciPy.stats 或 statsmodels。
后续
本文紧接上一章主要讲述了numpy数组相关的数学与统计运算。python过渡项目部分代码已经上传至gitee,后续会逐步更新,主要受时间原因限制,当然自己也可以克隆到本地学习拓展。
资料关注
公众号:咚咚王
gitee:https://gitee.com/wy18585051844/ai_learning

《Python编程:从入门到实践》
《利用Python进行数据分析》
《算法导论中文第三版》
《概率论与数理统计(第四版) (盛骤) 》
《程序员的数学》
《线性代数应该这样学第3版》
《微积分和数学分析引论》
《(西瓜书)周志华-机器学习》
《TensorFlow机器学习实战指南》
《Sklearn与TensorFlow机器学习实用指南》
《模式识别(第四版)》
《深度学习 deep learning》伊恩·古德费洛著 花书
《Python深度学习第二版(中文版)【纯文本】 (登封大数据 (Francois Choliet)) (Z-Library)》
《深入浅出神经网络与深度学习+(迈克尔·尼尔森(Michael+Nielsen)》
《自然语言处理综论 第2版》
《Natural-Language-Processing-with-PyTorch》
《计算机视觉-算法与应用(中文版)》
《Learning OpenCV 4》
《AIGC:智能创作时代》杜雨+&+张孜铭
《AIGC原理与实践:零基础学大语言模型、扩散模型和多模态模型》
《从零构建大语言模型(中文版)》
《实战AI大模型》
《AI 3.0》
posted on
浙公网安备 33010602011771号