我在参加Kaggle竞赛,测试数据集有880,000行。我想对其中的每10,000行应用随机森林分类器,但最终要覆盖整个数据集。
以下是我的分类器设置:
from sklearn.ensemble import RandomForestClassifier
clf = RandomForestClassifier(n_estimators=100)
# 训练数据特征,跳过第一列'Crime Category'
train_features = train[:, 1:]
# 'Crime Category'列的值
train_target = train[:, 0]
clf = clf.fit(train_features, train_target)
score = clf.score(train_features, train_target)
"Mean accuracy of Random Forest: {0}".format(score)
我用这个来训练模型并获取准确率。我把训练数据缩小了,这样可以更快地得到结果。但为了提交到Kaggle,我需要预测测试数据。基本上我想这样做:
test_x = testing_data[:, 1:]
print('-',*38)
for every 10,000 rows in test_x
test_ y = clf.predict(value)
print(".")
add the values to an array then do the next 10,000 rows
我想对每10,000行进行预测,将预测值存储起来,然后处理接下来的10,000行。每当我一次处理所有880,000行时,我的电脑就会卡住。我希望通过每次处理10,000行并使用print(“.”)来显示进度条。我已经将test.csv从pandas
的dataframe
转换为values
,使用了test= test.values
。
我尽可能提供了详细信息,如果你需要更多信息,请告诉我。
回答:
使用pd.DataFrame
,你可以遍历index
的块,并使用新的DataFrame
通过concat
合并结果。对于np.array
,使用np.array_split
。
def chunks(l, n):
""" Yield successive n-sized chunks from l."""
for i in range(0, len(l), n):
yield l[i:i + n]
test_x = pd.DataFrame(test_x)
test_result = pd.DataFrame()
for chunk in chunks(test_x.index, 10000):
test_data = test_x.ix[chunk]
test_result = pd.concat([test_result, pd.DataFrame(clf.predict(test_data))])