简体中文 繁體中文 English 日本語 Deutsch 한국 사람 بالعربية TÜRKÇE português คนไทย Français

站内搜索

搜索

活动公告

11-02 12:46
10-23 09:32
通知:本站资源由网友上传分享,如有违规等问题请到版务模块进行投诉,将及时处理!
10-23 09:31
10-23 09:28
通知:签到时间调整为每日4:00(东八区)
10-23 09:26

NumPy项目简介探索Python科学计算基础库的核心功能与应用场景深入了解数据科学背后的强大工具

3万

主题

423

科技点

3万

积分

大区版主

木柜子打湿

积分
31916

三倍冰淇淋无人之境【一阶】财Doro小樱(小丑装)立华奏以外的星空【二阶】⑨的冰沙

发表于 2025-9-20 01:10:02 | 显示全部楼层 |阅读模式 [标记阅至此楼]

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
NumPy项目简介探索Python科学计算基础库的核心功能与应用场景深入了解数据科学背后的强大工具

NumPy(Numerical Python)是Python语言的一个扩展程序库,支持大量的维度数组与矩阵运算,此外也针对数组运算提供大量的数学函数库。NumPy是Python科学计算的基础库,许多其他科学计算库如Pandas、SciPy、Matplotlib等都建立在NumPy之上。NumPy的出现使得Python能够像MATLAB、R语言等一样进行高效的数值计算,极大地推动了Python在科学计算和数据分析领域的发展。

NumPy的历史与发展

NumPy的前身是1995年开发的Numeric,随后在2001年出现了Numarray库。2005年,Travis Oliphant将Numeric和Numarray的特性结合,创建了NumPy库。NumPy 1.0版本于2006年发布,此后不断发展,目前最新的稳定版本是NumPy 1.2x系列。

NumPy的发展得到了广泛关注和支持,现在已经成为Python科学计算生态系统的核心组件。它的开发由一个活跃的社区维护,包括许多来自学术界和工业界的贡献者。

NumPy的核心功能

NumPy的核心是ndarray(N-dimensional array)对象,它是一个快速而灵活的大数据集容器。ndarray是一个通用的同构数据多维容器,也就是说,它包含的所有元素必须是相同类型的。
  1. import numpy as np
  2. # 创建一维数组
  3. arr1 = np.array([1, 2, 3, 4, 5])
  4. print("一维数组:")
  5. print(arr1)
  6. # 创建二维数组
  7. arr2 = np.array([[1, 2, 3], [4, 5, 6]])
  8. print("\n二维数组:")
  9. print(arr2)
  10. # 创建三维数组
  11. arr3 = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
  12. print("\n三维数组:")
  13. print(arr3)
  14. # 查看数组属性
  15. print("\n数组维度:", arr2.ndim)
  16. print("数组形状:", arr2.shape)
  17. print("数组大小:", arr2.size)
  18. print("数组类型:", arr2.dtype)
复制代码

NumPy提供了大量的通用函数(ufunc),这些函数可以对数组中的每个元素进行操作,而无需使用循环。这些函数被称为”向量化”操作,因为它们将操作应用于数组中的每个元素,而不是整个数组。
  1. import numpy as np
  2. # 创建数组
  3. arr = np.array([1, 2, 3, 4, 5])
  4. # 数学运算
  5. print("原始数组:", arr)
  6. print("数组平方:", np.square(arr))
  7. print("数组平方根:", np.sqrt(arr))
  8. print("数组指数:", np.exp(arr))
  9. print("数组对数:", np.log(arr))
  10. # 三角函数
  11. angles = np.array([0, np.pi/2, np.pi])
  12. print("\n角度:", angles)
  13. print("正弦值:", np.sin(angles))
  14. print("余弦值:", np.cos(angles))
复制代码

广播是NumPy中强大的机制,它允许不同形状的数组进行算术运算。广播的规则是:如果两个数组的维度数不同,则小维度数组的形状会在其前面补1;然后,对于每个维度,如果两个数组的大小相同,或者其中一个数组的大小为1,则认为它们是兼容的;如果两个数组在所有维度上都兼容,则可以广播。
  1. import numpy as np
  2. # 标量与数组
  3. arr = np.array([1, 2, 3, 4, 5])
  4. result = arr * 2
  5. print("标量与数组相乘:")
  6. print("原始数组:", arr)
  7. print("结果:", result)
  8. # 不同形状的数组
  9. arr1 = np.array([[1, 2, 3], [4, 5, 6]])  # 形状 (2, 3)
  10. arr2 = np.array([10, 20, 30])            # 形状 (3,)
  11. result = arr1 + arr2
  12. print("\n不同形状的数组相加:")
  13. print("数组1:")
  14. print(arr1)
  15. print("数组2:")
  16. print(arr2)
  17. print("结果:")
  18. print(result)
