您的位置:首页 > 其它

《Pattern Recognition and Machine Learning》:第一章,introduction(第一节:polynomial curve fitting)

2015-09-07 10:51 579 查看
开学了,以前学好多东西都忘了,趁此机会把未看的经典《Pattern Recognition and Machine Learning》看一下,回忆知识点,加深理解,但只记录新的理解

1.1节讲了一个例子,polynomial curve fitting。

1)使用root-mean-square(RMS) error比使用sum of squared errors好:

RMS不受样本数的影响:不同样本数得出的两个errors可以简单比较。

RMS的error和target y的数量级是一样的,因为square之后进行了root操作。

2)防止over-fitting的方法:

limit the number of parameters,减少模型复杂度。

adopting Bayesian approach,有先验,对少量数据适用。

regularization,注意 w0 一般不包含在regularizer内。

validation,分割数据集并单独验证参数泛化能力。

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

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

from sklearn.pipeline import Pipeline  
from sklearn.linear_model import LinearRegression  
from sklearn.preprocessing import PolynomialFeatures

#RMS
def rmse(y_test, y_true):  
    return sp.sqrt(sp.mean((y_test - y_true) ** 2))
  
# the sum of the squares of the errors
def sse(y_test, y_true):  
    return ((y_test - y_true) ** 2).sum() / 2.0

# load training and test datasets  
data = pd.read_csv('fitting.csv')

X = data.id.values  
y = data.dingdanshu.values 
X = np.array(X)    
y = np.array(y)
X = X[2:20]
y = y[2:20]
#print X
#print y

# plot scatter of original data
plt.scatter(X, y)

degree = [1, 2, 3, 4, 5]
for d in degree:
    clf = Pipeline([ ('poly', PolynomialFeatures(degree=d)), ('linear', LinearRegression(fit_intercept=False)) ])
    clf.fit(X[:, np.newaxis], y)
    y_test = clf.predict(X[:, np.newaxis])  

    print(clf.named_steps['linear'].coef_)
    print('rmse=%.2f, sse=%.2f, clf.score=%.2f' % (rmse(y_test, y),  sse(y_test, y), clf.score(X[:, np.newaxis], y)) )
    
    # plot fit line of y_test
    plt.plot(X, y_test, linewidth=2)
    
plt.grid()
plt.legend(['1', '2', '3','4','5'], loc='upper right')  
plt.show()

''' 对5次多项式求 每个点处的曲率
aa=clf.named_steps['linear'].coef_
for i in range(20):
    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
    y2=aa[2]*2+aa[3]*6*i+aa[4]*12*i*i+aa[5]*20*i*i*i
    r = (y2*y2)/((1+y1*y1)*(1+y1*y1)*(1+y1*y1))
    print i, "---", y1, "---", y2, "---", r
'''
结果如图所示:



提供部分数据:

iddingdanshu
0153880
1246449
2178882
3120823
482616
560869
648609
739028
832532
928355
1025058
1122341
1220822
1319471
1417555
1516965
1615134
1714305
1812716
1911684
2011274
2110270
229139
238210
247848
256906
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: