我需要使用从1到50不同数量的树来训练随机森林,并使用5个区块的交叉验证来验证创建的随机森林的质量,采用(r2)度量标准。
我想创建一个具有两列的数组(类似于表格),第一列我可以放置从1到50的树的数量,另一列我可以放入r2度量值。
我写了如下代码:
z = np.linspace(1.0, 50.0, num=50) # 生成从1到50的树的数量Z = np.array(z)P_scores = [Z,]z1 = 1while z1 < len(Z): clf = RandomForestRegressor(n_estimators=z1, random_state=1) clf.fit(X, Y) kf = KFold(len(X), n_folds=5, random_state=1, shuffle=True) R2 = cross_val_score(clf, X, Y, cv=kf, n_jobs=-1, scoring='r2') P_scores.append(R2) z1 += 1print(P_scores)
然而,结果看起来与我预期的相差甚远:
[array([ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14., 15., 16., 17., 18., 19., 20., 21., 22., 23., 24., 25., 26., 27., 28., 29., 30., 31., 32., 33., 34., 35., 36., 37., 38., 39., 40., 41., 42., 43., 44., 45., 46., 47., 48., 49., 50.]), array([ 0.18870118, 0.11762437, 0.23292905, 0.01941026, -0.04797139])]
我至少期望r2项的数组会更长(因为对于每棵树应该生成5个交叉验证的r2值,5*50=250)
我如何创建一个两列或六列的数组来存储我的估计结果?
回答:
您错误地使用了while循环
。您当前的代码只循环了49
次。此外,您没有正确地追加P_scores
。除此之外,代码的执行符合预期。您需要按如下方式更改代码:
P_scores = []z1 = 1# 这个循环将执行50次while z1 <= 50: clf = RandomForestRegressor(n_estimators=z1, random_state=1) clf.fit(X, Y) kf = KFold(len(X), n_folds=5, random_state=1, shuffle=True) R2 = cross_val_score(clf, X, Y, cv=kf, n_jobs=-1, scoring='r2') # 这将把索引z1和该索引的分数作为元组追加到P_scores数组中 # 每个R2数组将有5个元素(区块数量) # 因此总共有250个分数(如您所希望的) P_scores.append((z1,R2)) z1 += 1print(P_scores)