机器学习作业之波士顿房价(boston)数据分析与绘图(注释我都写了这么多,我不信你还看不懂?)

一、前言

看我前几篇文章的小伙伴都知道,最近一直在学习机器学习相关内容

学校里也开了这门课,有个很经典的作业就是利用机器学习知识预测波士顿房价

网上也有非常多相关介绍,但是一个个函数及参数我是真的不明白啥意思

索性干脆就自己学完写一个初学者也能很好上手的代码

不过还是需要对读者提些要求:

1、需要简单了解python基础知识
2、会简单使用pycharm或者jupyter notebook
3、知道添加三方头文件的方法
4、简单知道线性回归是干嘛的

第三条不太清楚的可以看我这篇文章

话不多说直接开始

二、简单介绍头文件

from sklearn.datasets import load_boston
from sklearn.model_selection import learning_curve
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import ShuffleSplit
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

1、sklearn头文件

一般python编辑器是不自带这个,需要自己下载

管理员身份运行cmd

pip install sklearn

提示安装成功就行

意外

题主执行pip指令是老是报错,以为是网速的问题

换用conda进行

结果还是非法报错

ValueError: check_hostname requires server_hostname

后来才发现是网络代理开着

关上就行

2、其他头文件

numpy和pandas这两个用于分析数据的头文件基本上都是不不分家

matplotlib头文件就是用来绘图的

也用pip基本上就行

pip install numpy
pip install pands
pip install matplotlib

如有报错直接百度

有参考我这篇文章使用手动和半自动方法的话一定要注意你python版本号和电脑是多少位的

三、题目理解

1、题目的简单介绍

在这里插入图片描述
想参考全部的数据可以访问这个网站

简单的数据展示:
在这里插入图片描述

2、属性标签

共有13个属性标签(feature)和1个预测目标(target)

CRIM per capita crime rate by town
ZN proportion of residential land zoned for lots over 25,000 sq.ft.
INDUS proportion of non-retail business acres per town
CHAS Charles River dummy variable (= 1 if tract bounds river; 0 otherwise)
NOX nitric oxides concentration (parts per 10 million)
RM average number of rooms per dwelling
AGE proportion of owner-occupied units built prior to 1940
DIS weighted distances to five Boston employment centres
RAD index of accessibility to radial highways
TAX full-value property-tax rate per $10,000
PTRATIO pupil-teacher ratio by town
B 1000(Bk - 0.63)^2 where Bk is the proportion of blacks by town
LSTAT % lower status of the population
MEDV Median value of owner-occupied homes in $1000’s

代码中我任选三个属性特征(feature)来预测房价(target)

当然理论上13个特征全选预测出来的房价会更准确了

但先把简单的都弄会了再把其他特征都加进去

3、降维比喻

假如我们在宠物店相中了一条狗,想猜猜他值多少钱,这个时候会找一些因素来判断狗狗是贵还是划算还是便宜,比如我列举了些因素:

颜色:可能黑色和黄色比较贵,杂色便宜
疫苗:打了疫苗会比没打疫苗贵,疫苗分为便宜和贵
听话与否:接受过训练比没接收过可能要贵
性格:活泼的更讨人喜欢
年龄:年龄小的更容易被顾客接受
血统:纯血或者父母都是品种纯净比混血更贵

如果只看颜色的话,大概能预测出一个价位

如果参考颜色和血统,又会得出一个价位

以此类推,如果考虑所有条件,那得出的价位更接近真实价格

这些因素就对应这波士顿房价的13个特征属性(feature)

狗狗的价位也对应着波士顿的房价(target)

四、代码

1、代码及注释

from sklearn.datasets import load_boston
from sklearn.model_selection import learning_curve
from sklearn.linear_model import LinearRegression
import pandas as pd
import numpy as np
from sklearn.model_selection import ShuffleSplit
import matplotlib.pyplot as plt


boston = load_boston()                      # 加载boston数据

X = boston.data                             # data为数据中的13个特征数据的所有值
Y = boston.target                           # target为数据中的想要预测的目标数据
# print(X.shape)                              # 训练向量,包括样本数量和特征的数量两个参数
#print(boston.keys())                        # boston的属性。输出结果dict_keys(['data', 'target', 'feature_names', 'DESCR', 'filename', 'data_module'])

df = pd.DataFrame(boston.data,columns=boston.feature_names)        # 以feature_names作为列名,把data填充到矩阵中,得到boston的数据
df['target'] = pd.Series(boston.target)     # 把target内容以列的形式保存在df的target中
print(df.head())                            # 只读取df中前五行数据,默认为五行

