从爬虫到用scikit-learn构建机器学习多元线性回归模型

《从爬虫到用scikit-learn构建机器学习多元线性回归模型》

一:前言

这是一个线性回归的学习笔记,数据源是我爱我家的北京朝阳区的房屋价格及其相关信息,有室、厅、大小、朝向、楼层层数、装修程度、单价、总价。然后利用scikit-learn 构建一个简单的多元线性回归模型并预测。介绍相关的sklearn函数使用和参数意义。
目的:练习pandas、sklearn等相关模块函数使用

二:运行环境

  • Python 3.6
  • jupyter notebook
  • scikit-learn 0.19.1
  • pandas 0.20.3

三:数据抓取

我爱我家-朝阳区 https://bj.5i5j.com/ershoufang/chaoyangqu/

《从爬虫到用scikit-learn构建机器学习多元线性回归模型》

抓取思路:查看当前地区房屋页面数量,然后循环抓取当页数据,本次抓取的数据有rooms halls size direction unit_price price,其实如果把距离地铁的距离加进去也是一个不错的特征,但是考虑到模型简单一点,就暂时没有加,后面如果练习的话可以考虑放进去训练。
下面是抓取部分的代码,把页面数填进去,数据量不大所以就循环抓取即可。
具体代码见:https://github.com/rieuse/Machine_Learning/blob/master/House_Regression

def get_house_data():
    for num in range(1, 299):
        url = f'https://bj.5i5j.com/ershoufang/chaoyangqu/n{num}/'
        print(url)
        s = requests.session()
        html = s.get(url, headers=headers).text
        content = etree.HTML(html).xpath('//*[@class="listCon"]')
        for item in content:
            desc = item.xpath('./div[1]/p[1]/text()')[0].replace(' ','')
            price = item.xpath('./div[1]/div[1]/p[1]/strong/text()')[0]
            unit_price = item.xpath('./div[1]/div[1]/p[2]//text()')[0][2:-4]
            rooms = desc[:1]
            halls = desc[2:3]
            size = re.search(r'(?<=·).+(?=平米·)', desc)[0]
            direction = re.search(r'(?<=平米·).{1,2}(?=·)', desc)
            if not direction:
                direction = ''
            else:
                direction = direction[0]
            height = re.search(r'(?<=·).{1}(?=楼层)', desc)[0]
            if '装' in desc:
                decoration = desc[-2:-1]
            else:
                decoration = ''
            data = {
                'rooms': rooms,
                'halls': halls,
                'size': size,
                'direction': direction,
                'height': height,
                'decoration': decoration,
                'unit_price': unit_price,
                'price': price
            }
            print(data)

四:利用sklearn 构建多元线性回归模型

(1)

下面的代码建议在jupyter notebook 上运行,这样对数据可视化会很方便。

import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
%matplotlib inline
row_df = pd.read_csv('house_price.csv')
df = row_df[row_df.iloc[:,1] !='多']
# 去除数据中房间数目是‘多’ 的部分
data_X = df[['rooms','halls','size','unit_price']]
data_y = df.price
# 选取指定的特征
X_train, X_test, y_train, y_test = train_test_split(data_X, data_y, test_size=0.3)
# 利用 train_test_split 把数据集分割成训练集和测试集
model = LinearRegression(fit_intercept=True, normalize=False, copy_X=True, n_jobs=1)
model.fit(X_train,y_train)
LinearRegression(copy_X=True, fit_intercept=True, n_jobs=1, normalize=False)
model.score(X_test,y_test)
# score: 0.94163368657645685
print(model.coef_)
print(model.intercept_)
# model.coef_输出线性方程的参数,model.intercept_输出线性方程的节距

上面选取了’rooms’,’halls’,’size’,’unit_price’,这几个特征进去训练,最后的预测效果评分达到94.16% 如果去掉单价这个特征来训练,预测效果评分就会下降很多。

data_X = df[['rooms','halls','size']]
data_y = df.price
X_train, X_test, y_train, y_test = train_test_split(data_X, data_y, test_size=0.3)
model = LinearRegression(fit_intercept=True, normalize=True, copy_X=True, n_jobs=1)
model.fit(X_train,y_train)    # 训练模型
model.score(X_test,y_test)    # 获取模型效果评分
model.predict(np.array([3,1,90]).reshape(1, -1)) 
# out:array([ 648.07270425])

根据训练好的模型,我们就可以看看北京朝阳区的三室一厅,90平米这样的房子大致是多少钱了,输出结果是648.07万元。

(2) LinearRegression() 参数
参数类型默认值说明
fit_intercept布尔型true是否对训练数据进行中心化。如果该变量为false,则表明输入的数据已经进行了中心化,在下面的过程里不进行中心化处理;否则,对输入的训练数据进行中心化处理
normalize布尔型false是否对数据进行标准化处理
copy_X布尔型true是否对X复制,如果选择false,则直接对原数据进行覆盖。(即经过中心化,标准化后,是否把新数据覆盖到原数据上)
n_jobs整型1计算时设置的任务个数(number of jobs)。如果选择-1则代表使用所有的CPU。对于 n_targets>1 且足够大规模的问题有加速作用。
(3) LinearRegression() 返回值:
名称返回值说明
coef_数组型变量, 形状为(n_features,)或(n_targets, n_features)说明:对于线性回归问题计算得到的feature的系数。如果输入的是多目标问题,则返回一个二维数组(n_targets, n_features);如果是单目标问题,返回一个一维数组 (n_features,)。
intercept_数组型变量线性模型中的独立项。例如这里的b: y = ax + b

五:总结

该项目代码以及数据源全部存放于 github.com/rieuse/Machine_Learning
会了爬虫就可以自己抓取喜欢的数据拿来分析数据和跑机器学习,非常方便。这次利用自己抓取的数据,练习了sklearn的线性回归模型。也同时看到了北京房价的恐怖,买房还需努力呀。抓取的数据特征有很多,利用更多的特征训练的模型效果就越好,预测就会更准。以后我在尝试一下利用这些特征最大化预测效果,或者使用其他的模型或者来训练本次的数据。

    原文作者:rieuse
    原文地址: https://www.jianshu.com/p/8a863fd28ca6#comments
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