线性回归拟合案例

这篇博客介绍了如何使用Python的numpy和matplotlib库进行线性回归分析,包括读取数据、绘制样本点、实现线性回归算法以及用sklearn库进行拟合。博主通过实例展示了如何画出拟合直线,并对比了自定义算法与sklearn库的结果。同时,还应用到波士顿房价数据集来展示线性回归在实际问题中的应用。
摘要由CSDN通过智能技术生成
01.根据数据集ex0.txt,画出样本点。并根据线性回归画出拟合直线。
注:可以采用sklearn里面的线性回归算法也可以自己写线性回归算法
import numpy as np
import matplotlib.pyplot as plt
dataSet=np.genfromtxt('ex0.txt')
x_data=dataSet[:,:-1]#最后一列是因变量y的真实值y=theta∧Tx(x称为自变量)
y_data=dataSet[:,-1]
def plot():
    plt.scatter(x_data[:,1],y_data)#scatter函数是画点
plot()
plt.show()

在这里插入图片描述

def standRegres(xArr,yArr):
    xMat=np.mat(xArr)
    yMat=np.mat(yArr).T#需要的y是一个列向量的形式,原先的y是行向量
    xTx=xMat.T*xMat
    if np.linalg.det(xTx) == 0.0:
        print("这个矩阵是奇异矩阵,矩阵不可逆")
        return
    ws=(xTx).I*(xMat.T*yMat)
    return ws
ws=standRegres(x_data,y_data)
print(ws)

在这里插入图片描述

#根据回归方程,画出拟合直线
yHat=x_data*ws
plt.plot(x_data[:,1],yHat,c='r')
plot()
plt.show()

在这里插入图片描述

#sklearn
import numpy as np
import matplotlib.pyplot as plt
dataSet = np.genfromtxt('ex0.txt')
x_data=dataSet[:,:-1]
y_data=dataSet[:,-1]
def plot():
    plt.scatter(x_data[:,1],y_data,c='blue',s=10)
    plt.xlabel('X')
    plt.ylabel('Y')
plot()
plt.show()

在这里插入图片描述

#案例1

from sklearn.linear_model import LinearRegression
LR=LinearRegression()
XData=x_data[:,1,np.newaxis]
#print('XData:',XData)

#关键点:
#model.fit(x,y) x即特征数据永远是二维
#model.predit(x) x即特征数据永远是二维
#关键点:易错点应因为sklearn里面的线性回归,会对数据自己加偏置项,所以不要把偏置项传进去
LR.fit(XData,y_data)
print(LR.coef_)#打印回归方程的参数
print(LR.intercept_)#打印截距的theta0
print(LR.score(XData,y_data))#对预测结果计算出的决定系数R∧2;拟合优度越大,说明xduiy的解释程度越大

在这里插入图片描述

ws=np.zeros((2,1))
ws[0]=LR.intercept_
ws[1]=LR.coef_
print(ws)

yHat=np.mat(x_data)*ws#记得转为矩阵;矩阵乘以数组,按照矩阵相乘
plot()
import matplotlib.pyplot as plt
plt.plot(x_data[:,1],yHat,'r')
plt.show()

在这里插入图片描述

#案例2:波士顿房价
import mglearn
from sklearn.linear_model import LinearRegression#线性回归算法
from sklearn.model_selection import train_test_split#数据集划分
X,y=mglearn.datasets.load_extended_boston()
X_train,X_test,y_train,y_test=train_test_split(X,y)
lr=LinearRegression().fit(X_train,y_train)
print("数据集的分值:",lr.score(X_train,y_train))#训练集的分值
print("数据集的分值:",lr.score(X_test,y_test))#测试集的分值
#过拟合:训练集上表现得好,但是测试集表现得不好

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

侬本多情。

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值