machine learning in coding(python):polynomial curve fitting,python拟合多项式

下面给出一个拟合多项式的例子:

[python]  view plain copy
  1. import pandas as pd    
  2. import numpy as np  
  3. import scipy as sp  
  4. import matplotlib.pyplot as plt  
  5.   
  6.   
  7. from sklearn.pipeline import Pipeline    
  8. from sklearn.linear_model import LinearRegression    
  9. from sklearn.preprocessing import PolynomialFeatures  
  10.   
  11.   
  12. #RMS  
  13. def rmse(y_test, y_true):    
  14.     return sp.sqrt(sp.mean((y_test - y_true) ** 2))  
  15.     
  16. # the sum of the squares of the errors  
  17. def sse(y_test, y_true):    
  18.     return ((y_test - y_true) ** 2).sum() / 2.0  
  19.   
  20.   
  21.   
  22.   
  23. # load training and test datasets    
  24. data = pd.read_csv('fitting.csv')  
  25.   
  26. X = data.id.values    
  27. y = data.dingdanshu.values   
  28. X = np.array(X)      
  29. y = np.array(y)  
  30. X = X[2:20]  
  31. y = y[2:20]  
  32. #print X  
  33. #print y  
  34.   
  35.   
  36. # plot scatter of original data  
  37. plt.scatter(X, y)  
  38.   
  39. degree = [12345]  
  40. for d in degree:  
  41.     clf = Pipeline([ ('poly', PolynomialFeatures(degree=d)), ('linear', LinearRegression(fit_intercept=False)) ])  
  42.     clf.fit(X[:, np.newaxis], y)  
  43.     y_test = clf.predict(X[:, np.newaxis])    
  44.   
  45.     print(clf.named_steps['linear'].coef_)  
  46.     print('rmse=%.2f, sse=%.2f, clf.score=%.2f' % (rmse(y_test, y),  sse(y_test, y), clf.score(X[:, np.newaxis], y)) )  
  47.       
  48.     # plot fit line of y_test  
  49.     plt.plot(X, y_test, linewidth=2)  
  50.       
  51. plt.grid()  
  52. plt.legend(['1''2''3','4','5'], loc='upper right')    
  53. plt.show()  
  54.   
  55.   
  56. ''''' 对5次多项式求 每个点处的曲率 
  57. aa=clf.named_steps['linear'].coef_ 
  58. for i in range(20): 
  59.     y1=aa[1]+aa[2]*2*i+aa[3]*3*i*i+aa[4]*4*i*i*i+aa[5]*5*i*i*i*i 
  60.     y2=aa[2]*2+aa[3]*6*i+aa[4]*12*i*i+aa[5]*20*i*i*i 
  61.     r = (y2*y2)/((1+y1*y1)*(1+y1*y1)*(1+y1*y1)) 
  62.     print i, "---", y1, "---", y2, "---", r 
  63. '''  
结果如图所示:

machine learning in coding(python):polynomial curve fitting,python拟合多项式_第1张图片


提供部分数据:

id dingdanshu
0 153880
1 246449
2 178882
3 120823
4 82616
5 60869
6 48609
7 39028
8 32532
9 28355
10 25058
11 22341
12 20822
13 19471
14 17555
15 16965
16 15134
17 14305
18 12716
19 11684
20 11274
21 10270
22 9139
23 8210
24 7848
25 6906

你可能感兴趣的:(ML,in,coding,machine,learning,in,coding)