Python scikit-learn包 决策树和随机森林实例代码

来源:互联网 发布:数据库系统实现 ppt 编辑:程序博客网 时间:2024/05/17 08:56

决策树

从训练数据中取随机的20条作为测试数据,用决策树学习剩余的数据。再用习得的决策树预测20条测试数据的label,和原20条测试数据的label进行比对。

>>> import numpy as np>>> B_x = np.loadtxt(open("D:\Python\B_train1_P.csv","rb"),delimiter=",",skiprows=0)>>> B_y = np.loadtxt(open("D:\Python\B_train1_l_P.csv","rb"),delimiter=",",skiprows=0)>>> np.random.seed(0)>>> indices = np.random.permutation(len(B_x))>>> B_x_train = B_x[indices[:-20]]>>> B_y_train = B_y[indices[:-20]]>>> B_x_test = B_x[indices[-20:]]>>> B_y_test = B_y[indices[-20:]]>>> from sklearn import tree>>> clf = tree.DecisionTreeClassifier()>>> clf = clf.fit(B_x_train, B_y_train)>>> clf.predict(B_x_test)array([ 0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0., 0.,  0.,  0.,  0.,  0.,  0.,  0.])>>> B_y_testarray([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0., 0.,  0.,  0.,  0.,  0.,  0.,  0.])>>> clf.predict_proba(B_x_test)array([[ 1.        ,  0.        ],       [ 1.        ,  0.        ],       [ 1.        ,  0.        ],       [ 0.        ,  1.        ],       [ 1.        ,  0.        ],       [ 1.        ,  0.        ],       [ 0.91581633,  0.08418367],       [ 1.        ,  0.        ],       [ 1.        ,  0.        ],       [ 1.        ,  0.        ],       [ 0.97058824,  0.02941176],       [ 1.        ,  0.        ],       [ 1.        ,  0.        ],       [ 1.        ,  0.        ],       [ 1.        ,  0.        ],       [ 0.95145631,  0.04854369],       [ 1.        ,  0.        ],       [ 1.        ,  0.        ],       [ 1.        ,  0.        ],       [ 1.        ,  0.        ]])

关于参数

决策树的重要参数都是防止过拟合的. 有2个参数是关键:
min_samples_leaf: 这个sklearn的默认值是1,10万样本项目使用min_samples_leaf的值为5;
max_depth:这个参数控制树的规模。决策树是一个非常直观的机器学习方法。一般我们都会把它的决策树结构打印出来观察,如果深度太深对于我们的理解是有难度的。

=-=我也不知道我这4000条训练数据这两个“重要”参数该取多少。

随机森林

>>> from sklearn.ensemble import RandomForestClassifier>>> clf = RandomForestClassifier(n_estimators=10)>>> clf = clf.fit(B_x_train, B_y_train)>>> clf.predict(B_x_test)
0 0
原创粉丝点击