python分类算法实例_python3机器学习经典实例-学习笔记9-分类算法

实例1-依据汽车属性进行评估

接下来看看如何用分类技术解决现实问题。我们将用一个包含汽车多种细节的数据集,例如车门数量、后备箱大小、维修成本等,来确定汽车的质量。分类的目的是把车辆的质量分成4种类型:不达标、达标、良好、优秀。

 buying:取值范围是vhigh、high、med、low;

 maint:取值范围是vhigh、high、med、low;

 doors:取值范围是2、3、4、5等;

 persons:取值范围是2、4等;

 lug_boot:取值范围是small、med、big;

 safety:取值范围是low、med、high。

数据示例:vhigh,vhigh,2,2,small,low,unacc

程序步骤导入必要的数据包

import numpy as np

from sklearn import preprocessing

from sklearn.ensemble import RandomForestClassifier

import matplotlib.pyplot as plt

读取数据

input_file = 'car.data.txt'

# Reading the data

X = []

y = []

count = 0

with open(input_file, 'r') as f:

for line in f.readlines():

data = line[:-1].split(',')

X.append(data)

X = np.array(X)

数据示例:vhigh,vhigh,2,2,small,low,unacc

每一行都包含由逗号分隔的单词列表。因此,我们解析输入文件,对每一行进行分割,然后将该列表附加到主数据。我们忽略每一行最后一个字符,因为那是一个换行符。由于Python程序包只能处理数值数据,所以需要把这些属性转换成程序包可以理解的形式。将字符串转换成数值

# Convert string data to numerical data

label_encoder = []

X_encoded = np.empty(X.shape)

for i,item in enumerate(X[0]):

label_encoder.append(preprocessing.LabelEncoder())

X_encoded[:, i] = label_encoder[-1].fit_transform(X[:, i])

X = X_encoded[:, :-1].astype(int)

y = X_encoded[:, -1].astype(int)

由于每个属性可以取有限数量的数值,所以可以用标记编码器将它们转换成数字。我们需要为不同的属性使用不同的标记编码器,例如,lug_boot属性可以取3个不同的值,需要建立一个懂得给这3个属性编码的标记编码器。每一行的最后一个值是类,将它赋值给变量y。建立训练分类器

params = {'n_estimators': 200, 'max_depth': 8, 'random_state': 7}

classifier = RandomForestClassifier(**params)

classifier.fit(X, y)

你可以改变n_estimators和max_depth参数的值,观察它们如何改变分类器的准确性。我们将用一个标准化的方法处理参数选择问题。进行交叉验证

# Cross validation

from sklearn import cross_validation

accuracy = cross_validation.cross_val_score(classifier,

X, y, scoring='accuracy', cv=3)

print ("Accuracy of the classifier: " + str(round(100*accuracy.mean(), 2)) + "%")

一旦训练好分类器,我们就需要知道它是如何执行的。我们用三折交叉验证(three-foldcross-validation,把数据分3组,轮换着用其中两组数据验证分类器)来计算分类器的准确性。建立分类器的主要目的就是要用它对孤立的和未知的数据进行分类。下面用分类器对一个单一数据点进行分类:

# Testing encoding on single data instance

input_data = ['vhigh', 'vhigh', '2', '2', 'small', 'low']

input_data_encoded = [-1] * len(input_data)

for i,item in enumerate(input_data):

input_data_encoded[i] = int(label_encoder[i].transform([input_data[i]]))

input_data_encoded = np.array(input_data_encoded).reshape(1,6)

第一步是把数据转换成数值类型。需要使用之前训练分类器时使用的标记编码器,因为我们需要保持数据编码规则的前后一致。如果输入数据点里出现了未知数据,标记编码器就会出现异常,因为它不知道如何对这些数据进行编码。例如,如果你把列表中的第一个值vhigh改成abcd ,那么标记编码器就不知道如何编码了,因为它不知道怎么处理这个字符串。这就像是错误检查,看看输入数据点是否有效。预测输出类型

# Predict and print output for a particular datapoint

output_class = classifier.predict(input_data_encoded)

print ("Output class:", label_encoder[-1].inverse_transform(output_class)[0])输出结果out

Accuracy of the classifier: 78.19%

Output class: unacc

生成验证曲线

前面用随机森林建立了分类器,但是并不知道如何定义参数。本节来处理两个参数:n_estimators和max_depth参数。它们被称为超参数(hyperparameters),分类器的性能是由它们决定的。当改变超参数时,如果可以看到分类器性能的变化情况,那就再好不过了。这就是验证曲线的作用。这些曲线可以帮助理解每个超参数对训练得分的影响。基本上,我们只对感兴趣的超参数进行调整,其他参数可以保持不变。下面将通过可视化图片演示超参数的变化对训练得分的影响。

验证曲线

########################

# Validation curves

from sklearn.learning_curve import validation_curve

classifier = RandomForestClassifier(max_depth=4, random_state=7)

parameter_grid = np.linspace(25, 200, 8).astype(int)

train_scores, validation_scores = validation_curve(classifier, X, y,

"n_estimators", parameter_grid, cv=5)

print ("\n##### VALIDATION CURVES #####")

print ("\nParam: n_estimators\nTraining scores:\n", train_scores)

print ("\nParam: n_estimators\nValidation scores:\n", validation_scores)

运行代码的结果

##### VALIDATION CURVES #####

Param: n_estimators

Training scores:

[[0.80680174 0.80824891 0.80752533 0.80463097 0.81358382]

[0.79522431 0.80535456 0.81041968 0.8089725 0.81069364]

[0.80101302 0.80680174 0.81114327 0.81476122 0.8150289 ]

[0.8024602 0.80535456 0.81186686 0.80752533 0.80346821]

[0.80028944 0.80463097 0.81114327 0.80824891 0.81069364]

[0.80390738 0.80535456 0.81041968 0.80969609 0.81647399]

[0.80390738 0.80463097 0.81114327 0.81476122 0.81719653]

[0.80390738 0.80607815 0.81114327 0.81403763 0.81647399]]

Param: n_estimators

Validation scores:

[[0.71098266 0.76589595 0.72543353 0.76300578 0.75290698]

[0.71098266 0.75433526 0.71965318 0.75722543 0.74127907]

[0.71098266 0.72254335 0.71965318 0.75722543 0.74418605]

[0.71098266 0.71387283 0.71965318 0.75722543 0.72674419]

[0.71098266 0.74277457 0.71965318 0.75722543 0.74127907]

[0.71098266 0.74277457 0.71965318 0.75722543 0.74127907]

[0.71098266 0.74566474 0.71965318 0.75722543 0.74418605]

[0.71098266 0.75144509 0.71965318 0.75722543 0.74127907]]

把数据画成图形

# Plot the curve

plt.figure()

plt.plot(parameter_grid, 100*np.average(train_scores, axis=1), color='black')

plt.title('Training curve')

plt.xlabel('Number of estimators')

plt.ylabel('Accuracy')

plt.show()

对参数max_depth进行验证与上相似

classifier = RandomForestClassifier(n_estimators=20, random_state=7)

parameter_grid = np.linspace(2, 10, 5).astype(int)

train_scores, valid_scores = validation_curve(classifier, X, y,

"max_depth", parameter_grid, cv=5)

print ("\nParam: max_depth\nTraining scores:\n", train_scores)

print ("\nParam: max_depth\nValidation scores:\n", validation_scores)

# Plot the curve

plt.figure()

plt.plot(parameter_grid, 100*np.average(train_scores, axis=1), color='black')

plt.title('Validation curve')

plt.xlabel('Maximum depth of the tree')

plt.ylabel('Accuracy')

plt.show()

结果输出

Param: max_depth

Training scores:

[[0.71852388 0.70043415 0.70043415 0.70043415 0.69942197]

[0.80607815 0.80535456 0.80752533 0.79450072 0.81069364]

[0.90665702 0.91027496 0.92836469 0.89797395 0.90679191]

[0.97467438 0.96743849 0.96888567 0.97829233 0.96820809]

[0.99421129 0.99710564 0.99782923 0.99855282 0.99277457]]

Param: max_depth

Validation scores:

[[0.71098266 0.76589595 0.72543353 0.76300578 0.75290698]

[0.71098266 0.75433526 0.71965318 0.75722543 0.74127907]

[0.71098266 0.72254335 0.71965318 0.75722543 0.74418605]

[0.71098266 0.71387283 0.71965318 0.75722543 0.72674419]

[0.71098266 0.74277457 0.71965318 0.75722543 0.74127907]

[0.71098266 0.74277457 0.71965318 0.75722543 0.74127907]

[0.71098266 0.74566474 0.71965318 0.75722543 0.74418605]

[0.71098266 0.75144509 0.71965318 0.75722543 0.74127907]]

生成学习曲线

学习曲线可以帮助我们理解训练数据集的大小对机器学习模型的影响。当遇到计算能力限制时,这一点非常有用。下面改变训练数据集的大小,把学习曲线画出来。

我们想分别用200、500、800、1100的训练数据集的大小测试模型的性能指标。我们把learning_curve方法中的cv参数设置为5,就是用五折交叉验证。

########################

# Learning curves

from sklearn.learning_curve import learning_curve

classifier = RandomForestClassifier(random_state=7)

parameter_grid = np.array([200, 500, 800, 1100])

train_sizes, train_scores, validation_scores = learning_curve(classifier,

X, y, train_sizes=parameter_grid, cv=5)

print ("\n##### LEARNING CURVES #####")

print ("\nTraining scores:\n", train_scores)

print ("\nValidation scores:\n", validation_scores)

# Plot the curve

plt.figure()

plt.plot(parameter_grid, 100*np.average(train_scores, axis=1), color='black')

plt.title('Learning curve')

plt.xlabel('Number of training samples')

plt.ylabel('Accuracy')

plt.show()

结果输出

##### LEARNING CURVES #####

Training scores:

[[1. 1. 1. 1. 1. ]

[1. 1. 0.998 0.998 0.998 ]

[0.99875 0.9975 0.99875 0.99875 0.99875 ]

[0.99818182 0.99545455 0.99909091 0.99818182 0.99818182]]

Validation scores:

[[0.69942197 0.69942197 0.69942197 0.69942197 0.70348837]

[0.74855491 0.65028902 0.76878613 0.76589595 0.70348837]

[0.70520231 0.78612717 0.52312139 0.76878613 0.77034884]

[0.65028902 0.75433526 0.65317919 0.75433526 0.76744186]]

虽然训练数据集的规模越小,仿佛训练准确性越高,但是它们很容易导致过度拟合。如果选择较大规模的训练数据集,就会消耗更多的资源。因此,训练数据集的规模选择也是一个需要结合计算能力进行综合考虑的问题。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值