机器学习(三)随机森林之根据汽车特征评估质量

编程入门 行业动态 更新时间:2024-10-06 18:31:04

机器学习(三)随机森林之根据汽车<a href=https://www.elefans.com/category/jswz/34/1769701.html style=特征评估质量"/>

机器学习(三)随机森林之根据汽车特征评估质量

随机森林之根据汽车特征评估质量

  • 实验内容
  • 准备工作
  • 实验步骤
  • 结果
  • 总结


实验内容

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


准备工作

你可以从+Evaluation下载数据集。 你需要把数据集中的每个值看成是字符串。考虑数据集中的6个属性,其取值范围是这样的:
 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。

考虑到每一行都包含字符串属性,需要假设所有特征都是字符串,并设置分类器。在上一章 中,我们用随机森林建立过回归器,这里再用随机森林建立分类器。

这是源代码和数据集,我把它放在百度网盘了,需要自取
链接:
提取码:gr2f
复制这段内容后打开百度网盘手机App,操作更方便哦

实验步骤

# based on 2_9 car.py
# goal: generate validation curves about classifier's performanceimport numpy as np
from sklearn import preprocessing
from sklearn.ensemble import RandomForestClassifier
from sklearn import model_selection
import matplotlib.pyplot as pltinput_file = 'car.data.txt'# Reading the data
X = []
y = []
count = 0with open(input_file, 'r') as f:for line in f.readlines():data = line[:-1].split(',')X.append(data)X = np.array(X)# 标记编码
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)# 森林中树的数量: 200
# 决策树 划分选择: 信息熵
# 决策树的最大深度: 10
# 控制从原始的数据集中采取有放回的抽样  参数=10params = {"n_estimators":200, "criterion":'entropy', "max_depth":10, "random_state":10}classifier = RandomForestClassifier(**params)
classifier.fit(X, y)# cross validation
accuracy = model_selection.cross_val_score(classifier, X, y,scoring='accuracy', cv=3)
print("Accuracy of the classifier: " + str(round(100*accuracy.mean(), 2)) + "%")# 使用单一数据样例进行检验
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)  # 将标记编码后的单一样本转换成numpy数组
input_data_encoded = input_data_encoded.reshape(1, len(input_data))# 打印输出结果
output_class = classifier.predict(input_data_encoded)
print("Output class:", label_encoder[-1].inverse_transform(output_class)[0])# 2_10 起始位置classifier = RandomForestClassifier(max_depth=4, random_state=7) # 固定max_depth参数为4定义分类器
parameter_grid = np.linspace(25, 200, 8).astype(int)
# 观察评估器数量对训练得分的影响,评估器每8迭代一次
train_scores, validation_scores = model_selection.validation_curve\(classifier, X, y, "n_estimators", parameter_grid, cv=5)
print("\nParam: n_estimators\nTraining scores:\n", train_scores)
print("\nParam: n_estimators\nValidation scores:\n", validation_scores)# 画出图像
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 = model_selection.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)# 画图
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()########################
# Learning curvesclassifier = RandomForestClassifier(random_state=7)parameter_grid = np.array([200, 500, 800, 1100])
train_sizes, train_scores, validation_scores = model_selection.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
# 特别说明:代码没有任何问题,最后这个学习图像画的不对完全是因为Pycharm软件缘故,在Spyder上运行没有任何问题
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()

结果

总结

提示:这里对文章进行总结:
例如:以上就是今天要讲的内容,本文仅仅简单介绍了pandas的使用,而pandas提供了大量能使我们快速便捷地处理数据的函数和方法。



更多推荐

机器学习(三)随机森林之根据汽车特征评估质量

本文发布于:2024-02-28 12:26:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1769586.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:特征   机器   森林   质量   汽车

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!