返回 导航

Python

hangge.com

Python - 机器学习算法库Scikit-Leran使用详解2(线性回归算法)

作者:hangge | 2022-08-22 08:10
    Scikit-learn 涵盖了常用的机器学习算法,并且这些算法它都做了良好的 API 封装,可以直接调用。本文通过样例介绍第一个机器学习算法:线性回归算法(Linear Regression),它是机器学习算法中较为简单,且容易理解的算法模型。

三、线性回归算法的应用

1,什么是线性回归?

(1)线性回归主要用来解决回归问题,也就是预测连续值的问题。而能满足这样要求的数学模型被称为“回归模型”。最简单的线性回归模型是我们所熟知的一次函数(即 y=kx+b),这种线性函数描述了两个变量之间的关系,其函数图像是一条连续的直线。如下图红色直线:

(2)上举的例子是一维的例子(x 只有一个),如果有两个特征,就是二元线性回归,要拟合的就是二维空间中的一个平面。如果有多个特征,那就是多元线性回归。多元线性回归通常可考虑如下的线性关系式:

2,一个简单样例

(1)下面是一个基于 sklearn 实现线性回归算法的样例,大致分为如下 3 步:
  • 首先从 sklearn 库中导入线性模型中的线性回归算法
  • 接着使用 fit() 方法喂入训练数据,训练线性回归模型
  • 最后便可以使用训练好的模型 predict() 方法进行预测
#使用numpy准备数据集
import numpy as np
#从 sklearn 库中导入线性模型中的线性回归算法
from sklearn import linear_model
#使用matplotlib绘制图像
import  matplotlib.pyplot as plt
#导入pandas
import pandas as pd 

print('----------------------  准备训练数据集  -------------------------------')
#创建一个随机数据集,其中每个样本包含1个特征x,一个目标y
#x的范围是0到10的区间均分间隔30份数
x = np.linspace(0,10,30)
#y由x的假设函数推倒出来
y = 2 * x + 3
print('x数据:\n',x)
print('y数据:\n',y)
#数据集绘制,散点图
plt.scatter(x,y)
plt.show()

print('---------------------- 数据转换  -------------------------------')
#由于fit 需要传入二维矩阵数据,因此需要处理x,y数据格式,将每个样本信息单独作为矩阵的一行
x=[[i] for i in x]
y=[[i] for i in y]
print('前5条样本数据特征值:')
# 将标签特征数据转化为datafram,更加直观的展现数据(这里只展示前5条数据)
print(pd.DataFrame(x).head(5))
print('前5条样本数据目标值:')
print(pd.DataFrame(y).head(5))


print('------------------------ 开始训练 -----------------------------')
#创建一个线性回归模型
model=linear_model.LinearRegression()
#训练模型
model.fit(x,y)
#准备测试数据 x_,这里准备了三组,如下:
x_=[[3],[4],[7]]
#使用predict()函数预测
y_=model.predict(x_)
#打印预测结果
print('预测数据特征值:')
print(pd.DataFrame(x_))
print('预测数据目标值:')
print(pd.DataFrame(y_))
#查看w和b的
print("\nw值为:",model.coef_)
print("b截距值为:",model.intercept_)
#绘制样本数据的散点图
plt.scatter(x,y)
#绘制预测数据的最佳拟合直线
plt.plot(x_,y_,color="red",linewidth=3.0,linestyle="-")
plt.show()

(2)运行结果如下:

3,给样本数据添加噪声

(1)现实中我们要面临的数据集都不会想上面那么理想,而是会存在一些波动。下面样例我们对每个样本数据都添加随机数,从而增加一些干扰:
#使用numpy准备数据集
import numpy as np
#从 sklearn 库中导入线性模型中的线性回归算法
from sklearn import linear_model
#使用matplotlib绘制图像
import  matplotlib.pyplot as plt
#导入pandas
import pandas as pd 

print('----------------------  准备训练数据集  -------------------------------')
#创建一个随机数据集,其中每个样本包含1个特征x,一个目标y
#x的范围是0到10的区间均分间隔30份数
x = np.linspace(0,10,30)
#y由x的假设函数推倒出来
y = 2 * x + 3
# 添加干扰,扰乱点的分布
y = y + np.random.randn(30)
print('x数据:\n',x)
print('y数据:\n',y)
#数据集绘制,散点图
plt.scatter(x,y)
plt.show()

print('---------------------- 数据转换  -------------------------------')
#由于fit 需要传入二维矩阵数据,因此需要处理x,y数据格式,将每个样本信息单独作为矩阵的一行
x=[[i] for i in x]
y=[[i] for i in y]
print('前5条样本数据特征值:')
# 将标签特征数据转化为datafram,更加直观的展现数据(这里只展示前5条数据)
print(pd.DataFrame(x).head(5))
print('前5条样本数据目标值:')
print(pd.DataFrame(y).head(5))


print('------------------------ 开始训练 -----------------------------')
#创建一个线性回归模型
model=linear_model.LinearRegression()
#训练模型
model.fit(x,y)
#准备测试数据 x_,这里准备了三组,如下:
x_=[[3],[4],[7]]
#使用predict()函数预测
y_=model.predict(x_)
#打印预测结果
print('预测数据特征值:')
print(pd.DataFrame(x_))
print('预测数据目标值:')
print(pd.DataFrame(y_))
#查看w和b的
print("\nw值为:",model.coef_)
print("b截距值为:",model.intercept_)
#绘制样本数据的散点图
plt.scatter(x,y)
#绘制预测数据的最佳拟合直线
plt.plot(x_,y_,color="red",linewidth=3.0,linestyle="-")
plt.show()

(2)运行结果如下:

4,波士顿房价数据应用样例

(1)下面我们以 sklearn 库自带的波士顿房价数据集对线性回归算法进行简单的应用。
提示train_test_split 函数可以打乱数据集,并对其进行拆分。该函数默认将 75% 的行数据及对应标签作为训练集,另外 25% 数据作为测试集。
#导入 sklearn 提供的波士顿房价数据
from sklearn.datasets import load_boston
#导入 sklearn 提供的线性回归算法
from sklearn.linear_model import LinearRegression
#导入skleran 提供的分割数据集的方法
from sklearn.model_selection import train_test_split
#导入pandas
import pandas as pd

#加载数据集
boston = load_boston()
#分割数据集训练集,测试集
x_train,x_test,y_train,y_test=train_test_split(boston['data'],boston['target'],random_state=0)
#创建一个线性回归模型
model=LinearRegression()
#训练模型
model.fit(x_train,y_train)
#训练后用测试集对模型进行评分
print("模型评分:",model.score(x_test,y_test))
print("w值为:",model.coef_)
print("b截距值为:",model.intercept_)
print('-----------------------------------------------------')

print('测试集前5条数据特征值:')
print(pd.DataFrame(x_test).head(5))
print('-----------------------------------------------------')
print('测试集前5条数据目标值:')
print(pd.DataFrame(y_test).head(5))
print('-----------------------------------------------------')
#使用模型预测
y_predict=model.predict(x_test)
print('使用模型预测测试集前5条数据的目标值:')
print(pd.DataFrame(y_predict).head(5))

(2)运行结果如下:
评论

全部评论(0)

回到顶部