线性回归和岭回归

来源:互联网 发布:matlab对离散数据求导 编辑:程序博客网 时间:2024/04/28 18:32

  我近半年每个月所写博客的数量

# -*- coding: utf-8 -*-"""Created on Fri Sep  1 18:23:07 2017@author: Administrator"""from sklearn import linear_modelimport numpy as npimport matplotlib.pyplot as plty=np.array([13,12,32,0,1,7,27]).reshape(-1,1)x=np.array([2,3,4,5,6,7,8]).reshape(-1,1)plt.plot(x,y)plt.rcParams['font.sans-serif'] = ['SimHei'] #用来正常显示中文标签plt.rcParams['axes.unicode_minus'] = False #用来正常显示负号##设置模型model = linear_model.LinearRegression()##训练数据model.fit(x, y)##用训练得出的模型预测数据y_plot = model.predict(x)##打印线性方程的权重print(model.coef_) ## 0.90045842、plt.scatter(x, y, color='red',label="样本数据",linewidth=2)plt.plot(x, y_plot, color='green',label="拟合直线",linewidth=2)plt.legend(loc='lower right')plt.show()from sklearn.preprocessing import PolynomialFeaturesfrom sklearn.pipeline import make_pipelineimport numpy as npimport matplotlib.pyplot as pltfrom sklearn.linear_model import Ridge##这里指定使用岭回归作为基函数model = make_pipeline(PolynomialFeatures(15), Ridge())model.fit(x, y)##根据模型预测结果y_plot = model.predict(x)##绘图plt.scatter(x, y, color='red',label="样本数据",linewidth=2)plt.plot(x, y_plot, color='green',label="拟合直线",linewidth=2)plt.legend(loc='lower right')plt.show()

这里写图片描述

这里写图片描述

原文链接