一.     问题描述

每个人都希望自己能获得更高的收入,而影响收入高低的因素有很多,能否通过大数据分析来找出对收入影响相对较大的因素?

二.     研究意义

如果我们知道对收入高低起决定性的作用,或者哪些因素组合在一起也能增大收入的可能性,那可以帮助很多人少走弯路,朝着正确的方向努力,早日达到目标。

三.     数据预处理

1.  选取数据集

本报告选取“adult”数据集,由美国人口普查数据集库抽取而来。

该数据集类变量为年收入是否超过50k,属性变量包含年龄,工种,学历,职业,人种等14个属性变量,其中有7个类别型变量。共有30000多条数据。

2.  预处理

由于capital-gain、capital-loss属性缺失70%以上的数据,所以选择删去这两个属性。

在其他类变量中,有缺少或异常属性400多条,占总数据比重较小,也选择删去。

四.     数据可视化

1.workclass

2.education

3.race

4.sex

5.marital-status

五.     算法选取与实现

本次报告中选用决策树算法。决策树是一种依托决策而建立起来的一种树。在机器学习中,决策树是一种预测模型,代表的是一种对象属性与对象值之间的一种映射关系,每一个节点代表某个对象,树中的每一个分叉路径代表某个可能的属性值,而每一个叶子节点则对应从根节点到该叶子节点所经历的路径所表示的对象的值。决策树仅有单一输出,如果有多个输出,可以分别建立独立的决策树以处理不同的输出。

由于数据量过大,普通决策树不能达到预期效果,所以再用预剪枝进行处理。预剪枝是在决策树生成过程中,在划分节点时,若该节点的划分没有提高其在训练集上的准确率,则不进行划分。

下面是预剪枝决策树程序

1. 计算数据集的基尼系数

def calcGini(dataSet):numEntries=len(dataSet)labelCounts={}#给所有可能分类创建字典for featVec in dataSet:currentLabel=featVec[-1]if currentLabel not in labelCounts.keys():labelCounts[currentLabel]=0labelCounts[currentLabel]+=1Gini=1.0#以2为底数计算香农熵for key in labelCounts:prob = float(labelCounts[key])/numEntriesGini-=prob*probreturn Gini

2. 对离散变量划分数据集,取出该特征取值为value的所有样本

def splitDataSet(dataSet,axis,value):retDataSet=[]for featVec in dataSet:if featVec[axis]==value:reducedFeatVec=featVec[:axis]reducedFeatVec.extend(featVec[axis+1:])retDataSet.append(reducedFeatVec)return retDataSet

3. 对连续变量划分数据集,direction规定划分的方向,决定是划分出小于value的数据样本还是大于value的数据样本集

def splitContinuousDataSet(dataSet,axis,value,direction):retDataSet=[]for featVec in dataSet:if direction==0:if featVec[axis]>value:reducedFeatVec=featVec[:axis]reducedFeatVec.extend(featVec[axis+1:])retDataSet.append(reducedFeatVec)else:if featVec[axis]<=value:reducedFeatVec=featVec[:axis]reducedFeatVec.extend(featVec[axis+1:])retDataSet.append(reducedFeatVec)return retDataSet

4. 选择最好的数据集划分方式

def chooseBestFeatureToSplit(dataSet,labels):numFeatures=len(dataSet[0])-1bestGiniIndex=100000.0bestFeature=-1bestSplitDict={}for i in range(numFeatures):featList=[example[i] for example in dataSet]#对连续型特征进行处理if type(featList[0]).__name__=='float' or type(featList[0]).__name__=='int':#产生n-1个候选划分点sortfeatList=sorted(featList)splitList=[]for j in range(len(sortfeatList)-1):splitList.append((sortfeatList[j]+sortfeatList[j+1])/2.0)bestSplitGini=10000slen=len(splitList)#求用第j个候选划分点划分时,得到的信息熵,并记录最佳划分点for j in range(slen):value=splitList[j]newGiniIndex=0.0subDataSet0=splitContinuousDataSet(dataSet,i,value,0)subDataSet1=splitContinuousDataSet(dataSet,i,value,1)prob0=len(subDataSet0)/float(len(dataSet))newGiniIndex+=prob0*calcGini(subDataSet0)prob1=len(subDataSet1)/float(len(dataSet))newGiniIndex+=prob1*calcGini(subDataSet1)if newGiniIndex<bestSplitGini:bestSplitGini=newGiniIndexbestSplit=j#用字典记录当前特征的最佳划分点bestSplitDict[labels[i]]=splitList[bestSplit]GiniIndex=bestSplitGini#对离散型特征进行处理else:uniqueVals=set(featList)newGiniIndex=0.0#计算该特征下每种划分的信息熵for value in uniqueVals:subDataSet=splitDataSet(dataSet,i,value)prob=len(subDataSet)/float(len(dataSet))newGiniIndex+=prob*calcGini(subDataSet)GiniIndex=newGiniIndexif GiniIndex<bestGiniIndex:bestGiniIndex=GiniIndexbestFeature=i#若当前节点的最佳划分特征为连续特征,则将其以之前记录的划分点为界进行二值化处理#即是否小于等于bestSplitValue#并将特征名改为 name<=value的格式if type(dataSet[0][bestFeature]).__name__=='float' or type(dataSet[0][bestFeature]).__name__=='int':      bestSplitValue=bestSplitDict[labels[bestFeature]]        labels[bestFeature]=labels[bestFeature]+'<='+str(bestSplitValue)for i in range(shape(dataSet)[0]):if dataSet[i][bestFeature]<=bestSplitValue:dataSet[i][bestFeature]=1else:dataSet[i][bestFeature]=0return bestFeature

