隨機森林之根據汽車特徵評估質量
阿新 • • 發佈:2020-12-19
實驗內容
根據汽車特徵評估質量
接下來看看如何用分類技術解決現實問題。我們將用一個包含汽車多種細節的資料集,例如 車門數量、後備箱大小、維修成本等,來確定汽車的質量。分類的目的是把車輛的質量分成4種 型別:不達標、達標、良好、優秀。
準備工作
你可以從https://archive.ics.uci.edu/ml/datasets/Car+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。
考慮到每一行都包含字串屬性,需要假設所有特徵都是字串,並設定分類器。在上一章 中,我們用隨機森林建立過迴歸器,這裡再用隨機森林建立分類器。
這是原始碼和資料集,我把它放在百度網盤了,需要自取
連結:https://pan.baidu.com/s/1liNa_Ptggr9zwxCjnldb2w
提取碼:gr2f
複製這段內容後開啟百度網盤手機App,操作更方便哦
實驗步驟
# based on 2_9 car.py
# goal: generate validation curves about classifier's performance
import numpy as np
from sklearn import preprocessing
from sklearn.ensemble import RandomForestClassifier
from sklearn import model_selection
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)
# 標記編碼
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
# 控制從原始的資料集中採取有放回的抽樣 引數=10
params = {"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