Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Chunking implemented for Issue #67 for improved memory management #105

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 38 additions & 5 deletions mglearn/plot_2d_separator.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,39 @@
import matplotlib.pyplot as plt
from .plot_helpers import cm2, cm3, discrete_scatter

def _call_classifier_chunked(classifier_pred_or_decide, X):


# The chunk_size is used to chunk the large arrays to work with x86 memory
# models that are restricted to < 2 GB in memory allocation.
# The chunk_size value used here is based on a measurement with the MLPClassifier
# using the following parameters:
# MLPClassifier(solver='lbfgs', random_state=0, hidden_layer_sizes=[1000,1000,1000])
# by reducing the value it is possible to trade in time for memory.
# It is possible to chunk the array as the calculations are independent of each other.
# Note: an intermittent version made a distinction between 32- and 64 bit architectures
# avoiding the chunking. Testing revealed that even on 64 bit architectures the chunking
# increases the performance by a factor of 3-5, probably due to the avoidance of memory
# swapping.
chunk_size = 10000
X_axis0_size = X.shape[0]

# Pre-allocate the entire result set to avoid array copying for efficiency.
# As we do not know the shape of the output, as it depends on whether a
# decision function or the predict probability is called, we simply test the output
# size for a single sample and use the shape of the output
Y_result = np.empty((X_axis0_size,) + classifier_pred_or_decide(X[0:1]).shape[1:])
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we don't need to do that. The time it takes to allocate these is so small that it doesn't really matter.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I just saw your comment re seasoned assembly programmer.
The reason I don't want to optimize here is the cost of maintenance vs speed.
Reallocating is clearly slower, but I'm pretty sure it's imperceptibly slower, and the code using pre-allocation is quite a bit more complex and more likely to introduce bugs, and harder to modify.
I imagine the python community makes a different trade-off between readability and speed here than the assembly community ;)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the feedback!
Sorry the explanation wasn't very clear. It is not about the pre-allocation of the Y_result versus the allocation of the loop_times individual result chunks; I agree this is not making a difference at all.
It is about concatenation of the incremental growing result set and copying the data as each loop iteration using something like:
y_result = np.stack((y_result, y_chunk))
This allocates the memory and copies the data each loop iteration. For larger data sets for which I tried it is an order of magnitude slower 10 seconds vs 100 seconds. I thought this would justify this.
I got the pre-allocation actually from a Python recipe - in assembler it would look very different ;)

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would not grow in each iteration but only call stack once in the end. That should reduce the memory allocated and I would be surprised if that impacted the runtime that much - though I could be wrong of course.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll write the version without the pre-allocation and will test it. ... let you know.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Below is the performance evaluation of the current HEAD and the two alternatives.
In summary:
There is a significant performance advantage in terms of memory and execution time compared to the current master.
The advantage for the pre-allocation is minimal / hardly measurable. Hence I submit a new PR for the change code, which is slightly more readable. Please close this one.

*** Performance evaluation for:
MLPClassifier(solver='lbfgs', random_state=0, hidden_layer_sizes=[1000, 1000, 1000])
runtime is in seconds

Current HEAD:

(32bit architecture) - Out of Memory Error
Ran 3 Iterations: Average runtime: 361.9377431869507 - standard deviation: 0.84561111123 (64bit architecture) - 36 GB Memory Allocated

bug_32bit_out_of_memory (pre-allocation of result set) (This PR)

Ran 3 Iterations: Average runtime: 151.96799866358438 - standard deviation: 0.5428240156760912 (32bit architecture) - ~1 GB Memory Allocated
Ran 3 Iterations: Average runtime: 103.92718044916789 - standard deviation: 0.3448667233842946 (64bit architecture) - ~1 GB Memory Allocated

bug_32bit_out_of_memory_v2 (accumulation of result set)

Ran 3 Iterations: Average runtime: 152.8699369430542 - standard deviation: 0.6673264039615153 (32bit architecture) - ~1 GB Memory Allocated
Ran 3 Iterations: Average runtime: 104.28479194641113 - standard deviation: 0.430773539134181 (64bit architecture) - ~1 GB Memory Allocated


# Call the classifier in chunks.
y_chunk_pos = 0
for x_chunk in np.array_split(X, np.arange(chunk_size,X_axis0_size,chunk_size,dtype=np.int32), axis=0):
Y_result[y_chunk_pos:y_chunk_pos + x_chunk.shape[0]] = classifier_pred_or_decide(x_chunk)

y_chunk_pos += x_chunk.shape[0]

return Y_result



def plot_2d_classification(classifier, X, fill=False, ax=None, eps=None,
alpha=1, cm=cm3):
Expand Down Expand Up @@ -82,14 +115,14 @@ def plot_2d_separator(classifier, X, fill=False, ax=None, eps=None, alpha=1,

X1, X2 = np.meshgrid(xx, yy)
X_grid = np.c_[X1.ravel(), X2.ravel()]
try:
decision_values = classifier.decision_function(X_grid)
if hasattr(classifier, "decision_function"):
decision_values = _call_classifier_chunked(classifier.decision_function, X_grid)
levels = [0] if threshold is None else [threshold]
fill_levels = [decision_values.min()] + levels + [
decision_values.max()]
except AttributeError:
else:
# no decision_function
decision_values = classifier.predict_proba(X_grid)[:, 1]
decision_values = _call_classifier_chunked(classifier.predict_proba, X_grid)[:, 1]
levels = [.5] if threshold is None else [threshold]
fill_levels = [0] + levels + [1]
if fill:
Expand All @@ -110,7 +143,7 @@ def plot_2d_separator(classifier, X, fill=False, ax=None, eps=None, alpha=1,
from sklearn.datasets import make_blobs
from sklearn.linear_model import LogisticRegression
X, y = make_blobs(centers=2, random_state=42)
clf = LogisticRegression().fit(X, y)
clf = LogisticRegression(solver = 'liblinear').fit(X, y)
plot_2d_separator(clf, X, fill=True)
discrete_scatter(X[:, 0], X[:, 1], y)
plt.show()