python演算法演練——One Rule 演算法,pythonrule
這樣某一個特徵只有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))
總結:OneR演算法,我在最開始的以為它是找到一個錯誤率最低的特徵之後可以判斷所有特徵的分類,
其實,現在明白它只能判斷這個特徵下的各特徵值的分類,所以,明顯它會有一些局限性。只是說
它比較快捷也比較簡單明了。但是,還是得是情況而判斷是否使用它。
class precision recall f1-score support
0 0.94 1.00 0.97 17
1 0.00 0.00 0.00 13
2 0.40 1.00 0.57 8
avg / total 0.51 0.66 0.55 38
註:
# 在上面代碼中。
for sample in x_test:
print sample[0]
# 得到的是x_test的第一列資料。而用下面的代碼得到的是x_test的第一行資料。
print x_test[0]
# 注意兩者區別