in[3]:np.linspace(0.,2.5,5) Out [3]:array([0.,0.625,1.25,1.875,2.5])
这在生成plots图表中非常有用。
注释:即从0开始,到2.5结束,然后分成5等份
多维数组矩阵 (Matrix by multidimensional array)
In [1] : a = np.array([[l, 2, 3] [4, 5, 6]]) ^ 第一行 (Row 1) In [2] : a Out [2] : array([[l, 2, 3] , [4, 5, 6]]) In [3] : a.shape #<- 行、列数等 (Number of rows, columns etc.) Out [3] : (2,3) In [4] : a.ndim #<- 维度数 (Number of dimensions) Out [4] : 2 In [5] : a,size #<- 元素数量 (Total number of elements) Out [5] : 6
形状变化 (Shape changing)
import numpy as np a = np .arange(0, 20, 1) #1维 b = a.reshape((4, 5)) #4行5列 c = a.reshape((20, 1)) #2维 d = a.reshape((-1, 4)) #-1:自动确定 #a.shape =(4, 5) #改变a的形状
Size(N,),(N,1)和(1,N)是不同的!!!
Size(N, )表示数组是一维的。
Size(N,1)表示数组是维数为2, N列和1行。
Size(1,N)表示数组是维数为2, 1行和N列。
让我们看一个例子,如下
例子 (Example)
import numpy as np a = np.array([1,2,3,4,5]) b = a.copy () c1 = np.dot(np.transpose(a), b) print(c1) c2 = np.dot(a, np.transpose(b)) print(c2) ax = np.reshape(a, (5,1)) bx = np.reshape(b, (1,5)) c = np.dot(ax, bx) print(c)
使用完全相同的元素填充数组 (Filling arrays with identical elements)
In [30] : a = np.arange(5); a Out[30] : array([0, 1, 2, 3, 4]) In [31] : b = a[2:]; b Out[31] : array([2, 3, 4]) In [32] : b[0] = 100 In [33] : b Out[33] : array([l00, 3, 4]) In [34] : a Out[34] : array([0,1,100,3,4])
副本和视图 (Copies and views)
为避免修改原始数组,可以制作一个切片的副本 (To avoid modifying the original array, one can make a copy of a slice:)
In [30] : a = np.arange(5); a Out[30] : array([0, 1, 2, 3, 4]) In [31] : b = a[2:].copy(); b Out[31] : array([2, 3, 4]) In [32] : b[0] = 100 In [33] : b Out[33] : array([1OO, 3, 4]) In [34] : a Out[34] : array([ 0, 1. 2, 3, 4])
In [1]: A = np.array([[1, 2],[3, 4]]) In [2]: A Out[2]: array([[1, 2], [3, 4]]) In [3]: A * A Out[3]: array([[1, 4], [9, 16]])
使用dot()函数进行矩阵乘法:(Matrix multiplication is done with the dot() function:)
In [4]: np.dot(A, A) Out[4]: array([[ 7, 10], [15, 22]])
矩阵乘法
dot()方法也适用于矩阵向量(matrix-vector)乘法:
In [1]: A Out[1]: array([[1, 2],[3, 4]]) In [2]: x = np.array([10, 20]) In [3]: np.dot(A, x) Out[3]: array([ 50, 110]) In [4]: np.dot(x, A) Out[4]: array([ 70, 100])
将数组保存到文件 (Saving arrays to files)
savetxt()将表保存到文本文件。 (savetxt() saves a table to a text file.)
In [1]: a = np,linspace(0. 1, 12); a,shape ' (3, 4); a Out [1] : array([[ O. , 0.09090909, 0.18181818, 0.27272727], [ 0.36363636, 0.45454545, 0.54545455, 0.63636364], [ 0.72727273, 0.81818182. 0.90909091, 1.]]) In [2] : np.savetxt("myfile.txt", a)
其他可用的格式(参见API文档) {Other formats of file are available (see documentation)}
save()将表保存为Numpy“.npy”格式的二进制文件 (save() saves a table to a binary file in NumPy “.npy” format.)
- In [3] : np.save("myfile" ,a)
生成一个二进制文件myfile .npy,其中包含一个可以使用np.load()加载的文件。 {produces a binary file myfile .npy that contains a and that can be loaded with np.load().}
将文本文件读入数组 (Reading text files into arrays)
loadtxt()将以文本文件存储的表读入数组。 (loadtxt() reads a table stored as a text file into an array.)
默认情况下,loadtxt()假定列是用空格分隔的。 您可以通过修改可选的参数进行更改。 以散列(#)开头的行将被忽略。 (By default, loadtxt() assumes that columns are separated with whitespace. You can change this by modifying optional parameters. Lines starting with hashes (#) are ignored.)
示例文本文件data.txt: (Example text file data.txt:)
|Year| Min temp.| Hax temp.|
|1990| -1.5 | 25.3|
|1991| -3.2| 21.2|
Code:
In [1] : tabla = np.loadtxt("data.txt") In [2] : table Out[2] : array ([[ 1.99000000e+03, -1.50000000e+00, 2.53000000e+01], [ 1.9910000e+03, -3.2000000e+00, 2.12000000e+01]
Numpy包含更高效率的功能
Numpy包含许多常用的数学函数,例如:
np.log
np.maximum
np.sin
np.exp
np.abs
在大多数情况下,Numpy函数比Math包中的类似函数更有效,特别是对于大规模数据。
Scipy (库)
SciPy的结构
scipy.integrate – >积分和普通微分方程
scipy.linalg – >线性代数
scipy.ndimage – >图像处理
scipy.optimize – >优化和根查找(root finding)
scipy.special – >特殊功能
scipy.stats – >统计功能
…
要加载一个特定的模块,请这样使用, 例如 :
from scipy import linalg
线性代数 (Linearalgebra)
线性方程的解 (Solution of linear equations:)
import numpy as np from scipy import linalg A = np.random.randn(5, 5) b = np.random.randn(5) x = linalg.solve(A, b) # A x = b#print(x) eigen = linalg.eig(A) # eigens#print(eigen) det = linalg.det(A) # determinant print(det)
linalg的其他有用的方法:eig()(特征值和特征向量),det()(行列式)。{Other useful functions from linalg: eig() (eigenvalues and eigenvectors), det() (determinant). }
数值整合 (Numerical integration)
integration.quad是一维积分的自适应数值积分的函数。 (integrate.quad is a function for adaptive numerical quadrature of one-dimensional integrals.)
import numpy as np from scipy import integrate def fun(x): return np.log(x) value, error = integrate.quad(fun,0,1) print(value) print(error)
3days_img009_Numerical-integration.jpg
用Scipy进行统计 (Statistics in Scipy)
scipy具有用于统计功能的子库,您可以导入它 (scipy has a sub-library for statistical functions, you can import it by)
from scipy import stats
然后您可以使用一些有用的统计功能。 例如,给出标准正态分布的累积密度函数(Then you are able to use some useful statistical function. For example, the cummulative density function of a standard normal distribution is given like
3days_img010_statistics_in_scipy.jpg
这个包,我们可以直接使用它,如下: (with this package, we can directly use it like)
from scipy import stats y = stats.norm.cdf(1.2)
优化:数据拟合 (Optimisation: Data fitting)
import numpy as np from scipy.optimize import curve_fit import matplotlib.pyplot as plt def func(x, a, b, c): return a * np.exp(-b * x) + c x = np.linspace(0, 4, 50) y = func(x, 2.5, 1.3, 0.5) ydata = y+0.2*np.random.normal(size=len(x)) popt, pcov = curve_fit(func, x, ydata) plt.plot(x, ydata, ’b*’) plt.plot(x, func(x, popt[0], / popt[1], popt[2]), ’r-’) plt.title(’$f(x)=ae^{-bx}+c$ curve fitting’)
3days_img011_data_fitting.jpg
优化:根搜索 (Optimisation: Root searching)
import numpy as np from scipy import optimize def fun(x): return np.exp(np.exp(x)) - x**2 # 通过初始化点0,找到兴趣0 (find zero of fun with initial point 0) # 通过Newton-Raphson方法 (by Newton-Raphson) value1 = optimize.newton(fun, 0) # 通过二分法找到介于(-5,5)之间的 (find zero between (-5,5) by bisection) value2 = optimize.bisect(fun, -5, 5)
Matplotlib
最简单的制图 (The simplest plot)
导入库需要添加以下内容
from matplotlib import pyplot as plt
为了绘制一个函数,我们操作如下 (To plot a function, we do:)
import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 10, 201) #y = x ** 0.5 #plt.plot(x, y) # default plot plt.figure(figsize = (3, 3)) # new fig plt.plot(x, x**0.3, ’r--’) # red dashed plt.plot(x, x-1, ’k-’) # continue plot plt.plot(x, np.zeros_like(x), ’k-’)
注意:您的x轴在plt.plot函数中应与y轴的尺寸相同。 (Note: Your x-axis should be the same dimension to y-axis in plt.plot function.)
3days_img012_the_simplest_plot.jpg
多个制图图例标签和标题 (Mu
ltiple plotting, legends, labels and title)
import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 10, 201) plt.figure(figsize = (4, 4)) for n in range(2, 5): y = x ** (1 / n) plt.plot(x, y, label=’x^(1/’ / + str(n) + ’)’) plt.legend(loc = ’best’) plt.xlabel(’X axis’) plt.ylabel(’Y axis’) plt.xlim(-2, 10) plt.title(’Multi-plot e.g. ’, fontsize = 18)
两个变量的函数3D制图(3D plot of a function with 2 variables)
import numpy as np import matplotlib.pyplot as plt from matplotlib import cm from mpl_toolkits.mplot3d import Axes3D x, y = np.mgrid[-5:5:100j, -5:5:100j] z = x**2 + y**2 fig = plt.figure(figsize=(8, 6)) ax = plt.axes(projection='3d') surf = ax.plot_surface(x, y, z, rstride=1,/ cmap=cm.coolwarm, cstride=1, / linewidth=0) fig.colorbar(surf, shrink=0.5, aspect=5) plt.title('3D plot of $z = x^2 + y^2$')
3days_img016_3D_plot.jpg
实验3:atplotlib (Lab 3: Matplotlib)
用蓝线绘制以下函数 (Plot the following function with blue line)
3days_img017_1.jpg
然后用红点标记坐标(1,2) (Then mark the coordinate (1, 2) with a red point.)
使用np.linspace()使t ∈ [0,2π]。 然后给 (Use np.linspace0 to make t ∈ [0,2π]. Then give)
3days_img017_2.jpg
针对X绘Y。 在这个情节中添加一个称为“Heart”的标题。 (Plot y against x. Add a title to this plot which is called “Heart” .)
针对x∈[-10,10], y∈[-10,10], 绘制3D函数 (Plot the 3D function for x∈[-10,10], y∈[-10,10])
3days_img017_3.jpg
Sympy
符号计算 (Symbolic computation)
到目前为止,我们只考虑了数值计算。 (So far, we only considered the numerical computation.)
Python也可以通过模块表征进行符号计算。(Python can also work with symbolic computation via module sympy.)
符号计算可用于计算方程,积分等的显式解。 (Symbolic computation can be useful for calculating explicit solutions to equations, integrations and so on.)
声明一个符号变量 (Declare a symbol variable)
import sympy as sy #声明x,y为变量 x = sy.Symbol('x') y = sy.Symbol('y') a, b = sy.symbols('a b') #创建一个新符号(不是函数 f = x**2 + 2 - 2*x + x**2 -1 print(f) #自动简化 g = x**2 + 2 - 2*x + x**2 -1 print(g)
符号的使用1:求解方程 (Use of symbol 1: Solve equations)
import sympy as sy x = sy.Symbol ('x') y = sy.Symbol('y') # 给定[-1,1] (give [-1, 1]) print(sy.solve
(x**2 - 1)) # 不能证解决 (no guarantee for solution) print(sy.solve(x**3 + 0.5*x**2 - 1)) # 用x的表达式表示y (exepress x in terms of y) print (sy.solve(x**3 + y**2)) # 错误:找不到算法 (error: no algorithm can be found) print(sy.solve(x**x + 2*x - 1))
符号的使用2:集成 (Use of symbol 2: Integration)
import sympy as sy x = sy.Symbol('x') y = sy.Symbol( 'y') b = sy.symbols ( 'a b') # 单变量 single variable f = sy.sin(x) + sy.exp(x) print(sy.integrate(f, (x, a, b))) print(sy.integrate(f, (x, 1, 2))) print(sy.integrate(f, (x, 1.0,2.0))) # 多变量 multi variables g = sy.exp(x) + x * sy.sin(y) print(sy.integrate(g, (y,a,b)))
符号的使用3:分化 (Use of symbol 3: Differentiation)
import sympy as sy x = sy.Symbol( 'x') y = sy.Symbol( 'y') # 单变量 (single variable) f = sy.cos(x) + x**x print(sy . diff (f , x)) # 多变量 (multi variables) g = sy.cos(y) * x + sy.log(y) print(sy.diff (g, y))