复制代码

NumPy数组支持类似Python列表的索引和切片操作,但提供了更多的功能和灵活性。
  1. import numpy as np
  2. # 创建一维数组
  3. arr1 = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
  4. print("原始一维数组:", arr1)
  5. # 基本索引
  6. print("索引3的元素:", arr1[3])
  7. # 切片
  8. print("切片[2:6]:", arr1[2:6])
  9. print("切片[::2]:", arr1[::2])  # 步长为2
  10. # 创建二维数组
  11. arr2 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
  12. print("\n原始二维数组:")
  13. print(arr2)
  14. # 二维数组索引
  15. print("元素[1, 2]:", arr2[1, 2])  # 第2行第3列
  16. # 二维数组切片
  17. print("第1行:", arr2[0, :])
  18. print("第2列:", arr2[:, 1])
  19. print("子数组:")
  20. print(arr2[:2, 1:])  # 前两行,从第2列开始
  21. # 布尔索引
  22. bool_idx = arr2 > 5
  23. print("\n布尔索引条件:")
  24. print(bool_idx)
  25. print("满足条件的元素:", arr2[bool_idx])
复制代码

NumPy提供了线性代数运算的功能,包括矩阵乘法、矩阵分解、特征值计算等。
  1. import numpy as np
  2. # 创建矩阵
  3. A = np.array([[1, 2], [3, 4]])
  4. B = np.array([[5, 6], [7, 8]])
  5. print("矩阵A:")
  6. print(A)
  7. print("矩阵B:")
  8. print(B)
  9. # 矩阵乘法
  10. print("\n矩阵乘法 (A @ B):")
  11. print(A @ B)
  12. print("矩阵乘法 (np.dot(A, B)):")
  13. print(np.dot(A, B))
  14. # 矩阵转置
  15. print("\n矩阵A的转置:")
  16. print(A.T)
  17. # 矩阵的逆
  18. try:
  19.     inv_A = np.linalg.inv(A)
  20.     print("\n矩阵A的逆:")
  21.     print(inv_A)
  22. except np.linalg.LinAlgError:
  23.     print("\n矩阵A不可逆")
  24. # 行列式
  25. det_A = np.linalg.det(A)
  26. print("\n矩阵A的行列式:", det_A)
  27. # 特征值和特征向量
  28. eigenvalues, eigenvectors = np.linalg.eig(A)
  29. print("\n矩阵A的特征值:")
  30. print(eigenvalues)
  31. print("矩阵A的特征向量:")
  32. print(eigenvectors)
  33. # 解线性方程组
  34. # Ax = b
  35. b = np.array([1, 2])
  36. x = np.linalg.solve(A, b)
  37. print("\n解方程组 Ax = b, 其中 b =", b)
  38. print("解 x =", x)
复制代码

NumPy的random模块提供了生成各种随机数的功能,可以用于模拟、统计抽样等应用。
  1. import numpy as np
  2. # 设置随机种子以确保结果可重现
  3. np.random.seed(42)
  4. # 生成[0, 1)之间的随机数
  5. rand_nums = np.random.rand(5)
  6. print("[0, 1)之间的随机数:")
  7. print(rand_nums)
  8. # 生成标准正态分布的随机数
  9. norm_nums = np.random.randn(5)
  10. print("\n标准正态分布的随机数:")
  11. print(norm_nums)
  12. # 生成指定范围内的随机整数
  13. int_nums = np.random.randint(0, 10, size=5)
  14. print("\n[0, 10)之间的随机整数:")
  15. print(int_nums)
  16. # 从数组中随机选择元素
  17. choices = np.random.choice(['apple', 'banana', 'cherry'], size=5)
  18. print("\n从列表中随机选择:")
  19. print(choices)
  20. # 生成随机排列
  21. perm = np.random.permutation([1, 2, 3, 4, 5])
  22. print("\n随机排列:")
  23. print(perm)
  24. # 从正态分布中抽样
  25. normal_sample = np.random.normal(loc=0, scale=1, size=1000)
  26. print("\n从正态分布N(0,1)中抽样1000个点:")
  27. print("前10个样本:", normal_sample[:10])
  28. print("样本均值:", np.mean(normal_sample))
  29. print("样本标准差:", np.std(normal_sample))
