多元线性回归

  • 之前复现了单特征预测幸福指数的线性回归模型,
  • 现在使用多向量特征回归看看是否会减小误差

导库与查看数据

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import plotly
import plotly.graph_objs as goplotly.offline.init_notebook_mode()from homemade.linear_regression import LinearRegression

data = pd.read_csv('F:/MLdata/data/world-happiness-report-2017.csv')data.head(10)

查看变量与预测变量之间的分布关系

histohrams = data.hist(grid=False, figsize=(10, 10))

拆分训练集测试集

input_param_name_1 = 'Economy..GDP.per.Capita.'
input_param_name_2 = 'Freedom'
output_param_name = 'Happiness.Score'# Split training set input and output.
x_train = train_data[[input_param_name_1, input_param_name_2]].values
y_train = train_data[[output_param_name]].values# Split test set input and output.
x_test = test_data[[input_param_name_1, input_param_name_2]].values
y_test = test_data[[output_param_name]].values
  • **在这里和之前发生了变化,输入变量变成了多维向量以GDP和FreeDom为例,绘制三维分布图
plot_training_trace = go.Scatter3d(x=x_train[:, 0].flatten(),y=x_train[:, 1].flatten(),z=y_train.flatten(),name='Training Set',mode='markers',marker={'size': 10,'opacity': 1,'line': {'color': 'rgb(255, 255, 255)','width': 1},}
)plot_test_trace = go.Scatter3d(x=x_test[:, 0].flatten(),y=x_test[:, 1].flatten(),z=y_test.flatten(),name='Test Set',mode='markers',marker={'size': 10,'opacity': 1,'line': {'color': 'rgb(255, 255, 255)','width': 1},}
)plot_layout = go.Layout(title='Date Sets',scene={'xaxis': {'title': input_param_name_1},'yaxis': {'title': input_param_name_2},'zaxis': {'title': output_param_name} },margin={'l': 0, 'r': 0, 'b': 0, 't': 0}
)plot_data = [plot_training_trace, plot_test_trace]plot_figure = go.Figure(data=plot_data, layout=plot_layout)plotly.offline.iplot(plot_figure)

绘制结果如下图所示,由于图片格式的限制,这里就只截图了,可以运行以后对每个点进行分析

模型训练

num_iterations = 500
regularization_param = 0
learning_rate = 0.01
polynomial_degree = 0
sinusoid_degree = 0   multipliers of additional features.# Init linear regression instance.
linear_regression = LinearRegression(x_train, y_train, polynomial_degree, sinusoid_degree)# Train linear regression.
(theta, cost_history) = linear_regression.train(learning_rate,regularization_param,num_iterations
)print('Initial cost: {:.2f}'.format(cost_history[0]))
print('Optimized cost: {:.2f}'.format(cost_history[-1]))theta_table = pd.DataFrame({'Model Parameters': theta.flatten()})
theta_table.head()

结果分析

梯度下降图

plt.plot(range(num_iterations), cost_history)
plt.xlabel('Iterations')
plt.ylabel('Cost')
plt.title('Gradient Descent Progress')
plt.show()


绘制预测结果平面,可以很容易理解多元线性回归的原理,和单变量是类似的


predictions_num = 10x_min = x_train[:, 0].min();
x_max = x_train[:, 0].max();y_min = x_train[:, 1].min();
y_max = x_train[:, 1].max();x_axis = np.linspace(x_min, x_max, predictions_num)
y_axis = np.linspace(y_min, y_max, predictions_num)x_predictions = np.zeros((predictions_num * predictions_num, 1))
y_predictions = np.zeros((predictions_num * predictions_num, 1))x_y_index = 0
for x_index, x_value in enumerate(x_axis):for y_index, y_value in enumerate(y_axis):x_predictions[x_y_index] = x_valuey_predictions[x_y_index] = y_valuex_y_index += 1z_predictions = linear_regression.predict(np.hstack((x_predictions, y_predictions)))plot_predictions_trace = go.Scatter3d(x=x_predictions.flatten(),y=y_predictions.flatten(),z=z_predictions.flatten(),name='Prediction Plane',mode='markers',marker={'size': 1,},opacity=0.8,surfaceaxis=2,
)plot_data = [plot_training_trace, plot_test_trace, plot_predictions_trace]
plot_figure = go.Figure(data=plot_data, layout=plot_layout)
plotly.offline.iplot(plot_figure)


可以很明显的看出预测的平面分布
将测试集和训练集进行对比,看看预测损失有多少

test_predictions = linear_regression.predict(x_test)test_predictions_table = pd.DataFrame({'Economy GDP per Capita': x_test[:, 0].flatten(),'Freedom': x_test[:, 1].flatten(),'Test Happiness Score': y_test.flatten(),'Predicted Happiness Score': test_predictions.flatten(),'Prediction Diff': (y_test - test_predictions).flatten()
})test_predictions_table.head(10)


