For example, to plot variable x
versus variable f1
:
plt.figure(figsize=(8,5))
plt.plot(x, f1, 'k-', lw=3)
plt.title('Figure: Example of Line Graph', fontsize=14)
plt.xlabel(r'$x$', fontsize=12)
plt.ylabel(r'$f(x)$', fontsize=12)
plt.show()
x = np.arange(0,50.2,0.2)
f1 = np.sin(x)+1
plt.figure(figsize=(8,5))
plt.plot(x, f1, 'k-', lw=3)
plt.title('Figure: Example of Smooth Line Graph', fontsize=14)
plt.xlabel(r'$x$', fontsize=12)
plt.ylabel(r'$f(x)$', fontsize=12)
plt.show()
Also, we can add another line graph of function
f2 = np.cos(x)-1
plt.figure(figsize=(8,5))
plt.plot(x, f1, 'k-', lw=3)
plt.plot(x, f2, 'gray', lw=3)
plt.title('Figure: Example of Two Line Graphs', fontsize=14)
plt.xlabel(r'$x$', fontsize=12)
plt.ylabel(r'$f(x)$', fontsize=12)
plt.show()
Alternatively, we can plot two functions in two subplots of a same figure.
plt.figure(figsize=(12,8))
plt.subplot(2,2,1)
plt.plot(x, f1, 'k-', lw=3)
plt.title('$Figure: f(x)=sin(x)+1$', fontsize=14)
plt.xlabel(r'$x$', fontsize=12)
plt.ylabel(r'$f(x)$', fontsize=12)
# 指定subplot的尺寸构图为2行2列当中的第2个图
plt.subplot(2,2,2)
plt.plot(x, f2, 'k-', lw=3)
plt.title('$Figure: f(x)=cos(x)-1$', fontsize=14)
plt.xlabel(r'$x$', fontsize=12)
plt.ylabel(r'$f(x)$', fontsize=12)
# 展示图片
plt.show()
# 图片格式微调
plt.figure(figsize=(8,5))
plt.title("Figure: Title of the figure",
fontsize=14) # 图像的全称
plt.xlabel(r"$x$", fontsize=12)
plt.ylabel(r"$f(x)$", fontsize=12)
plt.plot(x, f1, label="$sin(x)+1$",
color="k",
linewidth=1)
plt.plot(x, f2, label="$cos(x)-1$", color="gray",
linewidth=3, linestyle="dotted")
plt.legend(fontsize=12)
plt.grid() # 在图像当中输出网格分割线
plt.show() # 在图像当中将目标图像画出
figsize=(8,4)
restricts the figure size to 8 by 4 inches.label
defines the name of this line and will in the legend()
.legend()
displays a legend with the labels.grid()
displays a grid on the backdrop.plt.plot
we can choose the line style, thickness, color, etc.bisect()
) algorithm, which is robust and conceptually simple.bisect()
method takes three compulsory arguments:
f
: the function a
,b
.Clearly,
from scipy.optimize import bisect
def f(x):
return x**3 - 2 * x**2
x1 = bisect(f, a=-1, b=0)
x2 = bisect(f, a=1.5, b=3)
x1,x2
(0.0, 1.9999999999995453)
fsolve
method can be applied for more general purposes,
fsolve
algorithm needs only one starting point (x0
option) close to the suspected location of the root.from scipy.optimize import fsolve
x1 = fsolve(f, x0=0)
x2 = fsolve(f, x0=2)
x1, x2
(array([0.]), array([2.]))
fmin()
and minimize()
methods can perform such tasks.scipy.optimize.fmin()
command and try to maximize a simple function to find from numpy import arange,cos,exp
from scipy.optimize import fmin
def f(x):
return cos(x) - 3*exp(-(x-0.2)** 2)
x = arange(-20,20,0.1)
y = f(x) # Note, -f(x) = g(x)
plt.figure(figsize=(8,5))
plt.plot(x, y, 'k-', lw=3)
plt.title('Figure: Inspect the Function $f(x)=\cos(x) - 3\exp[-(x-0.2)^2]$', fontsize=14)
plt.xlabel(r'$x$', fontsize=12)
plt.ylabel(r'$f(x)$', fontsize=12)
plt.grid()
plt.show()
scipy.optimize.fmin(f,x0)
function takes two arguments:
f
to minimizex0
from which to start the search.It returns the value x
for which f(x) is locally minimized.
x0=2
or x0=12
) might be failed to find the global minima.# 从1,2,12开始,分别寻找f(x)的最小值
minimum1 = fmin(f, 1.0)
print("Start search at x=1, minimum is",minimum1)
minimum2 = fmin(f, 2.0)
print("Start search at x=2, minimum is",minimum2)
minimum3 = fmin(f, 12.0)
print("Start search at x=12, minimum is",minimum3)
Optimization terminated successfully.
Current function value: -2.023866
Iterations: 16
Function evaluations: 32
Start search at x=1, minimum is [0.23964844]
Optimization terminated successfully.
Current function value: -1.000529
Iterations: 16
Function evaluations: 32
Start search at x=2, minimum is [3.13847656]
Optimization terminated successfully.
Current function value: -1.000000
Iterations: 17
Function evaluations: 34
Start search at x=12, minimum is [9.42480469]
scipy.optimize.minimize(f,x0)
function has a similar syntax
from scipy.optimize import minimize
minimize(f, 1.0).x, minimize(f, 2.0).x, minimize(f, 12.0).x
(array([0.23961728]), array([3.13845708]), array([9.42477932]))
For different starting values:
x = arange(-8,13,0.1)
y = f(x)
plt.figure(figsize=(8,5))
plt.plot(x, y,'gray',lw=2)
plt.title('Figure: Multiple Optima of Function $\cos(x)-3e^{ -(x -0.2)^2}$', fontsize=14)
plt.xlabel(r'$x$', fontsize=12)
plt.ylabel(r'$f(x)$', fontsize=12)
plt.grid()
plt.plot(1.0 ,f(1.0), 'ok', label ='start 1=1')
plt.plot(minimum1, f(minimum1), 'vk', label='minimum 1')
plt.plot(2.0, f(2.0), 'sk', label='start 2=2')
plt.plot(minimum2, f(minimum2), 'Dk', label='minimum 2')
plt.plot(12.0 ,f(12.0), '^k', label='start 3=12')
plt.plot(minimum3, f(minimum3), 'Xk', label='minimum 3')
plt.legend(loc='lower left', fontsize=12, framealpha=0.6)
plt.show()
scipy.stats
.For the PDF of a uniform distribution
from scipy.stats import uniform
uniform.pdf([0,1,2,3,4], loc=0, scale=1)
array([1., 1., 0., 0., 0.])
norm(loc,scale)
function to implement.
loc
(location) keyword specifies the mean,scale
keyword specifies the standard deviation.from scipy.stats import norm
norm.pdf(np.array([0,-1,1,-200,100]))
array([0.39894228, 0.24197072, 0.24197072, 0. , 0. ])
norm.cdf(np.array([0,-1,1,-2,10]))
array([0.5 , 0.15865525, 0.84134475, 0.02275013, 1. ])
To find the q-th quantile of a distribution, we can use the Percent Point Function (norm.ppf(q)
):
norm.ppf(0.5)
0.0
The median can also be found using median
method directly:
norm.median(loc=0, scale=1)
0.0
Similarly, mean
, var
and std
functions give the mean, variance, and standard deviation of the distribution.
print( "Mean of N(5,10) is %2.1f"
% (norm.mean(loc=5, scale=10)))
print( "Variance of N(5,10) is %2.1f"
% (norm.var(loc=5, scale=10)))
print( "Standard deviation of N(5,10) is %2.1f"
% (norm.std(loc=5, scale=10)))
Mean of N(5,10) is 5.0
Variance of N(5,10) is 100.0
Standard deviation of N(5,10) is 10.0
To generate a sequence of random normal variates:
norm.rvs(0, 10, size=4)
array([-21.50986762, -5.84663993, 6.56998426, 11.75718474])
To generate the same random numbers, use the seed function.
plt.figure(figsize=(8, 5))
# Histogram
plt.hist(norm.rvs(0, 1, size=1000), bins=20, alpha=0.2,
density=True, color='gray', label='Histogram')
# PDF
x = np.linspace(norm.ppf(0.01), norm.ppf(0.99), 100)
plt.plot(x, norm.pdf(x), 'k-', lw=5, alpha=0.6,
label='N(0,1) PDF')
plt.title('Figure: Normal Distribution', fontsize=14)
plt.xlabel(r'$X$', fontsize=12)
plt.ylabel('density', fontsize=12)
plt.legend(loc='best', fontsize=12)
plt.show()
poisson
object.from scipy.stats import poisson
poisson.pmf(k=6, mu=3)
0.05040940672246224
binom
function takes n
and p
as shape parameters, where n
is the number of trails and p
is the probability of a single failure.from scipy.stats import binom
binom.pmf(k=5, n=10, p=0.4, loc=1)
0.25082265599999987
Note that binom.pmf(k, n, p, loc)
is identically equivalent to binom.pmf(k - loc, n, p)
.
binom.pmf(k=5-1, n=10, p=0.4, loc=0)
0.25082265599999987
The expon
function in scipy.stats
is for the exponential distribution. E.g.,
from scipy.stats import expon
expon.cdf(x=10, loc=0, scale=5)
0.8646647167633873
quad()
(stands for quadrature) function in the scipy.integrate
module performs the numerical integration of the kindquad()
function takes arguments of
import scipy
from math import cos, exp, pi
from scipy.integrate import quad
# 定义我们需要积分的函数
def f(x):
return(exp(cos(-2*x*pi) + 3.2))
result, error = quad(f,-2,2)
print("The numerical result is %f (+- %g)" % (result,error))
The numerical result is 124.239198 (+- 3.80539e-10)
quad
returns a tuple with two values:
print(quad(f, -2, 2, epsabs=1))
print(quad(f, -2, 2, epsabs=1.5e-25))
(124.23919750991882, 0.0004461052678550459)
(124.23919750992361, 3.805389029468099e-10)
We use odeint
function to solve an ordinary differential equation of the type
Consider the example finds
from scipy.integrate import odeint
# 定义ODE
def f(y,t):
return -2*y*t
# Initial value 起始值
y0 = 1
# 积分区间
a = 0
b = 2
# 定义t的值
t = np.arange(a,b,0.01)
# 利用odeint()函数实现
y = odeint(f, y0, t)
plt.figure(figsize=(8,5))
plt.plot(t, y,'k-',lw=2)
plt.title(r'Figure: The Function $y(t)$', fontsize=14)
plt.xlabel(r'$t$', fontsize=12)
plt.ylabel(r'$y(t)$', fontsize=12)
plt.show()
Create symbolic variables using SymPy’s Symbol
function:
import sympy
x = sympy.Symbol('x')
y = sympy.Symbol('y')
y - x + y + 10 * y**6
Variables with subscription (and in Greek letters) can also be defined:
x1 = sympy.Symbol('x_1')
x2 = sympy.Symbol('x_2')
alpha1 = sympy.Symbol('alpha_1')
rho2 = sympy.Symbol('rho_2')
Sigma = sympy.Symbol('Sigma_n')
x1 + x2 + alpha1 + Sigma + rho2
We can abbreviate the creation of multiple symbolic variables using the symbols
function.
x,y,z = sympy.symbols('x,y,z')
equation = x + 2/y*z + z**2
equation
Btw, latex()
function converts results to latex code:
sympy.latex(equation) # 把符号转换为TeX代码
'x + z^{2} + \\frac{2 z}{y}'
To insert real numerical values instead of generic variables:
x,y = sympy.symbols('x,y')
(x + 2*y).subs(x, 10)
(x + 2*y).subs(x, 10).subs(y, 3)
We can also substitute a symbolic variable for another one by:
myterm = 3*x + y**2
myterm.subs(x, y).subs(y, 2)
Define a symbolic function Function
method:
x,y,theta,n = sympy.symbols('x,y,theta,n')
l = sympy.Function('l')(x,y,theta,n)
l
Variables can be defined after generating the function:
g = sympy.Function('g')
g(x,y,theta,n)
solvers
.x = sympy.symbols('x')
sympy.solvers.solve(x**2 - 2*x)
[0, 2]
def f(x):
return x**3 - 2*x - 5
sympy.solvers.solve(f(x))
[(-1/2 - sqrt(3)*I/2)*(sqrt(1929)/18 + 5/2)**(1/3) + 2/(3*(-1/2 - sqrt(3)*I/2)*(sqrt(1929)/18 + 5/2)**(1/3)),
2/(3*(-1/2 + sqrt(3)*I/2)*(sqrt(1929)/18 + 5/2)**(1/3)) + (-1/2 + sqrt(3)*I/2)*(sqrt(1929)/18 + 5/2)**(1/3),
2/(3*(sqrt(1929)/18 + 5/2)**(1/3)) + (sqrt(1929)/18 + 5/2)**(1/3)]
diff(function, variable)
function:x,y,z = sympy.symbols('x,y,z')
sympy.diff(2*x, x)
sympy.diff(10 + 3*x + 4*y**2 + 10* x**2 + x**9 , y)
sympy.diff(10 + 3*x + 4*y**2 + 10* x**2 + x**9 , y).subs(y, 2)
For higher derivatives:
sympy.diff(3*x**4, x)
sympy.diff(3*x**4, x, x)
sympy.diff(3*x**4, x, x, x)
For the partial derivative with respect to different variables:
sympy.diff(sympy.diff(x**2 * y**7, x), y)
The integration uses a similar syntax.
x,y = sympy.symbols('x,y')
sympy.integrate(x**2, x) # 积分方程X^2
sympy.integrate(x**2, (x, 0, 1))
sympy.series(expression, x=None, x0=0, n=6)
.x = sympy.Symbol('x')
# 对方程sin(x) 关于x在x=0的附近展开
sympy.series(sympy.sin(x), x, x0=0)
We can also specify
- the point around which to expand (x0=0
by default),
- the maximum term number by option n
,
- and the direction of the expansion.
sympy.series(sympy.sin(x), x, x0=0, n=10)
x0 = sympy.Symbol('x_0')
sympy.series(sympy.sin(x), x, x0, 5)
One might wish to discard the big-O term:
sympy.series(sympy.sin(x), x, x0, 5).removeO() # 对方程sin(x) 关于x在x0的附近展开,并且最高次项等于5并且去掉大O项
sympy.stats
sub-module introduces a random variable type into the SymPy.
The normally distributed variable Normal(X, mean, std)
from sympy.stats import *
x = sympy.Symbol('x')
X = Normal("X", 0, 1) # 定义变量X服从mean为0,sd为1的正态分布
And its pdf. and cdf. can be seen:
density(Normal("X", 0, 1))(x) # 变量X的pdf
P(X <= 0) # 变量X小于0的概率
P(X < x) # 变量X小于x的概率
For the expectation and variance quantities:
E(X), variance(X*8+5)
(0, 64)
X = Normal("X", 0, 1)
Y = Normal("Y", 0, 1)
variance(X+Y)
MatrixSymbol
method to define a Z = sympy.MatrixSymbol('Z', 2, 1)
We must specify the variance-covariance matrix using SymPy.
sympy.Identity(2).as_explicit()
Z = (Normal("Z", [0,0], sympy.Identity(2).as_explicit()) )
variance(Z[0]+Z[1])
For the density function:
z = sympy.MatrixSymbol('z', 2, 1)
density(Z)(z)
Cov = sympy.Matrix([[1,0.2],[0.2,1]])
Z = (Normal("Z", sympy.Matrix([0, 0]), Cov))
variance(Z[0]+Z[1])