RandomForest算法(有监督学习),可以根据输入数据,选择最佳特征组合,减少特征冗余;原理:由于随机决策树生成过程采用的Boostrap,所以在一棵树的生成过程并不会使用所有的样本,未使用的样本就叫(Out_of_bag)袋外样本,通过袋外样本,可以评估这个树的准确度,其他子树叶按这个原理评估,最后可以取平均值,即是随机森林算法的性能;特征选择原理:因为袋外样本的存在,因此不需要进行十字交叉测试(节省时间),通过依次对每个特征赋予一个随机数,观察算法性能的变化,倘若变化大,则说明该特征重要,sklearn中会对每个特征赋予一个分数,分数越大,特征越重要,因此,可以根据特征重要性排序,然后选择最佳特征组合;随机森林算法特征维度,不同于PCA,随机森林算法能够考虑到特征对类别的影响,而PCA是单纯的数据方差;但是随机森林的缺点是需要迭代计算,如果在大数据条件下,进行选择,就难免有点捉襟见肘了;与LDA区别在于:LDA根据标签,通过变换将同标签数据距离缩小,将累间距离方法;LDA是一种有监督方法,PCA属于无监督方法;以上是原理和一些个人见解;现在上代码;已经在工作中跑了,学了Python的应该都能看懂,只要改一下数据路径,初始特征选择数量等就可以使用,不懂的可以问我,博客会常在的, 没全部注释!还有另外一个特征选择,就是通过利用oob对每个特征,迭代进行,评估分数,然后做一个排序,分数越高,特征越重要,然后利用分数由到到低,进行组合,在看模型是否精度是否发生变化,从而选择最优特征组合,这是另一个方法,也是一下代码的由来;"""Created on Mon Mar 19 20:22:09 2018@author: testfunction: iteritor for features combintaiondate:2018/3/19"""import copyimport sysimport pandas as pdimport numpy as npfrom sklearn.ensemble import RandomForestClassifierdata = pd.read_csv(r"C:\Users\huzhipeng_sx\Desktop\data", header=None, sep='\t')y_train = data[0].valuesX_train = data.drop(0, axis=1).valuesX_train = pd.DataFrame(np.delete(X_train, -5, axis=1))features_name = ['a', 'b', 'c']rf = RandomForestClassifier(n_estimators=200, oob_score=True)rf.fit(X_train, y_train)features_imp = rf.feature_importances_X_train = X_train.as_matrix() # 输入要是数组,不然无法切片,报错slicedef select_combine(X_train, y_train, features_name, features_imp, select_num):oob_result = []fea_result = []features_imp = list(features_imp)iter_count = X_train.shape[1] - select_num # 迭代次数if iter_count < 0:print("select_nume must less or equal X_train columns")else:features_test = copy.deepcopy(features_imp) # 生成一个排序特征,进行筛选features_test.sort()features_test.reverse()while iter_count >= 0:iter_count -= 1train_index = [features_imp.index(j) for j in features_test[:select_num]]train_feature_name = [features_name[k] for k in train_index][0]train_data = X_train[:, train_index]rf.fit(train_data, y_train)acc = rf.oob_score_print(acc)oob_result.append(acc)fea_result.append(train_index)if select_num < X_train.shape[1]:select_num += 1else:breakreturn max(oob_result), oob_result, fea_result[oob_result.index(max(oob_result))]select_num = 20max_result, oob_result, fea_result = select_combine(X_train, y_train, features_name, features_imp, select_num)本文链接:https: // blog.csdn.net / zehui6202 / article / details / 79625639
来源:https://www.cnblogs.com/lvdongjie/p/11542301.html