赞
踩
数据集:http://lib.stat.cmu.edu/datasets/boston
访问这个网页可以看到里面有对每个数据集的介绍,特征(506行,13列),最后一列是房价
1:数据集导入,导包
- from sklearn.datasets import load_boston
- from sklearn.linear_model import LinearRegression # 导入线性回归类
- from sklearn.model_selection import train_test_split # 数据集的划分
在python这边导的包数据是特征和结果分开的
2:获取数据
- #获取数据
- boston = load_boston()
- print(boston)
- # 目标值 特征值
- print(boston.data.shape) # 特征(506行,13列)
- x,y = boston.data,boston.target #分别获取特征值和目标值
3:对数据集进行划分
- # 3. 数据集划分 ( 训练集 + 测试集)
- x_train,x_test,y_train,y_test = train_test_split(x,y,test_size= 0.2,random_state=22) # random_state 随机种子
4:模型建立,评估
- # 4. 模型建立
- lr = LinearRegression()
- # 用回归对象训练模型 --- y = wx+b ---》 得到w和b的值
- lr.fit(x_train,y_train)
- print("权重w:\n",lr.coef_)
- print('截距b:\n',lr.intercept_)
- # 5. 预测
- y_pre = lr.predict(x_test)
- print("真实值:\n",y_test)
- print("预测值:\n",y_pre)
-
- # 6.评估(数据预测的相关性)
- print("测试集评估:\n",lr.score(x_test,y_test))
运行结果:
我们可以使用上一篇文章的绘图进行画图,评估出来的测试集结果为 0.7657465943591131
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。