features = df[['CRIM','RM','LSTAT']]        # 选取三个特征
print(features.describe())                  # 显示数量统计(count),均值(mean),标准差(std),最小值(min),四分位数(25%,50%,75%),最大值(max)

target = df['target']                       # 取出target的数值

split_num = int(len(features)*0.7)          # 切割数据集,train占0.7,test占0.3

X_train = features[:split_num]              # X_train取前70%部分的数据
Y_train = target[:split_num]                # Y_train取前70%部分的数据


X_test = features[split_num:]               # X_test取后30%部分的数据
Y_test = target[split_num:]                 # Y_test取后30%部分的数据

model = LinearRegression()                  # 使用线性回归
model.fit(X_train,Y_train)                  # 构建模型,调用fit训练
print('权重:',model.coef_,                   # 打印系数θ1,θ2,θ3和截距θ0
      '\n',
      '偏置:',model.intercept_)              # 拟合直线f = θ1*x1+θ2*x2+θ3*x3+θ0
                                            # x1,x2,x3分别对应特征'CRIM','RM','LSTAT'
                                            # model.coef_输出模型权重θ1,θ2,θ3
                                            # model.intercept_输出模型的偏置θ0征'CRIM','RM','LSTAT'
preds = model.predict(X_test)               # 用测试集测试得到预测结果
print(preds)                                # 输出预测值


def mae_value(y_true,y_pred):               # 计算MAE,传递参数分别为真实值和预测值
    n = len(y_true)
    mae = sum(np.abs(y_true - y_pred)) / n
    return mae

def mse_value(y_true,y_pred):               # 计算MSE
    n = len(y_true)
    mse = sum(np.square(y_true - y_pred)) / n
    return mse

mae = mae_value(Y_test.values,preds)        # values返回列表中所有的值
mse = mse_value(Y_test.values,preds)
print("MAE:",mae)
print("MSE:",mse)

def plot_learning_curve(plt,estimator,title,X,Y,ylim = None,cv = None,
                        n_jobs=1,train_sizes=np.linspace(.1,1.0,5)):	# 封装学习曲线函数
                            #estimator为使用的分类器。
                            #X为传入的矩阵(feature)
                            #Y传入的特征属性(target)
                            #ylim定义y轴取值范围
                            #cv默认使用3折交叉验证
                            #n_jobs并行运行的作业数
                            #train_sizes训练样本的相对或绝对的数字
    plt.title(title)                                    # plt.title设置图像标题
    if ylim is not None:
        plt.ylime(*ylim)
    plt.xlabel("Training example")                      # 设置x和y轴的标题
    plt.ylabel("Score")                                 # 设置x和y轴的标题
    train_sizes,train_scores,test_scores = learning_curve(estimator, X, Y, cv = cv, n_jobs = n_jobs,
                                                            train_sizes = train_sizes)
    train_scores_mean = np.mean(train_scores, axis=1)   # 平均值
    train_scores_std = np.std(train_scores, axis=1)     # 标准差
    test_scores_mean = np.mean(test_scores, axis=1)     # 平均值
    test_scores_std = np.std(test_scores, axis=1)       # 标准差
    plt.grid()                                          # 生成网格线
    plt.fill_between(train_sizes, train_scores_mean - train_scores_std, train_scores_mean + train_scores_std, alpha=0.1,
                     color="r")                         # 曲线下面覆盖成红色
    plt.fill_between(train_sizes, test_scores_mean - test_scores_std, test_scores_mean + test_scores_std, alpha=0.1,
                     color="g")                         # 曲线下面覆盖成绿色
    plt.plot(train_sizes, train_scores_mean, 'o--', color="r", label="Training score")          # 显示红色曲线
    plt.plot(train_sizes, test_scores_mean, 'o-', color="g", label="Cross-validation score")    # 显示绿色曲线
    plt.show()                                          # 在pycharm里取消注释
    plt.legend(loc="best")                              # 图例位置放在合适(best)位置
    return plt

cv = ShuffleSplit(n_splits=10,test_size=0.2,random_state=0)     # 交叉验证的参数
plt.figure(figsize=(10,6))                              # 指定figure的高和宽
plot_learning_curve(plt,model,"Learn Curve fore LinearRegression",features,target,ylim=None,cv=cv)
                                                        # 画出学习曲线

2、代码缺点

因为着急写出来,所以只封装了MAE、MSE与学习曲线函数

所以不用大家太多的跳转着读代码

基本上从上往下读就ok

等有机会在更新下封装起来的全部代码

五、运行结果

直接上图吧
在这里插入图片描述
虚线:针对训练数据集拟合的准确性

实线:针对交叉验证数据集拟合的准确性

如果依然有不懂的同学可以直接评论或私我

完事!!!

  • 6
    点赞
  • 99
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值