cookiedealer
cookiedealer

Reputation: 381

Scikit-learn out-of-core text classification memory consumption

I am trying to use scikit-learn to classify a large number of text documents, although I'm using the out-of-core functionality (with SGDClassifier and HashingVectorizer) the program seems to be consuming a lot of RAM (>10GB). I performed lemmatization and removed stopwords from the text data prior to this. I feel like I am missing out something important here. Can you spot a mistake in my code?

Thank you very much for any suggestion!

This is my python code:

import time
import numpy as np
import os
import re
import pyprind
from sklearn.feature_extraction.text import HashingVectorizer
from sklearn.linear_model import SGDClassifier
from sklearn.naive_bayes import MultinomialNB
from sklearn import metrics

directory = "mydirectory"
batch_size = 1000
n_batches = 44
pbar = pyprind.ProgBar(n_batches)

class Doc_Iterable:
    def __init__(self, file):
        self.file = file
    def __iter__(self):
        for line in self.file:
            line = re.sub('[^\w\s]|(.\d{1,4}[\./]\d{1,2}[\./]\d{1,4})|(\s\d{1,})', '', line)
            yield line


def stream_docs(path, texts_file, labels_file):
    with open(path + texts_file, 'r') as fX, open(path + labels_file, 'r') as fy:
        for text in fX:
            label = next(fy)
            text = re.sub('[^\w\s]|(.\d{1,4}[\./]\d{1,2}[\./]\d{1,4})|(\s\d{1,})', '', text)
            yield text, label

def get_minibatch(doc_stream, size):
    X, y = [], []
    for _ in range(size):
        text, label = next(doc_stream)
        X.append(text)
        y.append(label)
    return X, y


classes = set()
for label in open(directory + 'y_train', 'r'):
    classes.add(label)
for label in open(directory + 'y_test', 'r'):
    classes.add(label)
classes = list(classes)

validation_scores = []
training_set_size = []

h_vectorizer = HashingVectorizer(lowercase=True, ngram_range=(1,1))
clf = SGDClassifier(loss='hinge', n_iter=5, alpha=1e-4, shuffle=True)

doc_stream = stream_docs(path=directory, texts_file='X_train', labels_file='y_train')
n_samples = 0
iteration = 0

for _ in range(n_batches):
    print("Training with batch nr.", iteration)
    iteration += 1

    X_train, y_train = get_minibatch(doc_stream, size=batch_size)

    n_samples += len(X_train)

    X_train = h_vectorizer.transform(X_train)

    clf.partial_fit(X_train, y_train, classes=classes)

    pbar.update()


del X_train
del y_train
print("Training complete. Classifier trained with " + str(n_samples) + " samples.")
print()
print("Testing...")
print()
X_test = h_vectorizer.transform(Doc_Iterable(open(directory + 'X_test')))
y_test = np.genfromtxt(directory + 'y_test', dtype=None, delimiter='|').astype(str)
prediction = clf.predict(X_test)
score = metrics.accuracy_score(y_test, prediction)
print("Accuracy: ", score)
print()

Upvotes: 3

Views: 560

Answers (2)

elyase
elyase

Reputation: 40963

Try adjusting n_features in the HashingVectorizer, for example:

h_vectorizer = HashingVectorizer(n_features=10000, lowercase=True, ngram_range=(1,1))

With the default parameters(n_features=1048576) you can expect your transformed matrix to have up to:

1048576(features) x 1000(mini batch size) x 8 bytes = 8.4 GB

It will be less than that because of sparsity but the coefficients of the classifier will add up:

1048576(features) x len(classes) * 8 bytes

so that might explain your current memory usage.

Upvotes: 3

jonilyn2730
jonilyn2730

Reputation: 475

This might not be an answer (sorry if I could not comment due to reputation issues) but I have worked on an image classification project.

Based on my experience, training using scikit-learn was very slow (in my case I used about 30 images, it took me almost 2-6 minutes to train a classifier). When I switched to OpenCV-python, it would only take me about a minute or less to train the same classifier while using the same number of training data.

Upvotes: 0

Related Questions