1 import scipy as sp 2 data = sp.genfromtxt("web_traffic.tsv", delimiter="\t") 3 x = data[:,0] 4 y = data[:,1] 5 x = x[~sp.isnan(y)] 6 y = y[~sp.isnan(y)] 7 import matplotlib.pyplot as plt 8 plt.scatter(x,y) 9 plt.title("Web traffic over the last month") 10 plt.xlabel("Time") 11 plt.ylabel("Hits/hour") 12 plt.xticks([w*7*24 for w in range(10)], 13 [‘week %i‘%w for w in range(10)]) 14 15 def error(f,x,y): 16 return sp.sum((f(x)-y)**2) 17 18 fp1, residuals, rank, sv, rcomd = sp.polyfit(x,y,1,full=True) 19 f1 = sp.poly1d(fp1) 20 fx = sp.linspace(0,x[-1], 1000) 21 plt.plot(fx, f1(fx), linewidth=4) 22 plt.legend(["d=%i" % f1.order], loc="upper left") 23 24 f2p = sp.polyfit(x, y, 2) 25 f2 = sp.poly1d(f2p) 26 fx = sp.linspace(0,x[-1], 1000) 27 plt.plot(fx, f2(fx), linewidth=4) 28 plt.legend(["d=%i" % f2.order], loc="upper left") 29 30 f3p = sp.polyfit(x, y, 3) 31 f3 = sp.poly1d(f3p) 32 fx = sp.linspace(0,x[-1], 1000) 33 plt.plot(fx, f3(fx), linewidth=4) 34 plt.legend(["d=%i" % f3.order], loc="upper left") 35 36 plt.autoscale(tight=True) 37 plt.grid() 38 plt.show()
Note:
1>polyfit() 在图中画出要拟合的线。给定数据x,y 以及期望的多项式阶,它可以找到一个模型,并且返回函数模型的参数。
2>poly1d() 根据参数创建模型函数。
Building Machine Learning Systems with Python 1
原文:http://www.cnblogs.com/michael2016/p/5203985.html