5. 特征若已经划分完,节点下的样本还没有统一取值,则需要进行投票

def majorityCnt(classList):classCount={}for vote in classList:if vote not in classCount.keys():classCount[vote]=0classCount[vote]+=1return max(classCount)

6.由于在Tree中,连续值特征的名称以及改为了  feature<=value的形式,因此对于这类特征,需要利用正则表达式进行分割,获得特征名以及分割阈值

def classify(inputTree,featLabels,testVec):firstStr=list(inputTree.keys())[0]if '<=' in firstStr:featvalue=float(re.compile("(<=.+)").search(firstStr).group()[2:])featkey=re.compile("(.+<=)").search(firstStr).group()[:-2]secondDict=inputTree[firstStr]featIndex=featLabels.index(featkey)if testVec[featIndex]<=featvalue:judge=1else:judge=0for key in secondDict.keys():if judge==int(key):if type(secondDict[key]).__name__=='dict':classLabel=classify(secondDict[key],featLabels,testVec)else:classLabel=secondDict[key]else:secondDict=inputTree[firstStr]featIndex=featLabels.index(firstStr)for key in secondDict.keys():if testVec[featIndex]==key:if type(secondDict[key]).__name__=='dict':classLabel=classify(secondDict[key],featLabels,testVec)else:classLabel=secondDict[key]return classLabeldef testing(myTree,data_test,labels):error=0.0for i in range(len(data_test)):if classify(myTree,labels,data_test[i])!=data_test[i][-1]:error+=1print ('myTree %d' %error)return float(error)def testingMajor(major,data_test):error=0.0for i in range(len(data_test)):if major!=data_test[i][-1]:error+=1print ('major %d' %error)return float(error)

7.主程序,递归产生决策树

def createTree(dataSet,labels,data_full,labels_full,data_test):classList=[example[-1] for example in dataSet]if classList.count(classList[0])==len(classList):return classList[0]if len(dataSet[0])==1:return majorityCnt(classList)temp_labels=copy.deepcopy(labels)bestFeat=chooseBestFeatureToSplit(dataSet,labels)bestFeatLabel=labels[bestFeat]myTree={bestFeatLabel:{}}if type(dataSet[0][bestFeat]).__name__=='str':currentlabel=labels_full.index(labels[bestFeat])featValuesFull=[example[currentlabel] for example in data_full]uniqueValsFull=set(featValuesFull)featValues=[example[bestFeat] for example in dataSet]uniqueVals=set(featValues)del(labels[bestFeat])#针对bestFeat的每个取值,划分出一个子树。for value in uniqueVals:subLabels=labels[:]if type(dataSet[0][bestFeat]).__name__=='str':uniqueValsFull.remove(value)myTree[bestFeatLabel][value]=createTree(splitDataSet\(dataSet,bestFeat,value),subLabels,data_full,labels_full,\splitDataSet(data_test,bestFeat,value))if type(dataSet[0][bestFeat]).__name__=='str':for value in uniqueValsFull:myTree[bestFeatLabel][value]=majorityCnt(classList)#进行测试,若划分没有提高准确率,则不进行划分,返回该节点的投票值作为节点类别if testing(myTree,data_test,temp_labels)<testingMajor(majorityCnt(classList),data_test):return myTreereturn majorityCnt(classList)

六.     结果分析

1. 未剪枝决策树

2. 预剪枝决策树

转载于:https://www.cnblogs.com/yue-guan/p/adult1072.html

