【机器学习实战】1_GDP预测案例代码《Hands-On Machine Learning with Scikit_Learn &TensorFlow》

# -*- coding: utf-8 -*-
"""
Created on Fri Dec 14 13:45:58 2018

@author: Administrator
"""

#import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import sklearn
#from sklearn.linear_model import LinearRegression 

import os
datapath = os.path.join('datasets','lifesat','')

# 加载数据
file_path = r"D:\chengmi_吴限\python\handson-ml-master\handson-ml-master\datasets\lifesat\\"
file0 = open(file_path+"oecd_bli_2015.csv",'r', encoding='UTF-8')
file1 = open(file_path+"gdp_per_capita.csv",'r', encoding='latin1')
oecd_bli = pd.read_csv(file0,thousands = ',')
gdp_per_capita = pd.read_csv(file1,thousands = ',',delimiter = '\t',encoding = 'latin1',na_values = 'n/a')

'''
也许大多数人都有在Excel中使用数据透视表的经历,其实Pandas也提供了一个类似的功能,名为 pivot_table。
pandas的官方api上查到pivot()有三个参数,第一个index是重塑的新表的索引名称是什么,第二个columns是重塑的新表的列名称是什么,
一般来说就是被统计列的分组(每个分组是新的一列),第三个values就是生成新列的值应该是多少,如果没有,则会对data_df剩下未统计的列进行重新排列放到columns的上层。
重塑数据(产生一个“pivot”表格)以列值为标准。使用来自索引/列的唯一的值(去除重复值)为轴形成dataframe结果。
'''
oecd_bli = oecd_bli[oecd_bli["INEQUALITY"]=="TOT"]
oecd_bli['Value'] 
pd.DataFrame(oecd_bli.groupby(by = ['Country','Indicator']).aggregate(np.sum).loc[:,'Value']) 
oecd_bli.pivot(index='Country',columns='Indicator',values='Value')
# 数据预处理
def prepare_country_stats(oecd_bli,gdp_per_capita):
    oecd_bli = oecd_bli[oecd_bli["INEQUALITY"]=="TOT"]
#    oecd_bli.columns
#    oecd_bli['Indicator'].value_counts
#    oecd_bli['Indicator'].describe(include=['object'])
    oecd_bli = oecd_bli.pivot(index='Country',columns='Indicator',values='Value')
    
#    oecd_bli.head()
    gdp_per_capita.rename(columns={'2015':'GDP per capita'},inplace=True)
#    gdp_per_capita.info() 
#    gdp_per_capita.columns
    #查看数据集是否存在缺失值
#    gdp_per_capita.apply(lambda x:np.sum(x.isnull()))
#    gdp_per_capita[['GDP per capita','Units']].apply(lambda x:np.sum(x.isnull())) #'float' object has no attribute 'isnull'
    gdp_per_capita.set_index('Country',inplace = True)
    full_country_stats = pd.merge(left = oecd_bli,right = gdp_per_capita,left_index = True,right_index = True)
    full_country_stats.sort_values(by = 'GDP per capita',inplace = True)
#    full_country_stats['GDP per capita']
#    full_country_stats.columns
#    full_country_stats[['GDP per capita','Life satisfaction']].apply(lambda x:np.sum(x.isnull()))
    remove_indices = [0,1,6,8,33,34,35]
    keep_indices = list(set(range(36))-set(remove_indices))
    return full_country_stats[['GDP per capita','Life satisfaction']].iloc[keep_indices]

#1:iloc[]  根据列中的元素,选取对应元素的数据集 
#2:根据元素的选取条件来选取对应的数据集 
#3:根据元素的选取条件来来选取对应的数据集,并在符合条件的数据行添加flage标签

# 准备数据
country_stats = prepare_country_stats(oecd_bli,gdp_per_capita)
x = np.c_[country_stats["GDP per capita"]]
y = np.c_[country_stats["Life satisfaction"]]
'''
np.r_是按列连接两个矩阵,就是把两矩阵上下相加,要求列数相等,类似于pandas中的concat()。
np.c_是按行连接两个矩阵,就是把两矩阵左右相加,要求行数相等,类似于pandas中的merge()'''
#可视化数据
country_stats.plot(kind='scatter',x='GDP per capita',y='Life satisfaction')
plt.show()

# 选择线性模型
lin_reg_model = sklearn.linear_model.LinearRegression()

#训练模型
lin_reg_model.fit(x,y)

# 对塞浦路斯进行预测
X_new = [[22587]]  #赛普路斯的人均GDP
print(lin_reg_model.predict(X_new)) #outputs[[5.96242338]]

#K近邻模型
clf = sklearn.neighbors.KNeighborsRegressor(n_neighbors = 3)
clf.fit(x,y)
X_new = [[22587]]  #赛普路斯的人均GDP
print(clf.predict(X_new))  #output[[5.76666667]]
'''
研究数据
选择模型
用训练数据进行训练(即,学习算法搜寻模型参数值,使代价函数最小)
使用模型对新案例进行预测
'''
  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值