python數學工具(一)


python  數學工具包括:

1.函數的逼近

  1.1.回歸

  1.2.插值

2.凸優化
3.積分
4.符號數學

 

本文介紹函數的逼近的回歸方法

1.作為基函數的單項式

對函數 的擬合

首先定義函數並且可視化

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

def f(x):
    return np.sin(x)+0.5*x

x=np.linspace(-2*np.pi,2*np.pi,50)
plt.plot(x,f(x),'b')
plt.xlabel('x')
plt.ylabel('f(x)')
plt.grid(True)

 

先用一次函數擬合

reg=np.polyfit(x,f(x),deg=1)
ry=np.polyval(reg,x)
plt.plot(x,f(x),'b',label='f(x)')
plt.grid(True)
plt.plot(x,ry,'r.',label='reg')
plt.legend(loc=0)

  

 

再用高次函數進行擬合

 

reg=np.polyfit(x,f(x),deg=16)
ry=np.polyval(reg,x)
plt.plot(x,f(x),'b',label='f(x)')
plt.grid(True)
plt.plot(x,ry,'r.',label='reg')
plt.legend(loc=0)

  

擬合效果的檢查

print('平均誤差:',sum((ry-f(x))**2)/len(x))

平均誤差: 3.16518401761e-13

  

np.allclose(ry,f(x))

True

 

2.單獨的基函數

首先常見一個空的矩陣,然后為任一行添加函數

mat=np.zeros((3+1,len(x)))
mat[3,:]=x**3
mat[2,:]=x**2
mat[1,:]=x
mat[0,:]=1

reg=np.linalg.lstsq(mat.T,f(x))

#輸出系數
reg[0]
array([  1.52685368e-14,   5.62777448e-01,  -1.11022302e-15,
        -5.43553615e-03])


  

#輸出圖形
ry=np.dot(reg[0],mat)


plt.plot(x,f(x),'b',label='f(x)')
plt.plot(x,ry,'r.',label='reg')
plt.grid(True)
plt.legend(loc=0)

  

對每行的基函數進行變換:

mat=np.zeros((3+1,len(x)))
mat[3,:]=np.sin(x)
mat[2,:]=x**2
mat[1,:]=x
mat[0,:]=1

reg=np.linalg.lstsq(mat.T,f(x))

ry=np.dot(reg[0],mat)


plt.plot(x,f(x),'b',label='f(x)')
plt.plot(x,ry,'r.',label='reg')
plt.grid(True)
plt.legend(loc=0)

  

3.多維情形

def fm(x,y):
    return np.sin(x) + 0.25 * x + np.sqrt(y) + 0.05**y*2


x = np.linspace(0, 10, 20)
y = np.linspace(0, 10, 20)
x, y = np. meshgrid( x, y)

Z = fm(x,y)
x = x.flatten()
y = x. flatten()

import statsmodels.api as sm

matrix=np.zeros((len(x),6+1))

matrix[:,6] = np.sqrt(y)
matrix[:,5] = np.sin(x)
matrix[:,4] = y**2
matrix[:,3] = y**2
matrix[:,2] = y
matrix[:,1] = x
matrix[:,0] = 1

res=sm.OLS(fm(x,y),matrix).fit()

print(res.summary().as_text())

  

                         OLS Regression Results                            
==============================================================================
Dep. Variable:                      y   R-squared:                       0.999
Model:                            OLS   Adj. R-squared:                  0.999
Method:                 Least Squares   F-statistic:                 9.605e+04
Date:                Tue, 31 Jul 2018   Prob (F-statistic):               0.00
Time:                        10:51:36   Log-Likelihood:                 661.47
No. Observations:                 400   AIC:                            -1313.
Df Residuals:                     395   BIC:                            -1293.
Df Model:                           4                                         
Covariance Type:            nonrobust                                         
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
const          1.9548      0.010    193.732      0.000       1.935       1.975
x1             0.5891      0.005    111.546      0.000       0.579       0.600
x2             0.5891      0.005    111.546      0.000       0.579       0.600
x3            -0.0150      0.000    -54.014      0.000      -0.016      -0.014
x4            -0.0150      0.000    -54.014      0.000      -0.016      -0.014
x5             0.9533      0.004    251.168      0.000       0.946       0.961
x6            -1.6190      0.020    -79.979      0.000      -1.659      -1.579
==============================================================================
Omnibus:                        4.352   Durbin-Watson:                   0.880
Prob(Omnibus):                  0.113   Jarque-Bera (JB):                4.214
Skew:                          -0.208   Prob(JB):                        0.122
Kurtosis:                       2.717   Cond. No.                     4.93e+17
==============================================================================

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM