机器学习3 发表于 2019-03-10 字数统计: | 阅读时长 ≈ 机器学习3( matplotlib补充以及线性回归之最小二乘法的实现)1.matplotlib补充123456789101112131415161718192021222324252627282930import numpy as npimport matplotlib as mpfrom pylab import *figure(figsize=(16,6),dpi=80)subplot(1,1,1)#创建等差数列X=np.linspace(-np.pi,np.pi,256,endpoint=True)c,s=np.cos(X),np.sin(X)#绘制余弦曲线plot(X,c,color="blue",linewidth=1.0,linestyle="-")#绘制正弦曲线plot(X,s,color="green",linewidth=1.0,linestyle="-")xlim(-4.0,4.0)#设置上下限,设置横轴标记符xticks(np.linspace(-4,4,9,endpoint=True))ylim(-1.0,1.0)yticks(np.linspace(-1,1,5,endpoint=True))#设置边界xlim(X.min()*(1.1),X.max()*1.1)ylim(c.min()*1.1,c.max()*1.1)#设置记号xticks([-np.pi,-np.pi/2,0,np.pi/2,np.pi],[r'$-\pi$',r'$-\pi/2$',r'$0$',r'$+\pi/2$',r'$+\pi$'])yticks([-1,0,+1],[r'$-1$',r'$-\pi/2$',r'$0$',r'$+\pi/2$',r'$+\pi$'])savefig("exciese1",dpi=72) 2.线性回归之最小二乘法(使用sklearn中的糖尿病数据集)12345678910111213141516171819202122232425262728293031323334import matplotlib.pyplot as pltimport numpy as npfrom sklearn import datasets,linear_modelfrom sklearn.metrics import mean_squared_error,r2_score#加载数据集diabetes=datasets.load_diabetes()diabetes_X=diabetes.data[:,np.newaxis,2]diabetes_x_train=diabetes_X[:-20]diabetes_x_test=diabetes_X[-20:]diabetes_y_train=diabetes.target[:-20]diabetes_y_test=diabetes.target[-20:]regr=linear_model.LinearRegression()regr.fit(diabetes_x_train,diabetes_y_train)diabetes_y_predict=regr.predict(diabetes_x_test)#系数print(regr.coef_)#均方差print("%.2f"%mean_squared_error(diabetes_y_test,diabetes_y_predict))#预测print("得分:%.2f"%r2_score(diabetes_y_test,diabetes_y_predict))#绘制结果plt.scatter(diabetes_x_test,diabetes_y_test,color='black')plt.plot(diabetes_x_test,diabetes_y_predict,color='blue',linewidth=3)plt.xticks()plt.yticks()plt