机器学习-线性回归2-python代码-房价预测-一维自变量

项目源地址
现有房屋面积对应价格的一组数据。尝试使用线性回归方法,拟合出一条直线。并且完成对指定的新样本点,给出预测值,并画图。

step0.python版本以及包依赖

本文使用的python版本为Python 3.7.2
所用到需要额外安装的包有

pandas
numpy
sklearn
matplotlib

相关包下载方式汇总

导入方法:

from io import StringIO
import pandas as pd
from sklearn import linear_model
import matplotlib.pyplot as plt
import numpy as np

step1.数据输入

  1. 数据内容如下:
房屋面积(square_feet) 价格(price)
150 6450
200 7450
250 8450
300 9450
350 11450
400 15450
600 18450
  1. 为了方便实现,本文改成StringIO方法输入

    def get_data(file_name):
        """
        获取csv数据,给出自变量x,因变量y的list
        :param file_name:
        :return:
        """
        data = pd.read_csv(file_name)
        x, y = [], []
        for i, j in zip(data['square_feet'], data['price']):
            x.append([float(i)])
            y.append(float(j))
        return x, y
    
    
    input_data = StringIO(
            'square_feet,price\n150,6450\n200,7450\n250,8450\n300,9450\n350,11450\n400,15450\n600,18450\n')
    x_train, y_train = get_data(input_data)
    

step2.线性回归模型建立

  1. 使用sklearn中的linear_model方法,先创建一个线性回归对象

    regr = linear_model.LinearRegression()
    
  2. 使用对象中的fit方法,对样本进行训练

    regr.fit(x_train, y_train)
    
  3. 完成训练后,线性回归对象可以输出训练结果的截距和斜率:

    print("截距:" + str(regr.intercept_))
    print("斜率:" + str(regr.coef_))
    

    输出结果为:

    截距:1771.8085106382969
    斜率:[28.77659574]
    

step3.预测任意给定新的数据(房屋面积值)

  • 假设给定新房屋面积为500,我们通过线性回归对象的predict函数和函数表达式 y = a x + b y=ax+b 两种方式分别去验证

    test = [500]
    print(regr.predict(np.array(test).reshape(1, -1)))
    print(500 * regr.coef_ + regr.intercept_)
    
  • 输出结果为:

    [16160.10638298]
    [16160.10638298]
    
  • 可以发现两个结果一致。今后使用模型预测时可直接使用predict方法

step4.画图

  • 训练集使用蓝点标记,回归函数使用红色标记,预测数值(500)采用黑色。
    plt.scatter(x_train, y_train, color='blue')
    plt.scatter(test, regr.predict(np.array(test).reshape(1, -1)), color='black')
    plt.plot(x_train, regr.predict(x_train), color='red', linewidth=4)
    plt.show()
    

在这里插入图片描述

step5.完整代码

  • 新建文件‘predict_house_price.py’,将下述代码粘贴保存后,terminal(终端或cmd)切到文件目录即可运行,运行命令:

    $ python predict_house_price.py
    
  • 完整代码:

    #!/usr/local/bin/python3
    
    """
    @File    : predict_house_price.py
    @Author  : togetlife
    @Time    : 2019-03-19
    """
    
    from io import StringIO
    import pandas as pd
    from sklearn import linear_model
    import matplotlib.pyplot as plt
    import numpy as np
    
    
    def get_data(file_name):
        """
        获取csv数据,给出自变量x,因变量y的list
        :param file_name:
        :return:
        """
        data = pd.read_csv(file_name)
        x, y = [], []
        for i, j in zip(data['square_feet'], data['price']):
            x.append([float(i)])
            y.append(float(j))
        return x, y
    
    
    def main():
        # 输入文本,为了方便重现,直接将csv文件改为通过StringIO方法输入
        input_data = StringIO(
            'square_feet,price\n150,6450\n200,7450\n250,8450\n300,9450\n350,11450\n400,15450\n600,18450\n')
    
        # 划分训练集自变量与因变量
        x_train, y_train = get_data(input_data)
    
        # 创建对象,训练数据,输出回归函数参数
        regr = linear_model.LinearRegression()
        regr.fit(x_train, y_train)
        print("截距:" + str(regr.intercept_))
        print("斜率:" + str(regr.coef_))
    
        # 两种方式测试结果
        test = [500]
        print(regr.predict(np.array(test).reshape(1, -1)))
        print(500 * regr.coef_ + regr.intercept_)
    
        # 画图,包括训练集,回归函数和测试结果
        plt.scatter(x_train, y_train, color='blue')
        plt.scatter(test, regr.predict(np.array(test).reshape(1, -1)), color='black')
        plt.plot(x_train, regr.predict(x_train), color='red', linewidth=4)
        plt.show()
    
    
    if __name__ == '__main__':
        main()
    
    
  • 如有不妥,请指示正,谢谢阅读!
    作者:togetlife

猜你喜欢

转载自blog.csdn.net/togetlife/article/details/88656479