线性回归和岭回归
我近半年每个月所写博客的数量
# -*- 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()
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)
· AI 智能体引爆开源社区「GitHub 热点速览」