這樣某一個特征只有0和1兩種取值,數據集有三個類別。當取0的時候,假如類別A有20個這樣的個體,類別B有60個這樣的個體,類別C有20個這樣的個體。所以,這個特征為0時,最有可能的是類別B,但是,還是有40個個體不在B類別中,所以,將這個特征為0分到類別B中的錯誤率是40%。然后,將所有的特征統計完,計算所有的特征錯誤率,再選擇錯誤率最低的特征作為唯一的分類準則——這就是OneR。
現在用代碼來實現算法。
# OneR算法實現import numpy as npfrom sklearn.datasets import load_iris# 加載iris數據集dataset = load_iris()# 加載iris數據集中的data數組(數據集的特征)X = dataset.data# 加載iris數據集中的target數組(數據集的類別)y_true = dataset.target# 計算每一項特征的平均值attribute_means = X.mean(axis=0)# 與平均值比較,大于等于的為“1”,小于的為“0”.將連續性的特征值變為離散性的類別型。x = np.array(X >= attribute_means, dtype="int")from sklearn.model_selection import train_test_splitx_train, x_test, y_train, y_test = train_test_split(x, y_true, random_state=14)from operator import itemgetterfrom collections import defaultdict# 找到一個特征下的不同值的所屬的類別。def train_feature_class(x, y_true, feature_index, feature_values):  num_class = defaultdict(int)  for sample, y in zip(x, y_true):    if sample[feature_index] == feature_values:      num_class[y] += 1  # 進行排序,找出最多的類別。按從大到小排列  sorted_num_class = sorted(num_class.items(), key=itemgetter(1), reverse=True)  most_frequent_class = sorted_num_class[0][0]  error = sum(value_num for class_num , value_num in sorted_num_class if class_num != most_frequent_class)  return most_frequent_class, error# print train_feature_class(x_train, y_train, 0, 1)# 接著定義一個以特征為自變量的函數,找出錯誤率最低的最佳的特征,以及該特征下的各特征值所屬的類別。def train_feature(x, y_true, feature_index):  n_sample, n_feature = x.shape  assert 0 <= feature_index < n_feature  value = set(x[:, feature_index])  predictors = {}  errors = []  for current_value in value:    most_frequent_class, error = train_feature_class(x, y_true, feature_index, current_value)    predictors[current_value] = most_frequent_class    errors.append(error)  total_error = sum(errors)  return predictors, total_error# 找到所有特征下的各特征值的類別,格式就如:{0:({0: 0, 1: 2}, 41)}首先為一個字典,字典的鍵是某個特征,字典的值由一個集合構成,這個集合又是由一個字典和一個值組成,字典的鍵是特征值,字典的值為類別,最后一個單獨的值是錯誤率。all_predictors = {feature: train_feature(x_train, y_train, feature) for feature in xrange(x_train.shape[1])}# print all_predictors# 篩選出每個特征下的錯誤率出來errors = {feature: error for feature, (mapping, error) in all_predictors.items()}# 對錯誤率排序,得到最優的特征和最低的錯誤率,以此為模型和規則。這就是one Rule(OneR)算法。best_feature, best_error = sorted(errors.items(), key=itemgetter(1), reverse=False)[0]# print "The best model is based on feature {0} and has error {1:.2f}".format(best_feature, best_error)# print all_predictors[best_feature][0]# 建立模型model = {"feature": best_feature, "predictor": all_predictors[best_feature][0]}# print model# 開始測試——對最優特征下的特征值所屬類別進行分類。def predict(x_test, model):  feature = model["feature"]  predictor = model["predictor"]  y_predictor = np.array([predictor[int(sample[feature])] for sample in x_test])  return y_predictory_predictor = predict(x_test, model)# print y_predictor# 在這個最優特征下,各特征值的所屬類別與測試數據集相對比,得到準確率。accuracy = np.mean(y_predictor == y_test) * 100print "The test accuracy is {0:.2f}%".format(accuracy)from sklearn.metrics import classification_report# print(classification_report(y_test, y_predictor))            
新聞熱點
疑難解答