SciPy(Scientific Python)是Python科学计算生态系统中的基石库,它建立在NumPy之上,提供了大量用于科学计算、优化、积分、插值、信号处理、线性代数、统计和图像处理等领域的高级函数。本指南将深入解析SciPy的核心模块和函数,通过详细的代码示例展示如何在科学计算和数据处理中高效应用这些工具。
1. SciPy简介与安装
1.1 SciPy概述
SciPy是一个开源的Python库,专为科学计算和工程应用设计。它包含以下主要模块:
scipy.integrate
:数值积分和微分方程求解
scipy.optimize
:函数优化和方程求解
scipy.interpolate
:插值和样条函数
scipy.linalg
:线性代数运算(比NumPy更高级)
scipy.stats
:统计分布和假设检验
scipy.signal
:信号处理
scipy.sparse
:稀疏矩阵运算
scipy.ndimage
:多维图像处理
1.2 安装SciPy
# 通过pip安装
pip install scipy
# 通过conda安装(推荐用于科学计算环境)
conda install scipy
# 验证安装
import scipy
print(scipy.__version__) # 输出当前版本,如1.10.1
2. 数值积分与微分方程求解(scipy.integrate)
2.1 定积分计算
scipy.integrate.quad
函数用于计算单变量函数的定积分。
import numpy as np
from scipy.integrate import quad
# 定义被积函数
def f(x):
return np.sin(x) * np.exp(-x**2)
# 计算定积分:∫₀^∞ sin(x)*e^(-x²) dx
result, error = quad(f, 0, np.inf)
print(f”积分结果: {result:.6f}”)
print(f”估计误差: {error:.2e}”)
# 计算带参数的积分
def g(x, a, b):
return a * x**2 + b * np.sin(x)
result, error = quad(g, 0, 1, args=(2, 3)) # a=2, b=3
print(f”带参数积分结果: {result:.6f}”)
2.2 二重积分
from scipy.integrate import dblquad
# 定义二重积分函数
def h(x, y):
return np.sin(x) * np.cos(y)
# 计算∫₀^π ∫₀^π sin(x)*cos(y) dy dx
result, error = dblquad(h, 0, np.pi, lambda x: 0, lambda x: np.pi)
print(f”二重积分结果: {result:.6f}”)
print(f”估计误差: {error:.2e}”)
2.3 常微分方程(ODE)求解
scipy.integrate.solve_ivp
用于求解初值问题。
from scipy.integrate import solve_ivp
import matplotlib.pyplot as plt
# 定义ODE系统:dy/dt = -k*y (指数衰减)
def exponential_decay(t, y, k):
return -k * y
# 初始条件和参数
y0 = [1.0] # 初始值
k = 0.5 # 衰减常数
t_span = (0, 10) # 时间范围
t_eval = np.linspace(0, 10, 100) # 评估点
# 求解ODE
sol = solve_ivp(exponential_decay, t_span, y0, args=(k,), t_eval=t_eval)
# 绘制结果
plt.figure(figsize=(8, 5))
plt.plot(sol.t, sol.y[0], ‘b-‘, linewidth=2, label=’数值解’)
plt.plot(sol.t, np.exp(-k*sol.t), ‘r–‘, linewidth=1, label=’解析解’)
plt.xlabel(‘时间 t’)
plt.ylabel(‘y(t)’)
plt.title(‘指数衰减ODE求解’)
plt.legend()
plt.grid(True)
plt.show()
2.4 刚性ODE求解
对于刚性方程,使用
method=’Radau’
或
method=’BDF’
。
# 刚性ODE示例:dy/dt = -1000*y + 1
def stiff_ode(t, y):
return -1000 * y + 1
# 使用BDF方法求解
sol_stiff = solve_ivp(stiff_ode, (0, 0.01), [0.0], method=’BDF’)
print(f”刚性ODE在t=0.01时的解: {sol_stiff.y[0][-1]:.6f}”)
3. 函数优化与方程求解(scipy.optimize)
3.1 无约束优化
scipy.optimize.minimize
用于最小化标量函数。
from scipy.optimize import minimize
# 定义目标函数:Rosenbrock函数(经典优化测试函数)
def rosenbrock(x):
return sum(100.0*(x[1:]-x[:-1]**2.0)**2.0 + (1-x[:-1])**2.0)
# 初始点
x0 = np.array([1.3, 0.7, 0.8, 1.9, 1.2])
# 使用BFGS算法优化
result = minimize(rosenbrock, x0, method=’BFGS’)
print(f”优化结果: {result.x}”)
print(f”最小值: {result.fun}”)
print(f”是否成功: {result.success}”)
print(f”迭代次数: {result.nit}”)
3.2 约束优化
from scipy.optimize import minimize
# 目标函数
def objective(x):
return (x[0] – 1)**2 + (x[1] – 2.5)**2
# 约束条件
def constraint1(x):
return x[0] + x[1] – 2 # x[0] + x[1] >= 2
def constraint2(x):
return 2*x[0] + x[1] – 3 # 2*x[0] + x[1] >= 3
# 约束字典
constraints = [
{‘type’: ‘ineq’, ‘fun’: constraint1},
{‘type’: ‘ineq’, ‘fun’: constraint2}
]
# 边界条件
bounds = [(0, None), (0, None)] # x[0] >= 0, x[1] >= 0
# 初始点
x0 = [0.5, 0.5]
# 求解约束优化
result = minimize(objective, x0, method=’SLSQP’, bounds=bounds, constraints=constraints)
print(f”约束优化结果: {result.x}”)
print(f”目标函数值: {result.fun}”)
3.3 方程求解
scipy.optimize.fsolve
用于求解非线性方程组。
from scipy.optimize import fsolve
# 定义方程组:f1(x,y)=x²+y²-1=0, f2(x,y)=x-y=0
def equations(vars):
x, y = vars
return [x**2 + y**2 – 1, x – y]
# 初始猜测
initial_guess = [0.5, 0.5]
# 求解
solution = fsolve(equations, initial_guess)
print(f”方程组解: x={solution[0]:.6f}, y={solution[1]:.6f}”)
print(f”验证: x²+y²={solution[0]**2 + solution[1]**2:.6f}”)
3.4 曲线拟合
scipy.optimize.curve_fit
用于非线性最小二乘拟合。
from scipy.optimize import curve_fit
# 定义拟合函数:指数衰减
def exp_decay(t, A, tau):
return A * np.exp(-t / tau)
# 生成带噪声的数据
t_data = np.linspace(0, 10, 50)
y_data = exp_decay(t_data, 2.5, 3.0) + 0.1 * np.random.randn(50)
# 拟合
popt, pcov = curve_fit(exp_decay, t_data, y_data, p0=[1, 1]) # p0为初始猜测
# 输出结果
print(f”拟合参数: A={popt[0]:.3f}, tau={popt[1]:.3f}”)
print(f”参数标准差: {np.sqrt(np.diag(pcov))}”)
# 绘制拟合结果
plt.figure(figsize=(8, 5))
plt.scatter(t_data, y_data, alpha=0.6, label=’数据’)
plt.plot(t_data, exp_decay(t_data, *popt), ‘r-‘, linewidth=2, label=’拟合曲线’)
plt.xlabel(‘时间 t’)
plt.ylabel(‘y’)
plt.title(‘指数衰减曲线拟合’)
plt.legend()
plt.grid(True)
plt.show()
4. 插值与样条函数(scipy.interpolate)
4.1 一维插值
from scipy.interpolate import interp1d, CubicSpline
# 生成数据点
x = np.linspace(0, 10, 11)
y = np.sin(x)
# 线性插值
f_linear = interp1d(x, y, kind=’linear’)
x_new = np.linspace(0, 10, 100)
y_linear = f_linear(x_new)
# 三次样条插值
f_cubic = CubicSpline(x, y)
y_cubic = f_cubic(x_new)
# 绘制结果
plt.figure(figsize=(10, 6))
plt.plot(x, y, ‘o’, markersize=8, label=’原始数据点’)
plt.plot(x_new, y_linear, ‘–‘, linewidth=2, label=’线性插值’)
plt.plot(x_new, y_cubic, ‘-‘, linewidth=2, label=’三次样条插值’)
plt.xlabel(‘x’)
plt.ylabel(‘y’)
plt.title(‘一维插值比较’)
plt.legend()
plt.grid(True)
plt.show()
4.2 二维插值
from scipy.interpolate import griddata
# 生成随机数据点
np.random.seed(42)
x = np.random.rand(100) * 10
y = np.random.rand(100) * 10
z = np.sin(x) * np.cos(y)
# 创建网格
xi = np.linspace(0, 10, 50)
yi = np.linspace(0, 10, 50)
xi, yi = np.meshgrid(xi, yi)
# 三种插值方法
zi_linear = griddata((x, y), z, (xi, yi), method=’linear’)
zi_nearest = griddata((x, y), z, (xi, yi), method=’nearest’)
zi_cubic = griddata((x, y), z, (xi, yi), method=’cubic’)
# 绘制结果
fig, axes = plt.subplots(1, 3, figsize=(15, 4))
axes[0].contourf(xi, yi, zi_linear, levels=20)
axes[0].set_title(‘线性插值’)
axes[1].contourf(xi, yi, zi_nearest, levels=20)
axes[1].set_title(‘最近邻插值’)
axes[2].contourf(xi, yi, zi_cubic, levels=20)
axes[2].set_title(‘三次样条插值’)
plt.tight_layout()
plt.show()
5. 线性代数运算(scipy.linalg)
5.1 矩阵分解
from scipy.linalg import lu, qr, svd, cholesky
# 创建矩阵
A = np.array([[4, 3, 2], [3, 5, 1], [2, 1, 6]])
# LU分解
P, L, U = lu(A)
print(“LU分解:”)
print(f”P矩阵:\n{P}”)
print(f”L矩阵:\n{L}”)
print(f”U矩阵:\n{U}”)
print(f”验证: P @ L @ U ≈ A? {np.allclose(P @ L @ U, A)}”)
# QR分解
Q, R = qr(A)
print(“\nQR分解:”)
print(f”Q矩阵:\n{Q}”)
print(f”R矩阵:\n{R}”)
print(f”验证: Q @ R ≈ A? {np.allclose(Q @ R, A)}”)
# 奇异值分解
U_svd, S, Vh = svd(A)
print(“\n奇异值分解:”)
print(f”奇异值: {S}”)
print(f”验证: U_svd @ np.diag(S) @ Vh ≈ A? {np.allclose(U_svd @ np.diag(S) @ Vh, A)}”)
# Cholesky分解(要求矩阵正定)
B = np.array([[4, 2, 1], [2, 5, 3], [1, 3, 6]])
L_chol = cholesky(B, lower=True)
print(“\nCholesky分解:”)
print(f”L矩阵:\n{L_chol}”)
print(f”验证: L_chol @ L_chol.T ≈ B? {np.allclose(L_chol @ L_chol.T, B)}”)
5.2 解线性方程组
from scipy.linalg import solve, solve_banded
# 普通线性方程组:Ax = b
A = np.array([[3, 2, 1], [2, 5, 3], [1, 3, 6]])
b = np.array([14, 23, 20])
x = solve(A, b)
print(f”解: {x}”)
print(f”验证: A @ x ≈ b? {np.allclose(A @ x, b)}”)
# 带状矩阵方程组
# 创建三对角矩阵(带宽为1)
n = 5
ab = np.zeros((3, n))
ab[0, 1:] = -1 # 上对角线
ab[1, :] = 2 # 主对角线
ab[2, :-1] = -1 # 下对角线
b_band = np.array([1, 2, 3, 4, 5])
x_band = solve_banded((1, 1), ab, b_band)
print(f”带状矩阵解: {x_band}”)
6. 统计分析(scipy.stats)
6.1 概率分布
from scipy.stats import norm, t, chi2, poisson
# 正态分布
x = np.linspace(-4, 4, 100)
pdf_norm = norm.pdf(x, loc=0, scale=1) # 标准正态分布
cdf_norm = norm.cdf(x, loc=0, scale=1)
# t分布
pdf_t = t.pdf(x, df=5, loc=0, scale=1) # 自由度为5的t分布
# 卡方分布
x_chi2 = np.linspace(0, 10, 100)
pdf_chi2 = chi2.pdf(x_chi2, df=3) # 自由度为3的卡方分布
# 泊松分布
x_poisson = np.arange(0, 10)
pmf_poisson = poisson.pmf(x_poisson, mu=3) # λ=3的泊松分布
# 绘制分布
fig, axes = plt.subplots(2, 2, figsize=(12, 8))
axes[0, 0].plot(x, pdf_norm, ‘b-‘, linewidth=2)
axes[0, 0].set_title(‘标准正态分布PDF’)
axes[0, 1].plot(x, pdf_t, ‘r-‘, linewidth=2)
axes[0, 1].set_title(‘t分布PDF (df=5)’)
axes[1, 0].plot(x_chi2, pdf_chi2, ‘g-‘, linewidth=2)
axes[1, 0].set_title(‘卡方分布PDF (df=3)’)
axes[1, 1].bar(x_poisson, pmf_poisson, color=’orange’)
axes[1, 1].set_title(‘泊松分布PMF (λ=3)’)
plt.tight_layout()
plt.show()
6.2 假设检验
from scipy.stats import ttest_ind, chi2_contingency, f_oneway
# t检验(两独立样本)
group1 = np.random.normal(5, 1, 30)
group2 = np.random.normal(5.5, 1, 30)
t_stat, p_value = ttest_ind(group1, group2)
print(f”t检验: t统计量={t_stat:.3f}, p值={p_value:.3f}”)
# 卡方检验(列联表)
observed = np.array([[10, 20, 30], [20, 30, 20]])
chi2_stat, p_val, dof, expected = chi2_contingency(observed)
print(f”卡方检验: χ²={chi2_stat:.3f}, p值={p_val:.3f}, 自由度={dof}”)
# 方差分析(ANOVA)
group_a = np.random.normal(10, 2, 20)
group_b = np.random.normal(12, 2, 20)
group_c = np.random.normal(14, 2, 20)
f_stat, p_val = f_oneway(group_a, group_b, group_c)
print(f”ANOVA: F统计量={f_stat:.3f}, p值={p_val:.3f}”)
6.3 描述性统计
from scipy.stats import describe
# 生成数据
data = np.random.randn(1000)
# 描述性统计
stats = describe(data)
print(f”样本数: {stats.nobs}”)
print(f”最小值: {stats.minmax[0]:.3f}”)
print(f”最大值: {stats.minmax[1]:.3f}”)
print(f”均值: {stats.mean:.3f}”)
print(f”方差: {stats.variance:.3f}”)
print(f”偏度: {stats.skewness:.3f}”)
print(f”峰度: {stats.kurtosis:.3f}”)
7. 信号处理(scipy.signal)
7.1 滤波器设计
from scipy.signal import butter, filtfilt, lfilter, freqz
# 设计低通巴特沃斯滤波器
def design_lowpass_filter(cutoff, fs, order=5):
nyquist = 0.5 * fs
normal_cutoff = cutoff / nyquist
b, a = butter(order, normal_cutoff, btype=’low’)
return b, a
# 参数
fs = 1000 # 采样频率
cutoff = 100 # 截止频率
order = 5
# 设计滤波器
b, a = design_lowpass_filter(cutoff, fs, order)
# 生成信号
t = np.linspace(0, 1, fs, endpoint=False)
signal = np.sin(2*np.pi*50*t) + 0.5*np.sin(2*np.pi*200*t) + 0.3*np.random.randn(len(t))
# 应用滤波器
filtered = filtfilt(b, a, signal) # 零相位滤波
# 绘制结果
plt.figure(figsize=(12, 6))
plt.subplot(2, 1, 1)
plt.plot(t, signal, ‘b-‘, alpha=0.7, label=’原始信号’)
plt.plot(t, filtered, ‘r-‘, linewidth=2, label=’滤波后信号’)
plt.xlabel(‘时间 (s)’)
plt.ylabel(‘幅度’)
plt.title(‘低通滤波器应用’)
plt.legend()
plt.grid(True)
# 频率响应
w, h = freqz(b, a, worN=512, fs=fs)
plt.subplot(2, 1, 2)
plt.plot(w, 20*np.log10(abs(h)), ‘b-‘, linewidth=2)
plt.axvline(cutoff, color=’r’, linestyle=’–‘, label=f’截止频率 {cutoff} Hz’)
plt.xlabel(‘频率 (Hz)’)
plt.ylabel(‘幅度 (dB)’)
plt.title(‘滤波器频率响应’)
plt.legend()
plt.grid(True)
plt.tight_layout()
plt.show()
7.2 频谱分析
from scipy.signal import welch, spectrogram
# 生成多频率信号
fs = 1000
t = np.linspace(0, 10, fs*10)
signal = (np.sin(2*np.pi*10*t) + 0.5*np.sin(2*np.pi*20*t) +
0.3*np.sin(2*np.pi*30*t) + 0.2*np.random.randn(len(t)))
# Welch方法功率谱密度
f_psd, Pxx = welch(signal, fs, nperseg=256)
# 短时傅里叶变换(STFT)
f_stft, t_stft, Sxx = spectrogram(signal, fs, nperseg=256, noverlap=128)
# 绘制结果
fig, axes = plt.subplots(1, 2, figsize=(12, 5))
# 功率谱密度
axes[0].semilogy(f_psd, Pxx, ‘b-‘, linewidth=2)
axes[0].set_xlabel(‘频率 (Hz)’)
axes[0].set_ylabel(‘功率谱密度’)
axes[0].set_title(‘Welch功率谱密度’)
axes[0].grid(True)
# 频谱图
im = axes[1].imshow(10*np.log10(Sxx), aspect=’auto’, origin=’lower’,
extent=[t_stft[0], t_stft[-1], f_stft[0], f_stft[-1]])
axes[1].set_xlabel(‘时间 (s)’)
axes[1].set_ylabel(‘频率 (Hz)’)
axes[1].set_title(‘短时傅里叶变换频谱图’)
plt.colorbar(im, ax=axes[1], label=’幅度 (dB)’)
plt.tight_layout()
plt.show()
8. 稀疏矩阵运算(scipy.sparse)
8.1 创建和操作稀疏矩阵
from scipy.sparse import csr_matrix, csc_matrix, lil_matrix
from scipy.sparse.linalg import spsolve
# 创建稀疏矩阵(大部分元素为零)
data = [1, 2, 3, 4, 5]
row = [0, 1, 2, 3, 4]
col = [0, 2, 4, 1, 3]
sparse_mat = csr_matrix((data, (row, col)), shape=(5, 5))
print(“稀疏矩阵:”)
print(sparse_mat.toarray()) # 转换为稠密矩阵显示
# 稀疏矩阵运算
print(f”稀疏矩阵形状: {sparse_mat.shape}”)
print(f”非零元素个数: {sparse_mat.nnz}”)
print(f”稀疏矩阵密度: {sparse_mat.nnz / (sparse_mat.shape[0] * sparse_mat.shape[1]):.3f}”)
# 稀疏矩阵乘法
vector = np.array([1, 2, 3, 4, 5])
result = sparse_mat @ vector
print(f”稀疏矩阵乘向量: {result}”)
8.2 稀疏线性方程组求解
from scipy.sparse import diags
from scipy.sparse.linalg import spsolve
# 创建三对角稀疏矩阵(大型方程组)
n = 1000
diagonals = [np.ones(n-1), -2*np.ones(n), np.ones(n-1)]
offsets = [-1, 0, 1]
A_sparse = diags(diagonals, offsets, shape=(n, n), format=’csr’)
# 右侧向量
b = np.ones(n)
b[0] = 0
b[-1] = 0
# 求解稀疏线性方程组
x_sparse = spsolve(A_sparse, b)
# 验证解
residual = np.linalg.norm(A_sparse @ x_sparse – b)
print(f”稀疏方程组求解完成,残差: {residual:.2e}”)
# 比较内存使用(可选)
import sys
print(f”稠密矩阵内存: {sys.getsizeof(np.array(A_sparse.todense())) / 1024 / 1024:.2f} MB”)
print(f”稀疏矩阵内存: {sys.getsizeof(A_sparse) / 1024:.2f} KB”)
9. 多维图像处理(scipy.ndimage)
9.1 图像滤波
from scipy.ndimage import gaussian_filter, median_filter, uniform_filter
import cv2 # 用于读取图像(可选,也可用matplotlib)
# 生成模拟图像(如果无法读取真实图像)
def generate_test_image(size=256):
x, y = np.meshgrid(np.linspace(-1, 1, size), np.linspace(-1, 1, size))
image = np.sin(10*x) * np.cos(10*y) + 0.3 * np.random.randn(size, size)
return image
# 生成测试图像
image = generate_test_image(256)
# 应用不同滤波器
gaussian_filtered = gaussian_filter(image, sigma=2)
median_filtered = median_filter(image, size=3)
uniform_filtered = uniform_filter(image, size=5)
# 绘制结果
fig, axes = plt.subplots(2, 2, figsize=(10, 10))
axes[0, 0].imshow(image, cmap=’gray’)
axes[0, 0].set_title(‘原始图像’)
axes[0, 1].imshow(gaussian_filtered, cmap=’gray’)
axes[0, 1].set_title(‘高斯滤波 (σ=2)’)
axes[1, 0].imshow(median_filtered, cmap=’gray’)
axes[1, 0].set_title(‘中值滤波 (size=3)’)
axes[1, 1].imshow(uniform_filtered, cmap=’gray’)
axes[1, 1].set_title(‘均值滤波 (size=5)’)
plt.tight_layout()
plt.show()
9.2 图像分割与特征提取
from scipy.ndimage import label, find_objects, center_of_mass, binary_dilation
# 生成二值图像(模拟分割结果)
binary_image = np.zeros((100, 100))
binary_image[20:30, 20:30] = 1
binary_image[60:70, 60:70] = 1
binary_image[40:50, 40:50] = 1
# 形态学操作:膨胀
dilated = binary_dilation(binary_image, iterations=2)
# 标记连通区域
labeled, num_features = label(binary_image)
print(f”检测到的连通区域数量: {num_features}”)
# 查找每个区域的边界框
objects = find_objects(labeled)
for i, obj in enumerate(objects):
if obj is not None:
print(f”区域 {i+1} 的边界框: {obj}”)
# 计算质心
center = center_of_mass(binary_image, labeled, i+1)
print(f”区域 {i+1} 的质心: ({center[0]:.1f}, {center[1]:.1f})”)
# 可视化
fig, axes = plt.subplots(1, 3, figsize=(12, 4))
axes[0].imshow(binary_image, cmap=’gray’)
axes[0].set_title(‘原始二值图像’)
axes[1].imshow(labeled, cmap=’nipy_spectral’)
axes[1].set_title(f’标记图像 ({num_features}个区域)’)
axes[2].imshow(dilated, cmap=’gray’)
axes[2].set_title(‘膨胀后的图像’)
plt.tight_layout()
plt.show()
10. 实际应用案例:综合使用SciPy进行数据分析
10.1 案例:信号去噪与特征提取
import numpy as np
import matplotlib.pyplot as plt
from scipy import signal, optimize, stats
# 生成模拟信号(包含趋势、周期性和噪声)
np.random.seed(42)
t = np.linspace(0, 10, 1000)
trend = 0.1 * t # 线性趋势
periodic = 2 * np.sin(2*np.pi*0.5*t) + 1.5 * np.sin(2*np.pi*2*t) # 周期性
noise = 0.5 * np.random.randn(len(t)) # 高斯噪声
signal_raw = trend + periodic + noise
# 步骤1:去除趋势(使用多项式拟合)
def remove_trend(data, degree=1):
t_norm = np.linspace(0, 1, len(data))
coeffs = np.polyfit(t_norm, data, degree)
trend_fit = np.polyval(coeffs, t_norm)
return data – trend_fit, trend_fit
signal_detrended, trend_fit = remove_trend(signal_raw, degree=1)
# 步骤2:滤波去噪(低通滤波)
b, a = signal.butter(4, 0.1, ‘low’)
signal_filtered = signal.filtfilt(b, a, signal_detrended)
# 步骤3:频谱分析
f, Pxx = signal.welch(signal_filtered, 100, nperseg=256)
# 步骤4:峰值检测
peaks, properties = signal.find_peaks(signal_filtered, height=0.5, distance=50)
print(f”检测到的峰值数量: {len(peaks)}”)
print(f”峰值位置: {t[peaks]}”)
# 步骤5:拟合周期性成分(使用curve_fit)
def multi_sine(t, A1, f1, phi1, A2, f2, phi2):
return A1*np.sin(2*np.pi*f1*t + phi1) + A2*np.sin(2*np.pi*f2*t + phi2)
# 初始猜测(基于频谱分析)
p0 = [2, 0.5, 0, 1.5, 2, 0]
popt, pcov = optimize.curve_fit(multi_sine, t, signal_filtered, p0=p0)
# 步骤6:统计检验(验证拟合效果)
residuals = signal_filtered – multi_sine(t, *popt)
stat, p_value = stats.normaltest(residuals)
print(f”残差正态性检验: p值={p_value:.4f}”)
# 综合可视化
fig, axes = plt.subplots(3, 2, figsize=(14, 10))
# 原始信号
axes[0, 0].plot(t, signal_raw, ‘b-‘, alpha=0.7, label=’原始信号’)
axes[0, 0].plot(t, trend_fit, ‘r–‘, linewidth=2, label=’拟合趋势’)
axes[0, 0].set_title(‘原始信号与趋势’)
axes[0, 0].legend()
axes[0, 0].grid(True)
# 去趋势后信号
axes[0, 1].plot(t, signal_detrended, ‘g-‘, alpha=0.7, label=’去趋势信号’)
axes[0, 1].plot(t, signal_filtered, ‘r-‘, linewidth=1.5, label=’滤波后信号’)
axes[0, 1].plot(t[peaks], signal_filtered[peaks], ‘ro’, markersize=8, label=’检测峰值’)
axes[0, 1].set_title(‘去趋势与滤波’)
axes[0, 1].legend()
axes[0, 1].grid(True)
# 频谱
axes[1, 0].semilogy(f, Pxx, ‘b-‘, linewidth=2)
axes[1, 0].set_xlabel(‘频率 (Hz)’)
axes[1, 0].set_ylabel(‘功率谱密度’)
axes[1, 0].set_title(‘功率谱密度’)
axes[1, 0].grid(True)
# 拟合结果
axes[1, 1].plot(t, signal_filtered, ‘b-‘, alpha=0.5, label=’滤波后信号’)
axes[1, 1].plot(t, multi_sine(t, *popt), ‘r-‘, linewidth=2, label=’拟合曲线’)
axes[1, 1].set_title(‘周期性成分拟合’)
axes[1, 1].legend()
axes[1, 1].grid(True)
# 残差分析
axes[2, 0].plot(t, residuals, ‘k-‘, alpha=0.7)
axes[2, 0].axhline(0, color=’r’, linestyle=’–‘)
axes[2, 0].set_title(‘拟合残差’)
axes[2, 0].grid(True)
# 残差直方图
axes[2, 1].hist(residuals, bins=30, density=True, alpha=0.7, color=’gray’)
x_norm = np.linspace(residuals.min(), residuals.max(), 100)
pdf = stats.norm.pdf(x_norm, loc=0, scale=np.std(residuals))
axes[2, 1].plot(x_norm, pdf, ‘r-‘, linewidth=2, label=’正态分布拟合’)
axes[2, 1].set_title(‘残差分布’)
axes[2, 1].legend()
axes[2, 1].grid(True)
plt.tight_layout()
plt.show()
11. 性能优化与最佳实践
11.1 向量化操作
# 避免使用循环,使用NumPy/SciPy的向量化函数
import time
# 低效的循环方式
def slow_function(x):
result = np.zeros_like(x)
for i in range(len(x)):
result[i] = np.sin(x[i]) * np.exp(-x[i]**2)
return result
# 向量化方式
def fast_function(x):
return np.sin(x) * np.exp(-x**2)
# 性能比较
x = np.random.rand(1000000)
start = time.time()
result_slow = slow_function(x)
time_slow = time.time() – start
start = time.time()
result_fast = fast_function(x)
time_fast = time.time() – start
print(f”循环方式耗时: {time_slow:.4f}秒”)
print(f”向量化方式耗时: {time_fast:.4f}秒”)
print(f”加速比: {time_slow/time_fast:.1f}倍”)
print(f”结果一致性: {np.allclose(result_slow, result_fast)}”)
11.2 使用稀疏矩阵处理大型数据
from scipy.sparse import random as sparse_random
# 创建大型稀疏矩阵(10000×10000,密度0.001)
n = 10000
density = 0.001
A_large = sparse_random(n, n, density=density, format=’csr’)
# 稀疏矩阵运算
vector = np.random.rand(n)
start = time.time()
result = A_large @ vector
time_sparse = time.time() – start
# 稠密矩阵运算(对比)
A_dense = A_large.toarray()
start = time.time()
result_dense = A_dense @ vector
time_dense = time.time() – start
print(f”稀疏矩阵运算时间: {time_sparse:.4f}秒”)
print(f”稠密矩阵运算时间: {time_dense:.4f}秒”)
print(f”加速比: {time_dense/time_sparse:.1f}倍”)
11.3 并行计算(使用joblib)
from joblib import Parallel, delayed
import multiprocessing
# 并行计算函数
def compute_parallel(x):
return np.sin(x) * np.exp(-x**2)
# 数据分块
def parallel_computation(data, n_jobs=-1):
# n_jobs=-1表示使用所有可用CPU核心
results = Parallel(n_jobs=n_jobs)(delayed(compute_parallel)(chunk)
for chunk in np.array_split(data, multiprocessing.cpu_count()))
return np.concatenate(results)
# 测试
data = np.random.rand(1000000)
start = time.time()
result_parallel = parallel_computation(data)
time_parallel = time.time() – start
# 串行计算对比
start = time.time()
result_serial = compute_parallel(data)
time_serial = time.time() – start
print(f”并行计算时间: {time_parallel:.4f}秒”)
print(f”串行计算时间: {time_serial:.4f}秒”)
print(f”加速比: {time_serial/time_parallel:.1f}倍”)
12. 常见问题与解决方案
12.1 数值稳定性问题
# 示例:避免数值下溢/上溢
from scipy.special import logsumexp
# 不稳定计算:exp(1000)会溢出
# x = np.array([1000, 1001, 1002])
# result = np.exp(x) / np.sum(np.exp(x)) # 会得到NaN
# 稳定计算:使用logsumexp
x = np.array([1000, 1001, 1002])
log_result = logsumexp(x) # 计算log(sum(exp(x)))
result_stable = np.exp(x – log_result) # 稳定计算softmax
print(f”稳定计算结果: {result_stable}”)
print(f”结果和: {np.sum(result_stable):.6f}”)
12.2 收敛性问题
from scipy.optimize import minimize
# 定义一个难以收敛的函数
def difficult_function(x):
return (x[0]**2 + 100*x[1]**2) * np.sin(10*x[0]) * np.cos(10*x[1])
# 使用不同的优化方法
methods = [‘BFGS’, ‘Nelder-Mead’, ‘Powell’, ‘CG’]
results = {}
for method in methods:
try:
result = minimize(difficult_function, [1, 1], method=method)
results[method] = result
print(f”{method}: 成功={result.success}, 函数值={result.fun:.6f}”)
except Exception as e:
print(f”{method}: 错误 – {e}”)
13. 总结
SciPy库为科学计算和数据处理提供了全面的工具集。通过本指南的详细解析和代码示例,您应该能够:
掌握核心模块
:理解每个模块的主要功能和适用场景
应用实际案例
:通过完整的代码示例学习如何解决实际问题
优化性能
:了解向量化、稀疏矩阵和并行计算等优化技巧
避免常见陷阱
:识别并解决数值稳定性和收敛性问题
关键要点:
数值积分
:使用
quad
和
dblquad
进行精确积分
优化问题
:
minimize
和
curve_fit
是解决优化和拟合问题的强大工具
插值
:
interp1d
和
CubicSpline
提供灵活的插值方法
统计分析
:
scipy.stats
包含丰富的分布和检验方法
信号处理
:滤波器设计和频谱分析是处理时间序列数据的关键
稀疏矩阵
:处理大规模数据时,稀疏矩阵能显著节省内存和计算时间
进一步学习建议:
阅读SciPy官方文档:
https://docs.scipy.org/doc/scipy/
探索SciPy的高级模块:
scipy.special
(特殊函数)、
scipy.fft
(快速傅里叶变换)
结合其他库使用:如
pandas
(数据处理)、
matplotlib
(可视化)、
scikit-learn
(机器学习)
参与SciPy社区:GitHub、Stack Overflow、SciPy会议
通过持续实践和探索,您将能够充分利用SciPy的强大功能,解决复杂的科学计算和数据处理问题。