机器学习实例--预测美国人口收入状况相关推荐

  1. 遥感图像+CNN,预测区域人口收入水平

    点击上方"小白学视觉",选择加"星标"或"置顶" 重磅干货,第一时间送达 本文转自机器之心 采用卷积神经网络(CNN)和卫星图像数据来预测区 ...

  2. 美国人口普查数据预测收入sklearn算法汇总3之ROC: KNN,LogisticRegression,RandomForest,NaiveBayes,StochasticGradientDece

    接<美国人口普查数据预测收入sklearn算法汇总1: 了解数据以及数据预处理> <美国人口普查数据预测收入sklearn算法汇总2: 特征编码, 特征选择, 降维, 递归特征消除& ...

  3. 美国人口普查年收入比赛_训练网络对收入进行分类:成人普查收入数据集

    美国人口普查年收入比赛 We have all heard that data science is the 'sexiest job of the 21st century'. Hence, it ...

  4. 用机器学习识别不断变化的股市状况—隐马尔可夫模型(HMM)股票指数预测实战

    "了解不同的股市状况,改变交易策略,对股市收益有很大的影响. 弄清楚何时开始或何时止损,调整风险和资金管理技巧,都取决于股市的当前状况. ▼ 有些策略在波澜不惊的股市中表现良好,而有些策略可 ...

  5. pandas 实例操作:美国人口案例分析

    pandas 案例分析:美国人口案例分析 ''' 需求:导入文件,查看原始数据将人口数据和各州简称数据进行合并将合并的数据中重复的abbreviation列进行删除查看存在缺失数据的列找到有哪些sta ...

  6. 美国人口预测问题 MATLAB程序_BeansSuperman_新浪博客

    下表给出的是近两个世纪的美国人口统计数据(以百万为单位),对模型做检验,最后用它预报2010年美国的人口. 年份 1790 1800 1810 1820 1830 1840 人口 3.9 5.3 7. ...

  7. 用Python搭建机器学习模型预测房租价格

    毫无疑问,机器学习是当前大数据分析中最热门的话题.这也是一些最令人兴奋的技术领域的基本概念,例如自动驾驶汽车和预测分析.百度上的机器学习搜索在2019年4月创历史新高,自此以来兴趣一直没有下降. 但是 ...

  8. 应用丨AI和机器学习如何改变美国政府决策方式

    在每个联邦机构中,重要的见解都隐藏在多年来收集的大量数据集中.但是由于联邦政府数据科学家的短缺,从这些数据中提取价值是非常耗时的.然而,随着数据科学,人工智能(AI)和机器学习的进步,各机构现在可以使 ...

  9. 机器学习股票预测_是否进行基础投资工作,以尝试通过机器学习预测股票成功...

    机器学习股票预测 Like most of you, I have a strong interest in making more money and growing my savings fast ...

最新文章

  1. IOS开发怎么UINavigationController设置title标题的颜色?
  2. itx机箱尺寸_乔思伯发布ITX机箱V8,采用独特抽拉式结构
  3. Delphi(Tuxedo,BDE,ADO)三合一数据集组件HsTxQuery
  4. 八十四、Python | Leetcode回溯算法系列
  5. tslib 编译移植步骤
  6. 在Hyper-v中创建并安装虚拟机
  7. 【报告分享】2022年零售行业消费趋势新主张-京东+罗兰贝格.pdf(附下载链接)...
  8. 《MySQL必知必会》学习笔记——第三章(了解数据库和表)
  9. 如何通过企业微信做精细化社群运营
  10. 基于qt开发的一款聊天气泡框
  11. SQL- join多表关联
  12. 无效的m3u8怎么办_你还在为m3u8文件如何转换而发愁?看了我就有答案了
  13. svn 分支 合并
  14. Amazon EKS 使用 EFS服务
  15. Arduino基础入门篇30—数字温度传感器DS18B20
  16. Elixir - case, cond, and if
  17. python源码大全-最全Python算法实现资源汇总!
  18. 夜间模式的开启与关闭,父模板的制作(2017.11.2)
  19. 通达信 缠论分笔、分段DLL插件
  20. 谷歌浏览器及wordpress等插件推荐集合

热门文章

  1. win10网络图标变成地球加禁止符号但能上网解决办法
  2. android ram rom测试工具,ROM与RAM的那点事,超详细解说
  3. 测试软件要求规范 (SRS)
  4. Gentoo USE参数清单中文详解
  5. 英文标点符号unicode
  6. thinkphp用phpqrcode生成二维码(含中间带logo、临时二维码)或生成微信二维码海报的方法
  7. JavaScript——Symbol类型
  8. 响应式极简新闻发布系统源码
  9. android 查看cpu 工具6,Android 之CPU监控命令
  10. 老板儿子来公司实习,还让我带着他学Python?搞笑