线性回归和岭回归
我近半年每个月所写博客的数量
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 1 18:23:07 2017
@author: Administrator
"""
from sklearn import linear_model
import numpy as np
import matplotlib.pyplot as plt
y=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 PolynomialFeatures
from sklearn.pipeline import make_pipeline
import numpy as np
import matplotlib.pyplot as plt
from 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()