复制代码

NumPy提供了快速傅里叶变换(FFT)的功能,用于信号处理、图像处理等领域。
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. # 创建一个信号
  4. t = np.linspace(0, 1, 1000, endpoint=False)
  5. signal = np.sin(2 * np.pi * 5 * t) + 0.5 * np.sin(2 * np.pi * 12 * t)
  6. # 计算FFT
  7. fft_result = np.fft.fft(signal)
  8. frequencies = np.fft.fftfreq(len(t), t[1] - t[0])
  9. # 绘制原始信号和FFT结果
  10. plt.figure(figsize=(12, 6))
  11. plt.subplot(2, 1, 1)
  12. plt.plot(t, signal)
  13. plt.title('原始信号')
  14. plt.xlabel('时间')
  15. plt.ylabel('振幅')
  16. plt.subplot(2, 1, 2)
  17. plt.plot(frequencies[:len(frequencies)//2], np.abs(fft_result[:len(fft_result)//2]))
  18. plt.title('FFT结果')
  19. plt.xlabel('频率')
  20. plt.ylabel('振幅')
  21. plt.tight_layout()
  22. plt.show()
复制代码

NumPy的应用场景

在数据科学领域,NumPy是数据处理和分析的基础。它提供了高效的数据结构和运算功能,使得处理大规模数据集成为可能。
  1. import numpy as np
  2. # 假设我们有一个包含1000个样本的数据集,每个样本有10个特征
  3. # 生成随机数据
  4. np.random.seed(42)
  5. data = np.random.randn(1000, 10)  # 1000个样本,10个特征
  6. # 添加一个目标变量(例如,分类标签)
  7. # 假设我们有一个简单的线性关系:y = 2*x1 + 3*x2 - 1.5*x3 + 噪声
  8. noise = np.random.normal(0, 0.1, 1000)
  9. target = 2 * data[:, 0] + 3 * data[:, 1] - 1.5 * data[:, 2] + noise
  10. # 数据标准化
  11. mean = np.mean(data, axis=0)
  12. std = np.std(data, axis=0)
  13. normalized_data = (data - mean) / std
  14. # 计算特征之间的相关性矩阵
  15. correlation_matrix = np.corrcoef(data.T)
  16. print("特征相关性矩阵:")
  17. print(correlation_matrix)
  18. # 数据分割为训练集和测试集
  19. indices = np.random.permutation(len(data))
  20. train_size = int(0.8 * len(data))
  21. train_indices = indices[:train_size]
  22. test_indices = indices[train_size:]
  23. X_train, X_test = normalized_data[train_indices], normalized_data[test_indices]
  24. y_train, y_test = target[train_indices], target[test_indices]
  25. print("\n训练集大小:", X_train.shape)
  26. print("测试集大小:", X_test.shape)
复制代码

NumPy是许多机器学习算法实现的基础。下面是一个使用NumPy实现简单线性回归的例子:
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. # 生成一些示例数据
  4. np.random.seed(42)
  5. X = 2 * np.random.rand(100, 1)
  6. y = 4 + 3 * X + np.random.randn(100, 1)
  7. # 添加偏置项(x0 = 1)
  8. X_b = np.c_[np.ones((100, 1)), X]  # 添加 x0 = 1
  9. # 使用正规方程计算参数
  10. theta_best = np.linalg.inv(X_b.T.dot(X_b)).dot(X_b.T).dot(y)
  11. print("最佳参数 (theta0, theta1):", theta_best.ravel())
  12. # 使用梯度下降法计算参数
  13. learning_rate = 0.1
  14. n_iterations = 1000
  15. m = 100
  16. # 随机初始化参数
  17. theta = np.random.randn(2, 1)
  18. # 存储每次迭代的成本,以便绘制
  19. cost_history = []
  20. for iteration in range(n_iterations):
  21.     # 计算预测值
  22.     predictions = X_b.dot(theta)
  23.    
  24.     # 计算误差
  25.     error = predictions - y
  26.    
  27.     # 计算成本(均方误差)
  28.     cost = (1/(2*m)) * np.sum(error ** 2)
  29.     cost_history.append(cost)
  30.    
  31.     # 计算梯度
  32.     gradients = (1/m) * X_b.T.dot(error)
  33.    
  34.     # 更新参数
  35.     theta = theta - learning_rate * gradients
  36. print("梯度下降后的参数 (theta0, theta1):", theta.ravel())
  37. # 绘制结果
  38. plt.figure(figsize=(12, 5))
  39. plt.subplot(1, 2, 1)
  40. plt.scatter(X, y)
  41. plt.plot(X, X_b.dot(theta_best), 'r-', label='正规方程')
  42. plt.plot(X, X_b.dot(theta), 'g-', label='梯度下降')
  43. plt.xlabel('X')
  44. plt.ylabel('y')
  45. plt.title('线性回归拟合')
  46. plt.legend()
  47. plt.subplot(1, 2, 2)
  48. plt.plot(range(n_iterations), cost_history)
  49. plt.xlabel('迭代次数')
  50. plt.ylabel('成本')
  51. plt.title('梯度下降成本变化')
  52. plt.tight_layout()
  53. plt.show()
复制代码

NumPy数组可以用来表示和操作图像。下面是一个使用NumPy进行基本图像处理的例子:
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from scipy import ndimage
  4. # 创建一个简单的图像(例如,一个渐变的圆形)
  5. size = 200
  6. x = np.linspace(-1, 1, size)
  7. y = np.linspace(-1, 1, size)
  8. xx, yy = np.meshgrid(x, y)
  9. circle = xx**2 + yy**2 <= 1
  10. image = circle.astype(float)
  11. # 添加一些噪声
  12. noise = np.random.normal(0, 0.1, image.shape)
  13. noisy_image = np.clip(image + noise, 0, 1)
  14. # 应用高斯滤波
  15. smoothed_image = ndimage.gaussian_filter(noisy_image, sigma=1)
  16. # 旋转图像
  17. rotated_image = ndimage.rotate(smoothed_image, angle=45, reshape=False)
  18. # 边缘检测(使用Sobel算子)
  19. sx = ndimage.sobel(smoothed_image, axis=0, mode='constant')
  20. sy = ndimage.sobel(smoothed_image, axis=1, mode='constant')
  21. sob = np.hypot(sx, sy)
  22. # 显示结果
  23. plt.figure(figsize=(12, 8))
  24. plt.subplot(2, 3, 1)
  25. plt.imshow(image, cmap='gray')
  26. plt.title('原始图像')
  27. plt.subplot(2, 3, 2)
  28. plt.imshow(noisy_image, cmap='gray')
  29. plt.title('添加噪声后的图像')
  30. plt.subplot(2, 3, 3)
  31. plt.imshow(smoothed_image, cmap='gray')
  32. plt.title('高斯滤波后的图像')
  33. plt.subplot(2, 3, 4)
  34. plt.imshow(rotated_image, cmap='gray')
  35. plt.title('旋转后的图像')
  36. plt.subplot(2, 3, 5)
  37. plt.imshow(sob, cmap='gray')
  38. plt.title('边缘检测')
  39. plt.tight_layout()
  40. plt.show()
复制代码

NumPy在科学计算中有广泛的应用,例如物理模拟、统计分析等。下面是一个使用NumPy进行简单物理模拟的例子:
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. # 模拟抛物运动
  4. def simulate_projectile_motion(v0, angle, g=9.81, dt=0.01):
  5.     # 将角度转换为弧度
  6.     angle_rad = np.radians(angle)
  7.    
  8.     # 初始速度分量
  9.     v0x = v0 * np.cos(angle_rad)
  10.     v0y = v0 * np.sin(angle_rad)
  11.    
  12.     # 计算飞行时间
  13.     t_flight = 2 * v0y / g
  14.    
  15.     # 时间数组
  16.     t = np.arange(0, t_flight, dt)
  17.    
  18.     # 位置数组
  19.     x = v0x * t
  20.     y = v0y * t - 0.5 * g * t**2
  21.    
  22.     return x, y, t
  23. # 模拟不同角度的抛物运动
  24. v0 = 20  # 初始速度
  25. angles = [30, 45, 60]  # 不同角度
  26. plt.figure(figsize=(10, 6))
  27. for angle in angles:
  28.     x, y, t = simulate_projectile_motion(v0, angle)
  29.     plt.plot(x, y, label=f'{angle}°')
  30. plt.title('不同角度的抛物运动')
  31. plt.xlabel('水平距离 (m)')
  32. plt.ylabel('垂直距离 (m)')
  33. plt.grid(True)
  34. plt.legend()
  35. plt.show()
  36. # 计算并绘制速度随时间的变化
  37. plt.figure(figsize=(10, 6))
  38. for angle in angles:
  39.     x, y, t = simulate_projectile_motion(v0, angle)
  40.     angle_rad = np.radians(angle)
  41.     v0x = v0 * np.cos(angle_rad)
  42.     v0y = v0 * np.sin(angle_rad)
  43.     vx = np.ones_like(t) * v0x  # 水平速度保持不变
  44.     vy = v0y - 9.81 * t  # 垂直速度随时间变化
  45.     v = np.sqrt(vx**2 + vy**2)  # 总速度
  46.     plt.plot(t, v, label=f'{angle}°')
  47. plt.title('速度随时间的变化')
  48. plt.xlabel('时间 (s)')
  49. plt.ylabel('速度 (m/s)')
  50. plt.grid(True)
  51. plt.legend()
  52. plt.show()
复制代码

NumPy在金融分析中也有广泛的应用,例如计算投资组合的风险和回报、期权定价等。下面是一个使用NumPy进行简单金融分析的例子:
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. # 模拟股票价格走势(几何布朗运动)
  4. def simulate_stock_price(S0, mu, sigma, T, n_steps):
  5.     dt = T / n_steps
  6.     t = np.linspace(0, T, n_steps)
  7.    
  8.     # 生成随机数
  9.     W = np.random.standard_normal(size=n_steps)
  10.     W = np.cumsum(W) * np.sqrt(dt)  # 布朗运动
  11.    
  12.     # 计算股票价格
  13.     X = (mu - 0.5 * sigma**2) * t + sigma * W
  14.     S = S0 * np.exp(X)
  15.    
  16.     return t, S
  17. # 参数设置
  18. S0 = 100  # 初始价格
  19. mu = 0.08  # 预期收益率
  20. sigma = 0.2  # 波动率
  21. T = 1  # 时间(年)
  22. n_steps = 252  # 步数(假设一年有252个交易日)
  23. # 模拟多条路径
  24. n_paths = 10
  25. plt.figure(figsize=(10, 6))
  26. for i in range(n_paths):
  27.     t, S = simulate_stock_price(S0, mu, sigma, T, n_steps)
  28.     plt.plot(t, S)
  29. plt.title('股票价格模拟')
  30. plt.xlabel('时间(年)')
  31. plt.ylabel('价格')
  32. plt.grid(True)
  33. plt.show()
  34. # 计算投资组合的风险和回报
  35. def portfolio_performance(weights, mean_returns, cov_matrix):
  36.     returns = np.sum(mean_returns * weights) * 252
  37.     std = np.sqrt(np.dot(weights.T, np.dot(cov_matrix, weights))) * np.sqrt(252)
  38.     return returns, std
  39. # 生成随机资产
  40. n_assets = 4
  41. mean_returns = np.random.randn(n_assets) * 0.1  # 日收益率
  42. cov_matrix = np.random.randn(n_assets, n_assets)
  43. cov_matrix = cov_matrix.T.dot(cov_matrix) * 0.01  # 协方差矩阵
  44. # 生成随机投资组合
  45. n_portfolios = 5000
  46. results = np.zeros((3, n_portfolios))
  47. for i in range(n_portfolios):
  48.     weights = np.random.random(n_assets)
  49.     weights /= np.sum(weights)
  50.    
  51.     returns, std = portfolio_performance(weights, mean_returns, cov_matrix)
  52.     results[0, i] = returns
  53.     results[1, i] = std
  54.     results[2, i] = returns / std  # 夏普比率
  55. # 绘制有效前沿
  56. plt.figure(figsize=(10, 6))
  57. plt.scatter(results[1, :], results[0, :], c=results[2, :], cmap='viridis')
  58. plt.colorbar(label='夏普比率')
  59. plt.xlabel('波动率')
  60. plt.ylabel('预期收益率')
  61. plt.title('投资组合有效前沿')
  62. plt.grid(True)
  63. plt.show()
复制代码

NumPy与其他库的集成

Pandas是建立在NumPy之上的数据分析库,提供了更高级的数据结构和数据分析工具。NumPy数组与Pandas的DataFrame和Series对象可以轻松转换。
  1. import numpy as np
  2. import pandas as pd
  3. # 从NumPy数组创建DataFrame
  4. data = np.random.randn(5, 4)  # 5行4列的随机数
  5. columns = ['A', 'B', 'C', 'D']
  6. df = pd.DataFrame(data, columns=columns)
  7. print("从NumPy数组创建的DataFrame:")
  8. print(df)
  9. # DataFrame转换为NumPy数组
  10. array = df.values
  11. print("\nDataFrame转换为NumPy数组:")
  12. print(array)
  13. # 使用NumPy函数处理DataFrame
  14. print("\nDataFrame每列的平均值:")
  15. print(df.apply(np.mean))
  16. # 使用NumPy条件筛选DataFrame
  17. print("\n满足条件的行:")
  18. print(df[df['A'] > 0])
复制代码

Matplotlib是Python的绘图库,与NumPy紧密集成,可以轻松地将NumPy数组可视化。
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. # 创建数据
  4. x = np.linspace(0, 10, 100)
  5. y1 = np.sin(x)
  6. y2 = np.cos(x)
  7. # 绘制图形
  8. plt.figure(figsize=(10, 6))
  9. plt.plot(x, y1, label='sin(x)')
  10. plt.plot(x, y2, label='cos(x)')
  11. plt.title('三角函数')
  12. plt.xlabel('x')
  13. plt.ylabel('y')
  14. plt.grid(True)
  15. plt.legend()
  16. plt.show()
  17. # 创建2D数组用于热图
  18. data = np.random.randn(10, 10)
  19. plt.figure(figsize=(8, 6))
  20. plt.imshow(data, cmap='coolwarm')
  21. plt.colorbar()
  22. plt.title('热图')
  23. plt.show()
复制代码

SciPy是建立在NumPy之上的科学计算库,提供了更多的科学计算功能,如优化、信号处理、统计等。
  1. import numpy as np
  2. from scipy import optimize, integrate, stats
  3. # 使用SciPy的优化功能
  4. def f(x):
  5.     return x**2 + 10*np.sin(x)
  6. result = optimize.minimize(f, x0=0)
  7. print("函数最小值:")
  8. print("x =", result.x[0])
  9. print("f(x) =", result.fun)
  10. # 使用SciPy的积分功能
  11. def integrand(x):
  12.     return np.exp(-x**2)
  13. result, error = integrate.quad(integrand, 0, np.inf)
  14. print("\n积分结果 (exp(-x^2)从0到无穷大):")
  15. print("结果 =", result)
  16. print("误差估计 =", error)
  17. # 使用SciPy的统计功能
  18. data = np.random.normal(0, 1, 1000)
  19. mean, std = stats.norm.fit(data)
  20. print("\n数据拟合正态分布:")
  21. print("均值 =", mean)
  22. print("标准差 =", std)
复制代码

Scikit-learn是Python的机器学习库,广泛使用NumPy数组作为数据结构。
  1. import numpy as np
  2. from sklearn import datasets, linear_model, model_selection
  3. # 加载数据集
  4. diabetes = datasets.load_diabetes()
  5. X = diabetes.data
  6. y = diabetes.target
  7. # 分割数据集
  8. X_train, X_test, y_train, y_test = model_selection.train_test_split(
  9.     X, y, test_size=0.2, random_state=42)
  10. # 创建线性回归模型
  11. regr = linear_model.LinearRegression()
  12. # 训练模型
  13. regr.fit(X_train, y_train)
  14. # 预测
  15. y_pred = regr.predict(X_test)
  16. # 评估模型
  17. print("系数:", regr.coef_)
  18. print("均方误差: %.2f" % np.mean((y_pred - y_test) ** 2))
  19. print("决定系数: %.2f" % regr.score(X_test, y_test))
复制代码

NumPy的性能优势

NumPy的主要性能优势来自于其底层实现和优化的算法。下面是一个比较NumPy和纯Python列表操作性能的例子:
  1. import numpy as np
  2. import time
  3. # 创建大型数据集
  4. size = 1000000
  5. list1 = list(range(size))
  6. list2 = list(range(size))
  7. array1 = np.arange(size)
  8. array2 = np.arange(size)
  9. # 比较向量加法
  10. start = time.time()
  11. result_list = [a + b for a, b in zip(list1, list2)]
  12. list_time = time.time() - start
  13. start = time.time()
  14. result_array = array1 + array2
  15. array_time = time.time() - start
  16. print(f"向量加法 - Python列表: {list_time:.6f}秒")
  17. print(f"向量加法 - NumPy数组: {array_time:.6f}秒")
  18. print(f"NumPy比Python快 {list_time/array_time:.2f}倍")
  19. # 比较点积
  20. start = time.time()
  21. dot_list = sum(a * b for a, b in zip(list1, list2))
  22. list_time = time.time() - start
  23. start = time.time()
  24. dot_array = np.dot(array1, array2)
  25. array_time = time.time() - start
  26. print(f"\n点积 - Python列表: {list_time:.6f}秒")
  27. print(f"点积 - NumPy数组: {array_time:.6f}秒")
  28. print(f"NumPy比Python快 {list_time/array_time:.2f}倍")
  29. # 比较矩阵乘法
  30. size = 1000
  31. matrix1 = [[i+j for j in range(size)] for i in range(size)]
  32. matrix2 = [[i-j for j in range(size)] for i in range(size)]
  33. np_matrix1 = np.array(matrix1)
  34. np_matrix2 = np.array(matrix2)
  35. start = time.time()
  36. result_matrix = [[sum(a*b for a, b in zip(row, col)) for col in zip(*matrix2)] for row in matrix1]
  37. list_time = time.time() - start
  38. start = time.time()
  39. result_np_matrix = np.matmul(np_matrix1, np_matrix2)
  40. array_time = time.time() - start
  41. print(f"\n矩阵乘法 - Python列表: {list_time:.6f}秒")
  42. print(f"矩阵乘法 - NumPy数组: {array_time:.6f}秒")
  43. print(f"NumPy比Python快 {list_time/array_time:.2f}倍")
复制代码

NumPy的性能优势主要来自以下几个方面:

1. 连续内存存储:NumPy数组在内存中是连续存储的,这使得访问和操作数据更加高效。
2. 向量化操作:NumPy使用向量化操作,避免了Python循环的开销,直接在底层使用优化的C或Fortran代码执行操作。
3. 并行计算:许多NumPy操作可以利用现代CPU的SIMD(单指令多数据)指令集进行并行计算。
4. 优化的算法:NumPy使用经过高度优化的算法,例如BLAS(基本线性代数子程序)和LAPACK(线性代数包)等。
5. 类型一致性:NumPy数组中的所有元素都是相同类型的,这避免了类型检查的开销,并允许使用更紧凑的内存表示。

连续内存存储:NumPy数组在内存中是连续存储的,这使得访问和操作数据更加高效。

向量化操作:NumPy使用向量化操作,避免了Python循环的开销,直接在底层使用优化的C或Fortran代码执行操作。

并行计算:许多NumPy操作可以利用现代CPU的SIMD(单指令多数据)指令集进行并行计算。

优化的算法:NumPy使用经过高度优化的算法,例如BLAS(基本线性代数子程序)和LAPACK(线性代数包)等。

类型一致性:NumPy数组中的所有元素都是相同类型的,这避免了类型检查的开销,并允许使用更紧凑的内存表示。

实际代码示例

下面是一个更综合的例子,展示如何使用NumPy进行数据分析和可视化:
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from scipy import stats
  4. # 生成模拟数据
  5. np.random.seed(42)
  6. n_samples = 1000
  7. # 生成两组数据
  8. group1 = np.random.normal(loc=5, scale=2, size=n_samples)
  9. group2 = np.random.normal(loc=6, scale=1.5, size=n_samples)
  10. # 计算基本统计量
  11. def print_stats(data, name):
  12.     print(f"{name}的统计量:")
  13.     print(f"  均值: {np.mean(data):.2f}")
  14.     print(f"  中位数: {np.median(data):.2f}")
  15.     print(f"  标准差: {np.std(data):.2f}")
  16.     print(f"  最小值: {np.min(data):.2f}")
  17.     print(f"  最大值: {np.max(data):.2f}")
  18.     print(f"  25%分位数: {np.percentile(data, 25):.2f}")
  19.     print(f"  75%分位数: {np.percentile(data, 75):.2f}")
  20.     print()
  21. print_stats(group1, "组1")
  22. print_stats(group2, "组2")
  23. # 执行t检验
  24. t_stat, p_value = stats.ttest_ind(group1, group2)
  25. print("t检验结果:")
  26. print(f"  t统计量: {t_stat:.4f}")
  27. print(f"  p值: {p_value:.4f}")
  28. if p_value < 0.05:
  29.     print("  结论: 两组数据有显著差异")
  30. else:
  31.     print("  结论: 两组数据没有显著差异")
  32. print()
  33. # 计算相关系数
  34. x = np.linspace(0, 10, n_samples)
  35. y = 2 * x + np.random.normal(0, 1, n_samples)
  36. corr_coef = np.corrcoef(x, y)[0, 1]
  37. print(f"x和y的相关系数: {corr_coef:.4f}")
  38. # 绘制直方图
  39. plt.figure(figsize=(12, 8))
  40. plt.subplot(2, 2, 1)
  41. plt.hist(group1, bins=30, alpha=0.5, label='组1')
  42. plt.hist(group2, bins=30, alpha=0.5, label='组2')
  43. plt.title('数据分布')
  44. plt.xlabel('值')
  45. plt.ylabel('频数')
  46. plt.legend()
  47. # 绘制箱线图
  48. plt.subplot(2, 2, 2)
  49. plt.boxplot([group1, group2], labels=['组1', '组2'])
  50. plt.title('箱线图')
  51. plt.ylabel('值')
  52. # 绘制散点图
  53. plt.subplot(2, 2, 3)
  54. plt.scatter(x, y, alpha=0.5)
  55. plt.title('散点图')
  56. plt.xlabel('x')
  57. plt.ylabel('y')
  58. # 绘制Q-Q图
  59. plt.subplot(2, 2, 4)
  60. stats.probplot(group1, plot=plt)
  61. plt.title('组1的Q-Q图')
  62. plt.tight_layout()
  63. plt.show()
  64. # 聚类分析示例
  65. from sklearn.cluster import KMeans
  66. # 生成三维数据
  67. np.random.seed(42)
  68. data = np.random.randn(300, 3)
  69. data[:100] += [2, 2, 2]  # 第一簇
  70. data[100:200] += [-2, -2, -2]  # 第二簇
  71. data[200:] += [2, -2, 0]  # 第三簇
  72. # 应用K-means聚类
  73. kmeans = KMeans(n_clusters=3, random_state=42)
  74. labels = kmeans.fit_predict(data)
  75. # 绘制3D散点图
  76. from mpl_toolkits.mplot3d import Axes3D
  77. fig = plt.figure(figsize=(10, 8))
  78. ax = fig.add_subplot(111, projection='3d')
  79. colors = ['r', 'g', 'b']
  80. for i in range(3):
  81.     ax.scatter(data[labels == i, 0], data[labels == i, 1], data[labels == i, 2],
  82.                c=colors[i], label=f'簇 {i+1}')
  83. ax.set_title('K-means聚类结果')
  84. ax.set_xlabel('X')
  85. ax.set_ylabel('Y')
  86. ax.set_zlabel('Z')
  87. ax.legend()
  88. plt.show()
复制代码

总结与展望

NumPy作为Python科学计算的基础库,提供了高效的多维数组对象和丰富的数学函数,使得Python成为科学计算和数据分析的强大工具。它的核心功能包括多维数组操作、通用函数、广播机制、线性代数运算、随机数生成和傅里叶变换等,这些功能为数据科学、机器学习、图像处理、科学计算和金融分析等领域提供了坚实的基础。

NumPy的性能优势来自于其底层的优化实现,包括连续内存存储、向量化操作、并行计算和优化的算法等,使得它比纯Python代码快几个数量级。

NumPy与其他科学计算库如Pandas、Matplotlib、SciPy和Scikit-learn等紧密集成,形成了一个完整的科学计算生态系统,为Python在科学计算和数据分析领域的应用提供了强大的支持。

展望未来,NumPy仍在不断发展,以适应新的计算硬件(如GPU、TPU等)和计算需求。NumPy项目也在积极改进其API,使其更加用户友好,并保持与Python生态系统的其他部分的兼容性。

对于任何希望在Python中进行科学计算、数据分析或机器学习的开发者和研究人员来说,掌握NumPy是必不可少的技能。通过学习和使用NumPy,你可以更高效地处理数据,实现复杂的算法,并构建强大的科学计算应用。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

频道订阅

频道订阅

加入社群

加入社群

联系我们|TG频道|RSS

Powered by Pixtech

© 2025 Pixtech Team.