scipy包含致力于科学计算中常见问题的各个工具箱。它的不同子模块相应于不同的应用。像插值,积分,优化,图像处理,统计,特殊函数等等。
scipy可以与其它标准科学计算程序库进行比较,比如GSL(GNU C或C++科学计算库),或者Matlab工具箱。scipy是Python中科学计算程序的核心包; 它用于有效地计算numpy矩阵,来让numpy和scipy协同工作。
在实现一个程序之前,值得检查下所需的数据处理方式是否已经在scipy中存在了。作为非专业程序员,科学家总是喜欢重新发明造轮子,导致了充满漏洞的,未经优化的,很难分享和维护的代码。相反,Scipy程序经过优化和测试,因此应该尽可能使用。
作者:Aieru
链接:https://www.jianshu.com/p/1a3db06e786d
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
# 10.1 Least squares from scipy.optimize import least_squares import numpy as np n = 5 m = 8 A = [] for i in range(n): temp = [] for j in range(m): temp += [np.random.randint(1, 100)] A += [temp] print("A:") for i in A: print(i) b = [] for j in range(n): b += [np.random.randint(1, 100)] print("b:") print(b) x = [0, 0, 0, 0, 0, 0, 0, 0] def func(x): return np.linalg.norm(np.matmul(A, x)-np.array(b)) solutions = least_squares(func, x) print("solution:") print(solutions.x) print("residual:") print(func(solutions.x))
输出:
A: [3, 78, 35, 57, 43, 48, 97, 66] [14, 54, 3, 67, 22, 73, 20, 10] [45, 95, 68, 46, 38, 79, 28, 12] [17, 17, 75, 78, 60, 76, 15, 62] [10, 60, 42, 36, 87, 78, 17, 64] b: [1, 28, 40, 54, 97] solution: [-0.04053965 0.14680695 -0.13608394 -0.27262632 0.75309927 0.44620533 -0.60086573 0.21903286] residual: 1.9376753415496063e-05
import math from scipy.optimize import fmin def func(x): return 1/((math.sin(x-2))**2*math.e**(-x**2)) fmin(func, 0)
输出:
Optimization terminated successfully. Current function value: 1.096870 Iterations: 20 Function evaluations: 40
import numpy as np from scipy.linalg import norm n = 5 m = 8 A = [] for i in range(n): temp = [] for j in range(m): temp += [np.random.randint(1, 100)] A += [temp] print("A:") for i in A: print(i) distances = [] for i in range(n): temp = [] for j in range(n): temp += [norm(np.subtract(A[i], A[j]))] distances += [temp] print("distances:") for i in distances: print(i)
输出:
A: [57, 44, 32, 40, 50, 69, 58, 77] [61, 78, 3, 32, 84, 66, 75, 76] [4, 91, 41, 74, 17, 52, 7, 7] [91, 4, 28, 49, 59, 14, 9, 41] [1, 57, 5, 97, 99, 95, 57, 27] distances: [0.0, 59.430631832414505, 123.02032352420473, 98.26494797230598, 113.4063490286148] [59.430631832414505, 0.0, 143.86104406683555, 127.27922061357856, 109.82258419833327] [123.02032352420473, 143.86104406683555, 0.0, 142.47806848775008, 120.26221351696466] [98.26494797230598, 127.27922061357856, 142.47806848775008, 0.0, 156.2145959889792] [113.4063490286148, 109.82258419833327, 120.26221351696466, 156.2145959889792, 0.0]