Search is not available for this dataset
text stringlengths 75 104k |
|---|
def save(self, storage, folder=None, name=None):
"""
This saves a `werkzeug.FileStorage` into this upload set. If the
upload is not allowed, an `UploadNotAllowed` error will be raised.
Otherwise, the file will be saved and its name (including the folder)
will be returned.
... |
def resolve_conflict(self, target_folder, basename):
"""
If a file with the selected name already exists in the target folder,
this method is called to resolve the conflict. It should return a new
basename for the file.
The default implementation splits the name and extension an... |
def get_vprof_version(filename):
"""Returns actual version specified in filename."""
with open(filename) as src_file:
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
src_file.read(), re.M)
if version_match:
return version_match.group... |
def _remove_duplicates(objects):
"""Removes duplicate objects.
http://www.peterbe.com/plog/uniqifiers-benchmark.
"""
seen, uniq = set(), []
for obj in objects:
obj_id = id(obj)
if obj_id in seen:
continue
seen.add(obj_id)
uniq.append(obj)
return uniq |
def _get_obj_count_difference(objs1, objs2):
"""Returns count difference in two collections of Python objects."""
clean_obj_list1 = _process_in_memory_objects(objs1)
clean_obj_list2 = _process_in_memory_objects(objs2)
obj_count_1 = _get_object_count_by_type(clean_obj_list1)
obj_count_2 = _get_object... |
def _format_obj_count(objects):
"""Formats object count."""
result = []
regex = re.compile(r'<(?P<type>\w+) \'(?P<name>\S+)\'>')
for obj_type, obj_count in objects.items():
if obj_count != 0:
match = re.findall(regex, repr(obj_type))
if match:
obj_type, ob... |
def _trace_memory_usage(self, frame, event, arg): #pylint: disable=unused-argument
"""Checks memory usage when 'line' event occur."""
if event == 'line' and frame.f_code.co_filename in self.target_modules:
self._events_list.append(
(frame.f_lineno, self._process.memory_info(... |
def code_events(self):
"""Returns processed memory usage."""
if self._resulting_events:
return self._resulting_events
for i, (lineno, mem, func, fname) in enumerate(self._events_list):
mem_in_mb = float(mem - self.mem_overhead) / _BYTES_IN_MB
if (self._resulti... |
def obj_overhead(self):
"""Returns all objects that are considered a profiler overhead.
Objects are hardcoded for convenience.
"""
overhead = [
self,
self._resulting_events,
self._events_list,
self._process
]
overhead_count ... |
def compute_mem_overhead(self):
"""Returns memory overhead."""
self.mem_overhead = (self._process.memory_info().rss -
builtins.initial_rss_size) |
def profile_package(self):
"""Returns memory stats for a package."""
target_modules = base_profiler.get_pkg_module_names(self._run_object)
try:
with _CodeEventsTracker(target_modules) as prof:
prof.compute_mem_overhead()
runpy.run_path(self._run_object... |
def profile_module(self):
"""Returns memory stats for a module."""
target_modules = {self._run_object}
try:
with open(self._run_object, 'rb') as srcfile,\
_CodeEventsTracker(target_modules) as prof:
code = compile(srcfile.read(), self._run_object, 'exe... |
def profile_function(self):
"""Returns memory stats for a function."""
target_modules = {self._run_object.__code__.co_filename}
with _CodeEventsTracker(target_modules) as prof:
prof.compute_mem_overhead()
result = self._run_object(*self._run_args, **self._run_kwargs)
... |
def run(self):
"""Collects memory stats for specified Python program."""
existing_objects = _get_in_memory_objects()
prof, result = self.profile()
new_objects = _get_in_memory_objects()
new_obj_count = _get_obj_count_difference(new_objects, existing_objects)
result_obj_c... |
def get_pkg_module_names(package_path):
"""Returns module filenames from package.
Args:
package_path: Path to Python package.
Returns:
A set of module filenames.
"""
module_names = set()
for fobj, modname, _ in pkgutil.iter_modules(path=[package_path]):
filename = os.pat... |
def run_in_separate_process(func, *args, **kwargs):
"""Runs function in separate process.
This function is used instead of a decorator, since Python multiprocessing
module can't serialize decorated function on all platforms.
"""
manager = multiprocessing.Manager()
manager_dict = manager.dict()
... |
def get_run_object_type(run_object):
"""Determines run object type."""
if isinstance(run_object, tuple):
return 'function'
run_object, _, _ = run_object.partition(' ')
if os.path.isdir(run_object):
return 'package'
return 'module' |
def init_module(self, run_object):
"""Initializes profiler with a module."""
self.profile = self.profile_module
self._run_object, _, self._run_args = run_object.partition(' ')
self._object_name = '%s (module)' % self._run_object
self._globs = {
'__file__': self._run_o... |
def init_package(self, run_object):
"""Initializes profiler with a package."""
self.profile = self.profile_package
self._run_object, _, self._run_args = run_object.partition(' ')
self._object_name = '%s (package)' % self._run_object
self._replace_sysargs() |
def init_function(self, run_object):
"""Initializes profiler with a function."""
self.profile = self.profile_function
self._run_object, self._run_args, self._run_kwargs = run_object
filename = inspect.getsourcefile(self._run_object)
self._object_name = '%s @ %s (function)' % (
... |
def _replace_sysargs(self):
"""Replaces sys.argv with proper args to pass to script."""
sys.argv[:] = [self._run_object]
if self._run_args:
sys.argv += self._run_args.split() |
def sample(self, signum, frame): #pylint: disable=unused-argument
"""Samples current stack and adds result in self._stats.
Args:
signum: Signal that activates handler.
frame: Frame on top of the stack when signal is handled.
"""
stack = []
while frame an... |
def _insert_stack(stack, sample_count, call_tree):
"""Inserts stack into the call tree.
Args:
stack: Call stack.
sample_count: Sample count of call stack.
call_tree: Call tree.
"""
curr_level = call_tree
for func in stack:
next_lev... |
def _fill_sample_count(self, node):
"""Counts and fills sample counts inside call tree."""
node['sampleCount'] += sum(
self._fill_sample_count(child) for child in node['children'])
return node['sampleCount'] |
def _format_tree(self, node, total_samples):
"""Reformats call tree for the UI."""
funcname, filename, _ = node['stack']
sample_percent = self._get_percentage(
node['sampleCount'], total_samples)
color_hash = base_profiler.hash_name('%s @ %s' % (funcname, filename))
r... |
def call_tree(self):
"""Returns call tree."""
call_tree = {'stack': 'base', 'sampleCount': 0, 'children': []}
for stack, sample_count in self._stats.items():
self._insert_stack(reversed(stack), sample_count, call_tree)
self._fill_sample_count(call_tree)
if not call_tr... |
def _profile_package(self):
"""Runs statistical profiler on a package."""
with _StatProfiler() as prof:
prof.base_frame = inspect.currentframe()
try:
runpy.run_path(self._run_object, run_name='__main__')
except SystemExit:
pass
... |
def _profile_module(self):
"""Runs statistical profiler on a module."""
with open(self._run_object, 'rb') as srcfile, _StatProfiler() as prof:
code = compile(srcfile.read(), self._run_object, 'exec')
prof.base_frame = inspect.currentframe()
try:
exec(c... |
def profile_function(self):
"""Runs statistical profiler on a function."""
with _StatProfiler() as prof:
result = self._run_object(*self._run_args, **self._run_kwargs)
call_tree = prof.call_tree
return {
'objectName': self._object_name,
'sampleInterva... |
def _transform_stats(prof):
"""Processes collected stats for UI."""
records = []
for info, params in prof.stats.items():
filename, lineno, funcname = info
cum_calls, num_calls, time_per_call, cum_time, _ = params
if prof.total_tt == 0:
percenta... |
def _profile_package(self):
"""Runs cProfile on a package."""
prof = cProfile.Profile()
prof.enable()
try:
runpy.run_path(self._run_object, run_name='__main__')
except SystemExit:
pass
prof.disable()
prof_stats = pstats.Stats(prof)
... |
def _profile_module(self):
"""Runs cProfile on a module."""
prof = cProfile.Profile()
try:
with open(self._run_object, 'rb') as srcfile:
code = compile(srcfile.read(), self._run_object, 'exec')
prof.runctx(code, self._globs, None)
except SystemExit... |
def profile_function(self):
"""Runs cProfile on a function."""
prof = cProfile.Profile()
prof.enable()
result = self._run_object(*self._run_args, **self._run_kwargs)
prof.disable()
prof_stats = pstats.Stats(prof)
prof_stats.calc_callees()
return {
... |
def init_db():
"""Initializes DB."""
with contextlib.closing(connect_to_db()) as db:
db.cursor().executescript(DB_SCHEMA)
db.commit() |
def show_guestbook():
"""Returns all existing guestbook records."""
cursor = flask.g.db.execute(
'SELECT name, message FROM entry ORDER BY id DESC;')
entries = [{'name': row[0], 'message': row[1]} for row in cursor.fetchall()]
return jinja2.Template(LAYOUT).render(entries=entries) |
def add_entry():
"""Adds single guestbook record."""
name, msg = flask.request.form['name'], flask.request.form['message']
flask.g.db.execute(
'INSERT INTO entry (name, message) VALUES (?, ?)', (name, msg))
flask.g.db.commit()
return flask.redirect('/') |
def profiler_handler(uri):
"""Profiler handler."""
# HTTP method should be GET.
if uri == 'main':
runner.run(show_guestbook, 'cmhp')
# In this case HTTP method should be POST singe add_entry uses POST
elif uri == 'add':
runner.run(add_entry, 'cmhp')
return flask.redirect('/') |
def start(host, port, profiler_stats, dont_start_browser, debug_mode):
"""Starts HTTP server with specified parameters.
Args:
host: Server host name.
port: Server port.
profiler_stats: A dict with collected program stats.
dont_start_browser: Whether to open browser after profili... |
def _handle_root():
"""Handles index.html requests."""
res_filename = os.path.join(
os.path.dirname(__file__), _PROFILE_HTML)
with io.open(res_filename, 'rb') as res_file:
content = res_file.read()
return content, 'text/html' |
def _handle_other(self):
"""Handles static files requests."""
res_filename = os.path.join(
os.path.dirname(__file__), _STATIC_DIR, self.path[1:])
with io.open(res_filename, 'rb') as res_file:
content = res_file.read()
_, extension = os.path.splitext(self.path)
... |
def do_GET(self):
"""Handles HTTP GET requests."""
handler = self.uri_map.get(self.path) or self._handle_other
content, content_type = handler()
compressed_content = gzip.compress(content)
self._send_response(
200, headers=(('Content-type', '%s; charset=utf-8' % conte... |
def do_POST(self):
"""Handles HTTP POST requests."""
post_data = self.rfile.read(int(self.headers['Content-Length']))
json_data = gzip.decompress(post_data)
self._profile_json.update(json.loads(json_data.decode('utf-8')))
self._send_response(
200, headers=(('Content-t... |
def _send_response(self, http_code, message=None, headers=None):
"""Sends HTTP response code, message and headers."""
self.send_response(http_code, message)
if headers:
for header in headers:
self.send_header(*header)
self.end_headers() |
def main():
"""Main function of the module."""
parser = argparse.ArgumentParser(
prog=_PROGRAN_NAME, description=_MODULE_DESC,
formatter_class=argparse.RawTextHelpFormatter)
launch_modes = parser.add_mutually_exclusive_group(required=True)
launch_modes.add_argument('-r', '--remote', dest... |
def check_standard_dir(module_path):
"""Checks whether path belongs to standard library or installed modules."""
if 'site-packages' in module_path:
return True
for stdlib_path in _STDLIB_PATHS:
if fnmatch.fnmatchcase(module_path, stdlib_path + '*'):
return True
return False |
def record_line(self, frame, event, arg): # pylint: disable=unused-argument
"""Records line execution time."""
if event == 'line':
if self.prev_timestamp:
runtime = time.time() - self.prev_timestamp
self.lines.append([self.prev_path, self.prev_lineno, runtime... |
def lines_without_stdlib(self):
"""Filters code from standard library from self.lines."""
prev_line = None
current_module_path = inspect.getabsfile(inspect.currentframe())
for module_path, lineno, runtime in self.lines:
module_abspath = os.path.abspath(module_path)
... |
def fill_heatmap(self):
"""Fills code heatmap and execution count dictionaries."""
for module_path, lineno, runtime in self.lines_without_stdlib:
self._execution_count[module_path][lineno] += 1
self._heatmap[module_path][lineno] += runtime |
def _calc_skips(self, heatmap, num_lines):
"""Calculates skip map for large sources.
Skip map is a list of tuples where first element of tuple is line
number and second is length of the skip region:
[(1, 10), (15, 10)] means skipping 10 lines after line 1 and
10 lines aft... |
def _skip_lines(src_code, skip_map):
"""Skips lines in src_code specified by skip map."""
if not skip_map:
return [['line', j + 1, l] for j, l in enumerate(src_code)]
code_with_skips, i = [], 0
for line, length in skip_map:
code_with_skips.extend(
... |
def _profile_package(self):
"""Calculates heatmap for package."""
with _CodeHeatmapCalculator() as prof:
try:
runpy.run_path(self._run_object, run_name='__main__')
except SystemExit:
pass
heatmaps = []
for filename, heatmap in prof... |
def _format_heatmap(self, filename, heatmap, execution_count):
"""Formats heatmap for UI."""
with open(filename) as src_file:
file_source = src_file.read().split('\n')
skip_map = self._calc_skips(heatmap, len(file_source))
run_time = sum(time for time in heatmap.values())... |
def _profile_module(self):
"""Calculates heatmap for module."""
with open(self._run_object, 'r') as srcfile:
src_code = srcfile.read()
code = compile(src_code, self._run_object, 'exec')
try:
with _CodeHeatmapCalculator() as prof:
exec(code, sel... |
def profile_function(self):
"""Calculates heatmap for function."""
with _CodeHeatmapCalculator() as prof:
result = self._run_object(*self._run_args, **self._run_kwargs)
code_lines, start_line = inspect.getsourcelines(self._run_object)
source_lines = []
for line in co... |
def run_profilers(run_object, prof_config, verbose=False):
"""Runs profilers on run_object.
Args:
run_object: An object (string or tuple) for profiling.
prof_config: A string with profilers configuration.
verbose: True if info about running profilers should be shown.
Returns:
... |
def run(func, options, args=(), kwargs={}, host='localhost', port=8000): # pylint: disable=dangerous-default-value
"""Runs profilers on a function.
Args:
func: A Python function.
options: A string with profilers configuration (i.e. 'cmh').
args: func non-keyword arguments.
kwar... |
def predict_proba(self, X):
"""
Return probability estimates for the RDD containing test vector X.
Parameters
----------
X : RDD containing array-like items, shape = [m_samples, n_features]
Returns
-------
C : RDD with array-like items , shape = [n_sampl... |
def predict_log_proba(self, X):
"""
Return log-probability estimates for the RDD containing the
test vector X.
Parameters
----------
X : RDD containing array-like items, shape = [m_samples, n_features]
Returns
-------
C : RDD with array-like item... |
def fit(self, Z, classes=None):
"""Fit Gaussian Naive Bayes according to X, y
Parameters
----------
X : array-like, shape (n_samples, n_features)
Training vectors, where n_samples is the number of samples
and n_features is the number of features.
y : arr... |
def fit(self, Z, classes=None):
"""
TODO fulibacsi fix docstring
Fit Multinomial Naive Bayes according to (X,y) pair
which is zipped into TupleRDD Z.
Parameters
----------
Z : TupleRDD containing X [array-like, shape (m_samples, n_features)]
and y [ar... |
def _init_vocab(self, analyzed_docs):
"""Create vocabulary
"""
class SetAccum(AccumulatorParam):
def zero(self, initialValue):
return set(initialValue)
def addInPlace(self, v1, v2):
v1 |= v2
return v1
if not self.... |
def _count_vocab(self, analyzed_docs):
"""Create sparse feature matrix, and vocabulary where fixed_vocab=False
"""
vocabulary = self.vocabulary_
j_indices = _make_int_array()
indptr = _make_int_array()
indptr.append(0)
for doc in analyzed_docs:
for fea... |
def _sort_features(self, vocabulary):
"""Sort features by name
Returns a reordered matrix and modifies the vocabulary in place
"""
sorted_features = sorted(six.iteritems(vocabulary))
map_index = np.empty(len(sorted_features), dtype=np.int32)
for new_val, (term, old_val) ... |
def _limit_features(self, X, vocabulary, high=None, low=None,
limit=None):
"""Remove too rare or too common features.
Prune features that are non zero in more samples than high or less
documents than low, modifying the vocabulary, and restricting it to
at most th... |
def fit_transform(self, Z):
"""Learn the vocabulary dictionary and return term-document matrix.
This is equivalent to fit followed by transform, but more efficiently
implemented.
Parameters
----------
Z : iterable or DictRDD with column 'X'
An iterable of ra... |
def transform(self, Z):
"""Transform documents to document-term matrix.
Extract token counts out of raw text documents using the vocabulary
fitted with fit or the one provided to the constructor.
Parameters
----------
raw_documents : iterable
An iterable whi... |
def transform(self, Z):
"""Transform an ArrayRDD (or DictRDD with column 'X') containing
sequence of documents to a document-term matrix.
Parameters
----------
Z : ArrayRDD or DictRDD with raw text documents
Samples. Each sample must be a text document (either bytes ... |
def fit(self, Z):
"""Learn the idf vector (global term weights)
Parameters
----------
Z : ArrayRDD or DictRDD containing (sparse matrices|ndarray)
a matrix of term/token counts
Returns
-------
self : TfidfVectorizer
"""
X = Z[:, 'X']... |
def fit(self, Z):
"""Compute the mean and std to be used for later scaling.
Parameters
----------
Z : DictRDD containing (X, y) pairs
X - Training vector.
{array-like, sparse matrix}, shape [n_samples, n_features]
The data used to compute the m... |
def transform(self, Z):
"""Perform standardization by centering and scaling
Parameters
----------
Z : DictRDD containing (X, y) pairs
X - Training vector
y - Target labels
Returns
-------
C : DictRDD containing (X, y) pairs
X - ... |
def to_scikit(self):
"""
Convert to equivalent StandardScaler
"""
scaler = StandardScaler(with_mean=self.with_mean,
with_std=self.with_std,
copy=self.copy)
scaler.__dict__ = self.__dict__
return scaler |
def _spark_fit(self, cls, Z, *args, **kwargs):
"""Wraps a Scikit-learn Linear model's fit method to use with RDD
input.
Parameters
----------
cls : class object
The sklearn linear model's class to wrap.
Z : TupleRDD or DictRDD
The distributed trai... |
def _spark_predict(self, cls, X, *args, **kwargs):
"""Wraps a Scikit-learn Linear model's predict method to use with RDD
input.
Parameters
----------
cls : class object
The sklearn linear model's class to wrap.
Z : ArrayRDD
The distributed data to... |
def fit(self, Z):
"""
Fit linear model.
Parameters
----------
Z : DictRDD with (X, y) values
X containing numpy array or sparse matrix - The training data
y containing the target values
Returns
-------
self : returns an instance o... |
def fit(self, Z, **fit_params):
"""Fit all the transforms one after the other and transform the
data, then fit the transformed data using the final estimator.
Parameters
----------
Z : ArrayRDD, TupleRDD or DictRDD
Input data in blocked distributed format.
R... |
def fit_transform(self, Z, **fit_params):
"""Fit all the transforms one after the other and transform the
data, then use fit_transform on transformed data using the final
estimator."""
Zt, fit_params = self._pre_transform(Z, **fit_params)
if hasattr(self.steps[-1][-1], 'fit_trans... |
def score(self, Z):
"""Applies transforms to the data, and the score method of the
final estimator. Valid only if the final estimator implements
score."""
Zt = Z
for name, transform in self.steps[:-1]:
Zt = transform.transform(Zt)
return self.steps[-1][-1].sco... |
def fit(self, Z, **fit_params):
"""TODO: rewrite docstring
Fit all transformers using X.
Parameters
----------
X : array-like or sparse matrix, shape (n_samples, n_features)
Input data, used to fit transformers.
"""
fit_params_steps = dict((step, {})
... |
def fit_transform(self, Z, **fit_params):
"""TODO: rewrite docstring
Fit all transformers using X, transform the data and concatenate
results.
Parameters
----------
X : array-like or sparse matrix, shape (n_samples, n_features)
Input data to be transformed.
... |
def transform(self, Z):
"""TODO: rewrite docstring
Transform X separately by each transformer, concatenate results.
Parameters
----------
X : array-like or sparse matrix, shape (n_samples, n_features)
Input data to be transformed.
Returns
-------
... |
def fit(self, Z, classes=None):
"""Fit the model according to the given training data.
Parameters
----------
Z : DictRDD containing (X, y) pairs
X - Training vector
y - Target labels
classes : iterable
The set of available classes
Ret... |
def _fit(self, Z, parameter_iterable):
"""Actual fitting, performing the search over parameters."""
self.scorer_ = check_scoring(self.estimator, scoring=self.scoring)
cv = self.cv
cv = _check_cv(cv, Z)
if self.verbose > 0:
if isinstance(parameter_iterable, Sized):
... |
def fit(self, y):
"""Fit label encoder
Parameters
----------
y : ArrayRDD (n_samples,)
Target values.
Returns
-------
self : returns an instance of self.
"""
def mapper(y):
y = column_or_1d(y, warn=True)
_check_... |
def transform(self, y):
"""Transform labels to normalized encoding.
Parameters
----------
y : ArrayRDD [n_samples]
Target values.
Returns
-------
y : ArrayRDD [n_samples]
"""
mapper = super(SparkLabelEncoder, self).transform
map... |
def _score(estimator, Z_test, scorer):
"""Compute the score of an estimator on a given test set."""
score = scorer(estimator, Z_test)
if not isinstance(score, numbers.Number):
raise ValueError("scoring must return a number, got %s (%s) instead."
% (str(score), type(score)))
... |
def fit(self, Z):
"""Compute k-means clustering.
Parameters
----------
Z : ArrayRDD or DictRDD containing array-like or sparse matrix
Train data.
Returns
-------
self
"""
X = Z[:, 'X'] if isinstance(Z, DictRDD) else Z
check_rd... |
def predict(self, X):
"""Predict the closest cluster each sample in X belongs to.
In the vector quantization literature, `cluster_centers_` is called
the code book and each value returned by `predict` is the index of
the closest code in the code book.
Parameters
-------... |
def fit(self, Z, classes=None):
"""Fit the model according to the given training data.
Parameters
----------
Z : DictRDD containing (X, y) pairs
X - Training vector
y - Target labels
classes : iterable
The set of available classes
Ret... |
def predict(self, X):
"""Distributed method to predict class labels for samples in X.
Parameters
----------
X : ArrayRDD containing {array-like, sparse matrix}
Samples.
Returns
-------
C : ArrayRDD
Predicted class label per sample.
... |
def check_rdd_dtype(rdd, expected_dtype):
"""Checks if the blocks in the RDD matches the expected types.
Parameters:
-----------
rdd: splearn.BlockRDD
The RDD to check
expected_dtype: {type, list of types, tuple of types, dict of types}
Expected type(s). If the RDD is a DictRDD the ... |
def fit(self, Z):
"""Learn a list of feature name -> indices mappings.
Parameters
----------
Z : DictRDD with column 'X'
Dict(s) or Mapping(s) from feature names (arbitrary Python
objects) to feature values (strings or convertible to dtype).
Returns
... |
def transform(self, Z):
"""Transform ArrayRDD's (or DictRDD's 'X' column's) feature->value dicts
to array or sparse matrix.
Named features not encountered during fit or fit_transform will be
silently ignored.
Parameters
----------
Z : ArrayRDD or DictRDD with col... |
def fit(self, Z):
"""Learn empirical variances from X.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Sample vectors from which to compute variances.
y : any
Ignored. This parameter exists only for compatibility with... |
def svd(blocked_rdd, k):
"""
Calculate the SVD of a blocked RDD directly, returning only the leading k
singular vectors. Assumes n rows and d columns, efficient when n >> d
Must be able to fit d^2 within the memory of a single machine.
Parameters
----------
blocked_rdd : RDD
RDD with... |
def svd_em(blocked_rdd, k, maxiter=20, tol=1e-6, compute_u=True, seed=None):
"""
Calculate the SVD of a blocked RDD using an expectation maximization
algorithm (from Roweis, NIPS, 1997) that avoids explicitly
computing the covariance matrix, returning only the leading k
singular vectors. Assumes n r... |
def fit_transform(self, Z):
"""Fit LSI model to X and perform dimensionality reduction on X.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Training data.
Returns
-------
X_new : array, shape (n_samples, n_compon... |
def transform(self, Z):
"""Perform dimensionality reduction on X.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
New data.
Returns
-------
X_new : array, shape (n_samples, n_components)
Reduced versio... |
def _block_collection(iterator, dtype, bsize=-1):
"""Pack rdd with a specific collection constructor."""
i = 0
accumulated = []
for a in iterator:
if (bsize > 0) and (i >= bsize):
yield _pack_accumulated(accumulated, dtype)
accumulated = []
i = 0
accum... |
def _block_tuple(iterator, dtypes, bsize=-1):
"""Pack rdd of tuples as tuples of arrays or scipy.sparse matrices."""
i = 0
blocked_tuple = None
for tuple_i in iterator:
if blocked_tuple is None:
blocked_tuple = tuple([] for _ in range(len(tuple_i)))
if (bsize > 0) and (i >= ... |
def block(rdd, bsize=-1, dtype=None):
"""Block an RDD
Parameters
----------
rdd : RDD
RDD of data points to block into either numpy arrays,
scipy sparse matrices, or pandas data frames.
Type of data point will be automatically inferred
and blocked accordingly.
bsiz... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.