如何将randomforest分类器应用于所有数据集,一次在python中使用一小部分

问题描述 投票:3回答:3

所以我正在进行一场Kaggle比赛,测试数据集的大小为880,000行。我想在其10,000行部分应用随机森林分类器。但仍然适用于所有这些。 这是我的分类器的设置方式

from sklearn.ensemble import RandomForestClassifier

clf = RandomForestClassifier(n_estimators=100)
# Training data features, skip the first column 'Crime Category'
train_features = train[:, 1:]

# 'Crime Category' column values
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(“。”),我会得到一个进度条。我使用pandas将test.csv从dataframe values更改为test= test.values

我尽可能多地提供信息,如果您需要更多信息,请告诉我。

python pandas machine-learning dataset random-forest
3个回答
1
投票

使用pd.DataFrame,您可以使用新的index迭代concatDataFrame的块。对于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))])

0
投票

我假设您的索引是顺序整数...

groups = test_x.groupby(test_x.index // 10000)
groups.apply(clf.predict)

如果索引不是顺序整数,那么这是可能的......

groups = test.groupby(test.reset_index().index // 10000)

下面是一个完整的例子......

from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
import pandas as pd
import numpy as np

iris = load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)

train, test = (df[:100], df[100:])
y_train, y_test = (iris.target[:100], iris.target[100:])

clf = RandomForestClassifier()
clf.fit(train, y_train)

groups = test.groupby(test.index // 10)
groups.apply(clf.predict)

输出是Pandas系列的预测列表......

10    [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
11    [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
12    [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
13    [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
14    [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

0
投票

在2018年,来自fast.ai的fastai 0.7库有一个set_rf_samples()函数,它具有一些特殊功能。如果你登陆这个页面,强烈建议调查。您可以通过Jeremy Howard的YouTube频道的实施细节观看机器学习入门MOOC。

© www.soinside.com 2019 - 2024. All rights reserved.