【机器学习】线性回归预测

打印 上一主题 下一主题

主题 844|帖子 844|积分 2532

前言

回归分析就是用于预测输入变量(自变量)和输出变量(因变量)之间的关系,特别当输入的值发生变化时,输出变量值也发生改变!回归简单来说就是对数据进行拟合。线性回归就是通过线性的函数对数据进行拟合。机器学习并不能实现预言,只能实现简单的预测。我们这次对房价关于其他因素的关系。
波士顿房价预测

下载相关数据集


  • 数据集是506行14列的波士顿房价数据集,数据集是开源的。
  1. wget.download(url='https://archive.ics.uci.edu/ml/machine-learning-databases/housing/housing.data',out= 'housing.data')
  2. wget.download(url='https://archive.ics.uci.edu/ml/machine-learning-databases/housing/housing.names',out='housing.names')
  3. wget.download(url='https://archive.ics.uci.edu/ml/machine-learning-databases/housing/Index',out='Index')
复制代码
对数据集进行处理
  1. feature_names = ['CRIM','ZN','INDUS','CHAS','NOX','RM','AGE','DIS','RAD','TAX','PTRATIO','B','LSTAT','MEDV']
  2. feature_num = len(feature_names)
  3. print(feature_num)
  4. # 把7084 变为506*14
  5. housing_data = housing_data.reshape(housing_data.shape[0]//feature_num,feature_num)
  6. print(housing_data.shape[0])
  7. # 打印第一行数据
  8. print(housing_data[:1])
  9. ## 归一化
  10. feature_max = housing_data.max(axis=0)
  11. feature_min = housing_data.min(axis=0)
  12. feature_avg = housing_data.sum(axis=0)/housing_data.shape[0]
复制代码
模型定义
  1. ## 实例化模型
  2. def Model():
  3.     model = linear_model.LinearRegression()
  4.     return model
  5. # 拟合模型
  6. def train(model,x,y):
  7.     model.fit(x,y)
复制代码
可视化模型效果
  1. def draw_infer_result(groud_truths,infer_results):
  2.     title = 'Boston'
  3.     plt.title(title,fontsize=24)
  4.     x = np.arange(1,40)
  5.     y = x
  6.     plt.plot(x,y)
  7.     plt.xlabel('groud_truth')
  8.     plt.ylabel('infer_results')
  9.     plt.scatter(groud_truths,infer_results,edgecolors='green',label='training cost')
  10.     plt.grid()
  11.     plt.show()
复制代码
整体代码
  1. ## 基于线性回归实现房价预测## 拟合函数模型## 梯度下降方法## 开源房价策略数据集import wgetimport numpy as npimport osimport matplotlibimport matplotlib.pyplot as pltimport pandas as pdfrom sklearn import  linear_model## 下载之后注释掉'''wget.download(url='https://archive.ics.uci.edu/ml/machine-learning-databases/housing/housing.data',out= 'housing.data')
  2. wget.download(url='https://archive.ics.uci.edu/ml/machine-learning-databases/housing/housing.names',out='housing.names')
  3. wget.download(url='https://archive.ics.uci.edu/ml/machine-learning-databases/housing/Index',out='Index')''''''    1. CRIM      per capita crime rate by town    2. ZN        proportion of residential land zoned for lots over                  25,000 sq.ft.    3. INDUS     proportion of non-retail business acres per town    4. CHAS      Charles River dummy variable (= 1 if tract bounds                  river; 0 otherwise)    5. NOX       nitric oxides concentration (parts per 10 million)    6. RM        average number of rooms per dwelling    7. AGE       proportion of owner-occupied units built prior to 1940    8. DIS       weighted distances to five Boston employment centres    9. RAD       index of accessibility to radial highways    10. TAX      full-value property-tax rate per $10,000    11. PTRATIO  pupil-teacher ratio by town    12. B        1000(Bk - 0.63)^2 where Bk is the proportion of blacks                  by town    13. LSTAT    % lower status of the population    14. MEDV     Median value of owner-occupied homes in $1000's'''## 数据加载datafile = './housing.data'housing_data = np.fromfile(datafile,sep=' ')print(housing_data.shape)feature_names = ['CRIM','ZN','INDUS','CHAS','NOX','RM','AGE','DIS','RAD','TAX','PTRATIO','B','LSTAT','MEDV']
  4. feature_num = len(feature_names)
  5. print(feature_num)
  6. # 把7084 变为506*14
  7. housing_data = housing_data.reshape(housing_data.shape[0]//feature_num,feature_num)
  8. print(housing_data.shape[0])
  9. # 打印第一行数据
  10. print(housing_data[:1])
  11. ## 归一化
  12. feature_max = housing_data.max(axis=0)
  13. feature_min = housing_data.min(axis=0)
  14. feature_avg = housing_data.sum(axis=0)/housing_data.shape[0]def feature_norm(input):    f_size = input.shape    output_features = np.zeros(f_size,np.float32)    for batch_id in range(f_size[0]):        for index in range(13):            output_features[batch_id][index] = (input[batch_id][index]-feature_avg[index])/(feature_max[index]-feature_min[index])    return output_featureshousing_features = feature_norm(housing_data[:,:13])housing_data = np.c_[housing_features,housing_data[:,-1]].astype(np.float32)## 划分数据集  8:2ratio =0.8offset = int(housing_data.shape[0]*ratio)train_data = housing_data[:offset]test_data = housing_data[offset:]print(train_data[:2])## 模型配置## 线性回归## 实例化模型
  15. def Model():
  16.     model = linear_model.LinearRegression()
  17.     return model
  18. # 拟合模型
  19. def train(model,x,y):
  20.     model.fit(x,y)## 模型训练X, y = train_data[:,:13], train_data[:,-1:]model = Model()train(model,X,y)x_test, y_test = test_data[:,:13], test_data[:,-1:]prefict = model.predict(x_test)## 模型评估infer_results = []groud_truths = []def draw_infer_result(groud_truths,infer_results):
  21.     title = 'Boston'
  22.     plt.title(title,fontsize=24)
  23.     x = np.arange(1,40)
  24.     y = x
  25.     plt.plot(x,y)
  26.     plt.xlabel('groud_truth')
  27.     plt.ylabel('infer_results')
  28.     plt.scatter(groud_truths,infer_results,edgecolors='green',label='training cost')
  29.     plt.grid()
  30.     plt.show()draw_infer_result(y_test,prefict)
复制代码
效果展示


总结

线性回归预测还是比较简单的,可以简单理解为函数拟合,数据集是使用的开源的波士顿房价的数据集,算法也是打包好的包,方便我们引用。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

前进之路

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表