技術(shù)員聯(lián)盟提供win764位系統(tǒng)下載,win10,win7,xp,裝機純凈版,64位旗艦版,綠色軟件,免費軟件下載基地!

當(dāng)前位置:主頁 > 教程 > 服務(wù)器類 >

python算法演練_One Rule 算法教程

來源:技術(shù)員聯(lián)盟┆發(fā)布時間:2017-10-16 18:06┆點擊:

這樣某一個特征只有0和1兩種取值,數(shù)據(jù)集有三個類別。當(dāng)取0的時候,假如類別A有20個這樣的個體,類別B有60個這樣的個體,類別C有20個這樣的個體。所以,這個特征為0時,最有可能的是類別B,但是,還是有40個個體不在B類別中,所以,將這個特征為0分到類別B中的錯誤率是40%。然后,將所有的特征統(tǒng)計完,計算所有的特征錯誤率,再選擇錯誤率最低的特征作為唯一的分類準(zhǔn)則——這就是OneR。

現(xiàn)在用代碼來實現(xiàn)算法。

# OneR算法實現(xiàn) import numpy as np from sklearn.datasets import load_iris # 加載iris數(shù)據(jù)集 dataset = load_iris() # 加載iris數(shù)據(jù)集中的data數(shù)組(數(shù)據(jù)集的特征) X = dataset.data # 加載iris數(shù)據(jù)集中的target數(shù)組(數(shù)據(jù)集的類別) y_true = dataset.target # 計算每一項特征的平均值 attribute_means = X.mean(axis=0) # 與平均值比較,大于等于的為“1”,小于的為“0”.將連續(xù)性的特征值變?yōu)殡x散性的類別型。 x = np.array(X >= attribute_means, dtype="int") from sklearn.model_selection import train_test_split x_train, x_test, y_train, y_test = train_test_split(x, y_true, random_state=14) from operator import itemgetter from 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) # 接著定義一個以特征為自變量的函數(shù),找出錯誤率最低的最佳的特征,以及該特征下的各特征值所屬的類別。 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)}首先為一個字典,字典的鍵是某個特征,字典的值由一個集合構(gòu)成,這個集合又是由一個字典和一個值組成,字典的鍵是特征值,字典的值為類別,最后一個單獨的值是錯誤率。 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()} # 對錯誤率排序,得到最優(yōu)的特征和最低的錯誤率,以此為模型和規(guī)則。這就是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 # 開始測試——對最優(yōu)特征下的特征值所屬類別進行分類。 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_predictor y_predictor = predict(x_test, model) # print y_predictor # 在這個最優(yōu)特征下,各特征值的所屬類別與測試數(shù)據(jù)集相對比,得到準(zhǔn)確率。 accuracy = np.mean(y_predictor == y_test) * 100 print "The test accuracy is {0:.2f}%".format(accuracy) from sklearn.metrics import classification_report # print(classification_report(y_test, y_predictor))

總結(jié):OneR算法,我在最開始的以為它是找到一個錯誤率最低的特征之后可以判斷所有特征的分類,其實,現(xiàn)在明白它只能判斷這個特征下的各特征值的分類,所以,明顯它會有一些局限性。只是說它比較快捷也比較簡單明了。但是,還是得是情況而判斷是否使用它。

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

注: