当前位置:   article > 正文

使用决策树和随机森林对数据分类

使用决策树和随机森林对数据分类


前言

在研究机器学习,发现了一些宝藏算法,写下来让自己记住,超有用!同时也想要分享给大家,如果喜欢可以支持一下,谢谢。

一、使用决策树和随机森林对数据分类

使用决策树算法和随机森林算法对income_classification.csv的收入水平进行分类。训练集和测试集的比例是7:3,选取适当的特征列,使得针对测试样本的分类准确率在80%以上,比较2种分类方法的准确率。

数据说明:

特征列

age:年龄,整数

workclass:工作性质,字符串

education:教育程度,字符串

education_num:受教育年限,整数

maritial_status:婚姻状况,字符串

occupation:职业,字符串

relationship:亲戚关系,字符串

race:种族,字符串

sex:性别,字符串

capital_gain:资本收益,浮点数

capital_loss:资本损失,浮点数

hours_per_week:每周工作小时数,浮点数

native_country:原籍,字符串

分类标签列:income

imcome > 50K

Imcome ≤ 50K

  读入数据并显示数据的维度和前5行数据
  • 1

import pandas as pd

import numpy as np

对连续变量年龄进行离散化,并显示前5行数据离散化后的结果

age_bins = [20, 30,40, 50, 60, 70]

对属性是字符串的任意特征进行数字编号处理,显示前5行编码后的结果,每个特定的字符串用一个整数来表示,整数序列从0开始增长。

from sklearn.preprocessing import LabelEncoder

enc = LabelEncoder()

对预处理后的数据用决策树算法和随机森林算法分类

代码思路:

  1. 选择合适的若干特征字段

  2. 按7:3划分训练集和样本集

  3. 使用训练集训练一个决策树分类器

  4. 使用测试集计算决策树分类器的分类准确率

  5. 使用训练集训练一个随机森林分类器

  6. 使用测试集计算随机森林分类器的分类准确率

fromsklearn.ensemble import RandomForestClassifier

from sklearn importtree

fromsklearn.preprocessing import LabelEncoder

fromsklearn.feature_extraction import DictVectorizer

accuracy_random =clf_random.score(xTest, yTest)

二、代码

import numpy as np
from sklearn.feature_extraction import DictVectorizer
from sklearn.ensemble import RandomForestClassifier
from sklearn import tree

print(‘1.载入数据…’)
data = []
labels = []
with open(“income_classification.csv”) as ifile:
for line in ifile:
# data需要是字典形式,因为之后需要使用DictVectorizer()修改字符串数据类型,以便符合DecisionTreeClassifier()
rowDict = {}
tokens = line.strip().split(’,’)
rowDict[‘age’] = tokens[0]
rowDict[‘workclass’] = tokens[1]
rowDict[‘education_num’] = tokens[2]
rowDict[‘maritial_status’] = tokens[3]
rowDict[‘occupation’] = tokens[4]
rowDict[‘relationship’] = tokens[5]
rowDict[‘race’] = tokens[6]
rowDict[‘sex’] = tokens[7]
rowDict[‘capital_gain’] = tokens[8]
rowDict[‘capital_loss’] = tokens[9]
rowDict[‘hours_per_week’] = tokens[10]
rowDict[‘native_country’] = tokens[11]
rowDict[‘income’] = tokens[12]
data.append(rowDict)
labels.append(tokens[-1])

print(‘2. 构造数据和标签…’)
x = np.array(data)
labels = np.array(labels)
y = np.zeros(labels.shape) # 初始label全为0

y[labels == ‘<=50K’] = 0 # 当label等于这三种属性的话,设置为1。
y[labels == ‘>50K’] = 1

print(‘3.转换字符串数据类型…’)
vec = DictVectorizer() # 转换字符串数据类型
dx = vec.fit_transform(x).toarray()

print(‘4.拆分训练数据和测试数据…’)
print(‘训练集和验证集比例7:3’)

拆分成训练数据和测试数据

ratio = 0.7
xTrain = []
yTrain = []
xTest = []
yTest = []
features = xTrain, xTest
labels = yTrain, yTest
for i in range(len(dx)):
dataSetIndex = 0 if np.random.random() < ratio else 1
features[dataSetIndex].append(dx[i])
labels[dataSetIndex].append(y[i])

CART决策树分类

print(‘5.CART决策树分类…’)
clf_cart = tree.DecisionTreeClassifier(criterion = ‘entropy’) # CART算法,使用entropy作为标准;默认是是用gini作为标准
clf_cart.fit(xTrain, yTrain)

检查准确率

accuracy_cart = clf_cart.score(xTest, yTest)
print(‘CART树分类准确率:’,accuracy_cart)

print(‘6.随机森林分类…’)
clf_random = RandomForestClassifier()
clf_random.fit(xTrain, yTrain)

检查准确率

accuracy_random = clf_random.score(xTest, yTest)
print(‘随机森林分类准确率:’, accuracy_random)


以上代码全部复制进python环境即可运行,亲测有效

三、总结

python库很强大,短短几句话就完事了。
但是如果你不知道有这几句话,你确实得找很久
希望我能帮你省些时间,喜欢的可以支持一下,谢谢啦~

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/646515
推荐阅读
相关标签
  

闽ICP备14008679号