相比单变量回归,明显变得更加优良了

多元线性回归预测国家幸福指数相关推荐

  1. 多元线性回归预测房价

    文章目录 一.利用Jupyter实现 1.1 基础包与数据导入 1.3 变量探索 1.3 多元线性回归建模 1.4 模型优化 二.用Excel重做上面的多元线性回归,求解回归方程 三.用机器学习库Sk ...

  2. MATLAB实现多元线性回归预测

    一.简单的多元线性回归: data.txt 1,230.1,37.8,69.2,22.1 2,44.5,39.3,45.1,10.4 3,17.2,45.9,69.3,9.3 4,151.5,41.3 ...

  3. Python 实现多元线性回归预测

    一.二元输入特征线性回归 测试数据为:ex1data2.txt 2104,3,399900 1600,3,329900 2400,3,369000 1416,2,232000 3000,4,53990 ...

  4. [Step By Step]SAP HANA PAL多元线性回归预测分析Linear Regression实例FORECASTWITHLR(预测)...

    一元线性回归算法说明: http://www.cnblogs.com/omygod/archive/2013/05/12/3073783.html 多元线性回归算法说明: http://www.cnb ...

  5. 统计建模-多元线性回归预测房价

    简单聊聊统计建模中,使用多元线性回归模型来预测房价. 文章目录 变量描述: (1)读取数据 (2)单变量描述 (3)自变量对因变量的影响分析 (4)检验变量重要性 (5)筛选出重要变量建模 (6)模型 ...

  6. 使用MATLAB进行多元线性回归预测

    在回归分析中,如果有两个或两个以上的自变量,就称为多元回归.事实上,一种现象常常是与多个因素相联系的,由多个自变量的最优组合共同来预测或估计因变量,比只用一个自变量进行预测或估计更有效,更符合实际.因 ...

  7. 分析哪个国家在总体幸福指数上排名最高,中国居然80名以外?

    本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理. 以下文章来源于CDA数据分析师 ,作者CDA数据分析师 前言 <世界幸福指 ...

  8. GDP越高就越幸福吗?用Python分析《世界幸福指数报告》后我们发现…

    公众号后台回复"图书",了解更多号主新书内容 作者:CDA数据分析师 来源:CDA数据分析师  CDA数据分析师 出品   作者:真达.Mika 数据:真达   [导读] 今天教大 ...

  9. 用Python分析幸福指数

    作者:huny https://www.cnblogs.com/huny/p/14146719.html 世界上最幸福的国家有哪些?个人幸福和哪些指标相关?你幸福吗?如果不知道,那就进来看看这篇关于幸 ...

最新文章

  1. 对计算机技术的发展方向研究,网络技术发展对计算机技术的影响
  2. java有画图的库吗_Java画图
  3. 逆向工程核心原理学习笔记(八):小端序标记法1
  4. 九州云腾双因素认证系统_阿里云全资收购九州云腾,加速构建云上零信任体系...
  5. 多个cpu显卡组装的服务器,小白折腾玩玩服务器配置,洋垃圾配件组装一次点亮...
  6. svn导出项目到myeclipse,运行报ClassNotFoundException
  7. Facebook 开源代码分析工具 —— Mariana Trench
  8. HTTP 1 1与HTTP 1 0的比较
  9. 程序设计实践之车辆信息管理系统
  10. kubernetes 创建pod /merged/dev/shm: invalid argument
  11. java中使用jxls导出excel,excel单元格换行,多sheet页导出
  12. java二进制保存图片_Java中如何把图片转换成二进制流
  13. 魅族设置语音录音服务器,魅族手机留言录音功能使用方法介绍
  14. UPC 2021个人训练赛第10场
  15. Qt4.8.5——QWSServer
  16. CTFshow web3 菜鸡刷题记录
  17. 在线教育,异军突起,有一种华丽转身,叫做.NET在线讲师!(全职/兼职皆可)...
  18. 串口通信数据位长度对传输数据的影响
  19. 顶峰网谈百度关键词排名基本规则
  20. C语言 火车票信息管理系统

热门文章

  1. MTK CVE-2020-0069 使用方式,以及Android端测试工具
  2. CSS background-size :contain与cover区别
  3. linux 地址寄存器地址,petalinux的app中直接访问AXI UART等寄存器地址
  4. 工作了,该怎么办呀?
  5. win xp 读写 mac 的时间机器移动硬盘
  6. 美团滴滴掐架告一段落,乐语却在新零售“跨界”上立了个旗帜
  7. 【U3D】人物触发物体显示界面(游戏开始/游戏结束/碰撞金币等)
  8. hive金额怎么转换千位分隔符_sql 数据转换 千位分隔符
  9. 使用Spock框架进行单元测试
  10. 程序员的台式机组建之路