Dataset Viewer
Auto-converted to Parquet Duplicate
Code
stringlengths
103
85.9k
Summary
sequencelengths
0
94
Please provide a description of the function:def train(train_dir, model_save_path=None, n_neighbors=None, knn_algo='ball_tree', verbose=False): X = [] y = [] # Loop through each person in the training set for class_dir in os.listdir(train_dir): if not os.path.isdir(os.path.join(train_dir, ...
[ "\n Trains a k-nearest neighbors classifier for face recognition.\n\n :param train_dir: directory that contains a sub-directory for each known person, with its name.\n\n (View in source code to see train_dir example tree structure)\n\n Structure:\n <train_dir>/\n ├── <person1>/\n ...
Please provide a description of the function:def predict(X_img_path, knn_clf=None, model_path=None, distance_threshold=0.6): if not os.path.isfile(X_img_path) or os.path.splitext(X_img_path)[1][1:] not in ALLOWED_EXTENSIONS: raise Exception("Invalid image path: {}".format(X_img_path)) if knn_clf i...
[ "\n Recognizes faces in given image using a trained KNN classifier\n\n :param X_img_path: path to image to be recognized\n :param knn_clf: (optional) a knn classifier object. if not specified, model_save_path must be specified.\n :param model_path: (optional) path to a pickled knn classifier. if not spe...
Please provide a description of the function:def show_prediction_labels_on_image(img_path, predictions): pil_image = Image.open(img_path).convert("RGB") draw = ImageDraw.Draw(pil_image) for name, (top, right, bottom, left) in predictions: # Draw a box around the face using the Pillow module ...
[ "\n Shows the face recognition results visually.\n\n :param img_path: path to image to be recognized\n :param predictions: results of the predict function\n :return:\n " ]
Please provide a description of the function:def _rect_to_css(rect): return rect.top(), rect.right(), rect.bottom(), rect.left()
[ "\n Convert a dlib 'rect' object to a plain tuple in (top, right, bottom, left) order\n\n :param rect: a dlib 'rect' object\n :return: a plain tuple representation of the rect in (top, right, bottom, left) order\n " ]
Please provide a description of the function:def _trim_css_to_bounds(css, image_shape): return max(css[0], 0), min(css[1], image_shape[1]), min(css[2], image_shape[0]), max(css[3], 0)
[ "\n Make sure a tuple in (top, right, bottom, left) order is within the bounds of the image.\n\n :param css: plain tuple representation of the rect in (top, right, bottom, left) order\n :param image_shape: numpy shape of the image array\n :return: a trimmed plain tuple representation of the rect in (to...
Please provide a description of the function:def face_distance(face_encodings, face_to_compare): if len(face_encodings) == 0: return np.empty((0)) return np.linalg.norm(face_encodings - face_to_compare, axis=1)
[ "\n Given a list of face encodings, compare them to a known face encoding and get a euclidean distance\n for each comparison face. The distance tells you how similar the faces are.\n\n :param faces: List of face encodings to compare\n :param face_to_compare: A face encoding to compare against\n :retu...
Please provide a description of the function:def load_image_file(file, mode='RGB'): im = PIL.Image.open(file) if mode: im = im.convert(mode) return np.array(im)
[ "\n Loads an image file (.jpg, .png, etc) into a numpy array\n\n :param file: image file name or file object to load\n :param mode: format to convert the image to. Only 'RGB' (8-bit RGB, 3 channels) and 'L' (black and white) are supported.\n :return: image contents as numpy array\n " ]
Please provide a description of the function:def _raw_face_locations(img, number_of_times_to_upsample=1, model="hog"): if model == "cnn": return cnn_face_detector(img, number_of_times_to_upsample) else: return face_detector(img, number_of_times_to_upsample)
[ "\n Returns an array of bounding boxes of human faces in a image\n\n :param img: An image (as a numpy array)\n :param number_of_times_to_upsample: How many times to upsample the image looking for faces. Higher numbers find smaller faces.\n :param model: Which face detection model to use. \"hog\" is less...
Please provide a description of the function:def face_locations(img, number_of_times_to_upsample=1, model="hog"): if model == "cnn": return [_trim_css_to_bounds(_rect_to_css(face.rect), img.shape) for face in _raw_face_locations(img, number_of_times_to_upsample, "cnn")] else: return [_trim_...
[ "\n Returns an array of bounding boxes of human faces in a image\n\n :param img: An image (as a numpy array)\n :param number_of_times_to_upsample: How many times to upsample the image looking for faces. Higher numbers find smaller faces.\n :param model: Which face detection model to use. \"hog\" is less...
Please provide a description of the function:def batch_face_locations(images, number_of_times_to_upsample=1, batch_size=128): def convert_cnn_detections_to_css(detections): return [_trim_css_to_bounds(_rect_to_css(face.rect), images[0].shape) for face in detections] raw_detections_batched = _raw_f...
[ "\n Returns an 2d array of bounding boxes of human faces in a image using the cnn face detector\n If you are using a GPU, this can give you much faster results since the GPU\n can process batches of images at once. If you aren't using a GPU, you don't need this function.\n\n :param img: A list of images...
Please provide a description of the function:def face_landmarks(face_image, face_locations=None, model="large"): landmarks = _raw_face_landmarks(face_image, face_locations, model) landmarks_as_tuples = [[(p.x, p.y) for p in landmark.parts()] for landmark in landmarks] # For a definition of each point ...
[ "\n Given an image, returns a dict of face feature locations (eyes, nose, etc) for each face in the image\n\n :param face_image: image to search\n :param face_locations: Optionally provide a list of face locations to check.\n :param model: Optional - which model to use. \"large\" (default) or \"small\" ...
Please provide a description of the function:def face_encodings(face_image, known_face_locations=None, num_jitters=1): raw_landmarks = _raw_face_landmarks(face_image, known_face_locations, model="small") return [np.array(face_encoder.compute_face_descriptor(face_image, raw_landmark_set, num_jitters)) for r...
[ "\n Given an image, return the 128-dimension face encoding for each face in the image.\n\n :param face_image: The image that contains one or more faces\n :param known_face_locations: Optional - the bounding boxes of each face if you already know them.\n :param num_jitters: How many times to re-sample th...
Please provide a description of the function:def _parse_datatype_string(s): sc = SparkContext._active_spark_context def from_ddl_schema(type_str): return _parse_datatype_json_string( sc._jvm.org.apache.spark.sql.types.StructType.fromDDL(type_str).json()) def from_ddl_datatype(type...
[ "\n Parses the given data type string to a :class:`DataType`. The data type string format equals\n to :class:`DataType.simpleString`, except that top level struct type can omit\n the ``struct<>`` and atomic types use ``typeName()`` as their format, e.g. use ``byte`` instead\n of ``tinyint`` for :class:`...
Please provide a description of the function:def _int_size_to_type(size): if size <= 8: return ByteType if size <= 16: return ShortType if size <= 32: return IntegerType if size <= 64: return LongType
[ "\n Return the Catalyst datatype from the size of integers.\n " ]
Please provide a description of the function:def _infer_type(obj): if obj is None: return NullType() if hasattr(obj, '__UDT__'): return obj.__UDT__ dataType = _type_mappings.get(type(obj)) if dataType is DecimalType: # the precision and scale of `obj` may be different from...
[ "Infer the DataType from obj\n " ]
Please provide a description of the function:def _infer_schema(row, names=None): if isinstance(row, dict): items = sorted(row.items()) elif isinstance(row, (tuple, list)): if hasattr(row, "__fields__"): # Row items = zip(row.__fields__, tuple(row)) elif hasattr(row, "_...
[ "Infer the schema from dict/namedtuple/object" ]
Please provide a description of the function:def _has_nulltype(dt): if isinstance(dt, StructType): return any(_has_nulltype(f.dataType) for f in dt.fields) elif isinstance(dt, ArrayType): return _has_nulltype((dt.elementType)) elif isinstance(dt, MapType): return _has_nulltype(d...
[ " Return whether there is NullType in `dt` or not " ]
Please provide a description of the function:def _create_converter(dataType): if not _need_converter(dataType): return lambda x: x if isinstance(dataType, ArrayType): conv = _create_converter(dataType.elementType) return lambda row: [conv(v) for v in row] elif isinstance(dataT...
[ "Create a converter to drop the names of fields in obj " ]
Please provide a description of the function:def _make_type_verifier(dataType, nullable=True, name=None): if name is None: new_msg = lambda msg: msg new_name = lambda n: "field %s" % n else: new_msg = lambda msg: "%s: %s" % (name, msg) new_name = lambda n: "field %s in %s" ...
[ "\n Make a verifier that checks the type of obj against dataType and raises a TypeError if they do\n not match.\n\n This verifier also checks the value of obj against datatype and raises a ValueError if it's not\n within the allowed range, e.g. using 128 as ByteType will overflow. Note that, Python floa...
Please provide a description of the function:def to_arrow_type(dt): import pyarrow as pa if type(dt) == BooleanType: arrow_type = pa.bool_() elif type(dt) == ByteType: arrow_type = pa.int8() elif type(dt) == ShortType: arrow_type = pa.int16() elif type(dt) == IntegerType...
[ " Convert Spark data type to pyarrow type\n " ]
Please provide a description of the function:def to_arrow_schema(schema): import pyarrow as pa fields = [pa.field(field.name, to_arrow_type(field.dataType), nullable=field.nullable) for field in schema] return pa.schema(fields)
[ " Convert a schema from Spark to Arrow\n " ]
Please provide a description of the function:def from_arrow_type(at): import pyarrow.types as types if types.is_boolean(at): spark_type = BooleanType() elif types.is_int8(at): spark_type = ByteType() elif types.is_int16(at): spark_type = ShortType() elif types.is_int32(a...
[ " Convert pyarrow type to Spark data type.\n " ]
Please provide a description of the function:def from_arrow_schema(arrow_schema): return StructType( [StructField(field.name, from_arrow_type(field.type), nullable=field.nullable) for field in arrow_schema])
[ " Convert schema from Arrow to Spark.\n " ]
Please provide a description of the function:def _check_series_localize_timestamps(s, timezone): from pyspark.sql.utils import require_minimum_pandas_version require_minimum_pandas_version() from pandas.api.types import is_datetime64tz_dtype tz = timezone or _get_local_timezone() # TODO: handl...
[ "\n Convert timezone aware timestamps to timezone-naive in the specified timezone or local timezone.\n\n If the input series is not a timestamp series, then the same series is returned. If the input\n series is a timestamp series, then a converted series is returned.\n\n :param s: pandas.Series\n :pa...
Please provide a description of the function:def _check_dataframe_localize_timestamps(pdf, timezone): from pyspark.sql.utils import require_minimum_pandas_version require_minimum_pandas_version() for column, series in pdf.iteritems(): pdf[column] = _check_series_localize_timestamps(series, tim...
[ "\n Convert timezone aware timestamps to timezone-naive in the specified timezone or local timezone\n\n :param pdf: pandas.DataFrame\n :param timezone: the timezone to convert. if None then use local timezone\n :return pandas.DataFrame where any timezone aware columns have been converted to tz-naive\n ...
Please provide a description of the function:def _check_series_convert_timestamps_internal(s, timezone): from pyspark.sql.utils import require_minimum_pandas_version require_minimum_pandas_version() from pandas.api.types import is_datetime64_dtype, is_datetime64tz_dtype # TODO: handle nested times...
[ "\n Convert a tz-naive timestamp in the specified timezone or local timezone to UTC normalized for\n Spark internal storage\n\n :param s: a pandas.Series\n :param timezone: the timezone to convert. if None then use local timezone\n :return pandas.Series where if it is a timestamp, has been UTC normal...
Please provide a description of the function:def _check_series_convert_timestamps_localize(s, from_timezone, to_timezone): from pyspark.sql.utils import require_minimum_pandas_version require_minimum_pandas_version() import pandas as pd from pandas.api.types import is_datetime64tz_dtype, is_dateti...
[ "\n Convert timestamp to timezone-naive in the specified timezone or local timezone\n\n :param s: a pandas.Series\n :param from_timezone: the timezone to convert from. if None then use local timezone\n :param to_timezone: the timezone to convert to. if None then use local timezone\n :return pandas.Se...
Please provide a description of the function:def add(self, field, data_type=None, nullable=True, metadata=None): if isinstance(field, StructField): self.fields.append(field) self.names.append(field.name) else: if isinstance(field, str) and data_type is None: ...
[ "\n Construct a StructType by adding new elements to it to define the schema. The method accepts\n either:\n\n a) A single parameter which is a StructField object.\n b) Between 2 and 4 parameters as (name, data_type, nullable (optional),\n metadata(optional). The da...
Please provide a description of the function:def _cachedSqlType(cls): if not hasattr(cls, "_cached_sql_type"): cls._cached_sql_type = cls.sqlType() return cls._cached_sql_type
[ "\n Cache the sqlType() into class, because it's heavy used in `toInternal`.\n " ]
Please provide a description of the function:def asDict(self, recursive=False): if not hasattr(self, "__fields__"): raise TypeError("Cannot convert a Row class into dict") if recursive: def conv(obj): if isinstance(obj, Row): return o...
[ "\n Return as an dict\n\n :param recursive: turns the nested Row as dict (default: False).\n\n >>> Row(name=\"Alice\", age=11).asDict() == {'name': 'Alice', 'age': 11}\n True\n >>> row = Row(key=1, value=Row(name='a', age=2))\n >>> row.asDict() == {'key': 1, 'value': Row(ag...
Please provide a description of the function:def summary(self): if self.hasSummary: return LinearRegressionTrainingSummary(super(LinearRegressionModel, self).summary) else: raise RuntimeError("No training summary available for this %s" % se...
[ "\n Gets summary (e.g. residuals, mse, r-squared ) of model on\n training set. An exception is thrown if\n `trainingSummary is None`.\n " ]
Please provide a description of the function:def evaluate(self, dataset): if not isinstance(dataset, DataFrame): raise ValueError("dataset must be a DataFrame but got %s." % type(dataset)) java_lr_summary = self._call_java("evaluate", dataset) return LinearRegressionSummary(...
[ "\n Evaluates the model on a test dataset.\n\n :param dataset:\n Test dataset to evaluate model on, where dataset is an\n instance of :py:class:`pyspark.sql.DataFrame`\n " ]
Please provide a description of the function:def summary(self): if self.hasSummary: return GeneralizedLinearRegressionTrainingSummary( super(GeneralizedLinearRegressionModel, self).summary) else: raise RuntimeError("No training summary available for this ...
[ "\n Gets summary (e.g. residuals, deviance, pValues) of model on\n training set. An exception is thrown if\n `trainingSummary is None`.\n " ]
Please provide a description of the function:def evaluate(self, dataset): if not isinstance(dataset, DataFrame): raise ValueError("dataset must be a DataFrame but got %s." % type(dataset)) java_glr_summary = self._call_java("evaluate", dataset) return GeneralizedLinearRegres...
[ "\n Evaluates the model on a test dataset.\n\n :param dataset:\n Test dataset to evaluate model on, where dataset is an\n instance of :py:class:`pyspark.sql.DataFrame`\n " ]
Please provide a description of the function:def _get_local_dirs(sub): path = os.environ.get("SPARK_LOCAL_DIRS", "/tmp") dirs = path.split(",") if len(dirs) > 1: # different order in different processes and instances rnd = random.Random(os.getpid() + id(dirs)) random.shuffle(dir...
[ " Get all the directories " ]
Please provide a description of the function:def _get_spill_dir(self, n): return os.path.join(self.localdirs[n % len(self.localdirs)], str(n))
[ " Choose one directory for spill by number n " ]
Please provide a description of the function:def mergeValues(self, iterator): # speedup attribute lookup creator, comb = self.agg.createCombiner, self.agg.mergeValue c, data, pdata, hfun, batch = 0, self.data, self.pdata, self._partition, self.batch limit = self.memory_limit ...
[ " Combine the items by creator and combiner " ]
Please provide a description of the function:def mergeCombiners(self, iterator, limit=None): if limit is None: limit = self.memory_limit # speedup attribute lookup comb, hfun, objsize = self.agg.mergeCombiners, self._partition, self._object_size c, data, pdata, batch...
[ " Merge (K,V) pair by mergeCombiner " ]
Please provide a description of the function:def _spill(self): global MemoryBytesSpilled, DiskBytesSpilled path = self._get_spill_dir(self.spills) if not os.path.exists(path): os.makedirs(path) used_memory = get_used_memory() if not self.pdata: #...
[ "\n dump already partitioned data into disks.\n\n It will dump the data in batch for better performance.\n " ]
Please provide a description of the function:def items(self): if not self.pdata and not self.spills: return iter(self.data.items()) return self._external_items()
[ " Return all merged items as iterator " ]
Please provide a description of the function:def _external_items(self): assert not self.data if any(self.pdata): self._spill() # disable partitioning and spilling when merge combiners from disk self.pdata = [] try: for i in range(self.partitions)...
[ " Return all partitioned items as iterator " ]
Please provide a description of the function:def _recursive_merged_items(self, index): subdirs = [os.path.join(d, "parts", str(index)) for d in self.localdirs] m = ExternalMerger(self.agg, self.memory_limit, self.serializer, subdirs, self.scale * self.partitions, self...
[ "\n merge the partitioned items and return the as iterator\n\n If one partition can not be fit in memory, then them will be\n partitioned and merged recursively.\n " ]
Please provide a description of the function:def _get_path(self, n): d = self.local_dirs[n % len(self.local_dirs)] if not os.path.exists(d): os.makedirs(d) return os.path.join(d, str(n))
[ " Choose one directory for spill by number n " ]
Please provide a description of the function:def sorted(self, iterator, key=None, reverse=False): global MemoryBytesSpilled, DiskBytesSpilled batch, limit = 100, self._next_limit() chunks, current_chunk = [], [] iterator = iter(iterator) while True: # pick el...
[ "\n Sort the elements in iterator, do external sort when the memory\n goes above the limit.\n " ]
Please provide a description of the function:def _spill(self): global MemoryBytesSpilled, DiskBytesSpilled if self._file is None: self._open_file() used_memory = get_used_memory() pos = self._file.tell() self._ser.dump_stream(self.values, self._file) ...
[ " dump the values into disk " ]
Please provide a description of the function:def _spill(self): global MemoryBytesSpilled, DiskBytesSpilled path = self._get_spill_dir(self.spills) if not os.path.exists(path): os.makedirs(path) used_memory = get_used_memory() if not self.pdata: #...
[ "\n dump already partitioned data into disks.\n " ]
Please provide a description of the function:def _merge_sorted_items(self, index): def load_partition(j): path = self._get_spill_dir(j) p = os.path.join(path, str(index)) with open(p, 'rb', 65536) as f: for v in self.serializer.load_stream(f): ...
[ " load a partition from disk, then sort and group by key " ]
Please provide a description of the function:def worker(sock, authenticated): signal.signal(SIGHUP, SIG_DFL) signal.signal(SIGCHLD, SIG_DFL) signal.signal(SIGTERM, SIG_DFL) # restore the handler for SIGINT, # it's useful for debugging (show the stacktrace before exit) signal.signal(SIGINT, ...
[ "\n Called by a worker process after the fork().\n " ]
Please provide a description of the function:def portable_hash(x): if sys.version_info >= (3, 2, 3) and 'PYTHONHASHSEED' not in os.environ: raise Exception("Randomness of hash of string should be disabled via PYTHONHASHSEED") if x is None: return 0 if isinstance(x, tuple): h =...
[ "\n This function returns consistent hash code for builtin types, especially\n for None and tuple with None.\n\n The algorithm is similar to that one used by CPython 2.7\n\n >>> portable_hash(None)\n 0\n >>> portable_hash((None, 1)) & 0xffffffff\n 219750521\n " ]
Please provide a description of the function:def _parse_memory(s): units = {'g': 1024, 'm': 1, 't': 1 << 20, 'k': 1.0 / 1024} if s[-1].lower() not in units: raise ValueError("invalid format: " + s) return int(float(s[:-1]) * units[s[-1].lower()])
[ "\n Parse a memory string in the format supported by Java (e.g. 1g, 200m) and\n return the value in MiB\n\n >>> _parse_memory(\"256m\")\n 256\n >>> _parse_memory(\"2g\")\n 2048\n " ]
Please provide a description of the function:def ignore_unicode_prefix(f): if sys.version >= '3': # the representation of unicode string in Python 3 does not have prefix 'u', # so remove the prefix 'u' for doc tests literal_re = re.compile(r"(\W|^)[uU](['])", re.UNICODE) f.__doc...
[ "\n Ignore the 'u' prefix of string in doc tests, to make it works\n in both python 2 and 3\n " ]
Please provide a description of the function:def cache(self): self.is_cached = True self.persist(StorageLevel.MEMORY_ONLY) return self
[ "\n Persist this RDD with the default storage level (C{MEMORY_ONLY}).\n " ]
Please provide a description of the function:def persist(self, storageLevel=StorageLevel.MEMORY_ONLY): self.is_cached = True javaStorageLevel = self.ctx._getJavaStorageLevel(storageLevel) self._jrdd.persist(javaStorageLevel) return self
[ "\n Set this RDD's storage level to persist its values across operations\n after the first time it is computed. This can only be used to assign\n a new storage level if the RDD does not have a storage level set yet.\n If no storage level is specified defaults to (C{MEMORY_ONLY}).\n\n ...
Please provide a description of the function:def unpersist(self, blocking=False): self.is_cached = False self._jrdd.unpersist(blocking) return self
[ "\n Mark the RDD as non-persistent, and remove all blocks for it from\n memory and disk.\n\n .. versionchanged:: 3.0.0\n Added optional argument `blocking` to specify whether to block until all\n blocks are deleted.\n " ]
Please provide a description of the function:def getCheckpointFile(self): checkpointFile = self._jrdd.rdd().getCheckpointFile() if checkpointFile.isDefined(): return checkpointFile.get()
[ "\n Gets the name of the file to which this RDD was checkpointed\n\n Not defined if RDD is checkpointed locally.\n " ]
Please provide a description of the function:def map(self, f, preservesPartitioning=False): def func(_, iterator): return map(fail_on_stopiteration(f), iterator) return self.mapPartitionsWithIndex(func, preservesPartitioning)
[ "\n Return a new RDD by applying a function to each element of this RDD.\n\n >>> rdd = sc.parallelize([\"b\", \"a\", \"c\"])\n >>> sorted(rdd.map(lambda x: (x, 1)).collect())\n [('a', 1), ('b', 1), ('c', 1)]\n " ]
Please provide a description of the function:def flatMap(self, f, preservesPartitioning=False): def func(s, iterator): return chain.from_iterable(map(fail_on_stopiteration(f), iterator)) return self.mapPartitionsWithIndex(func, preservesPartitioning)
[ "\n Return a new RDD by first applying a function to all elements of this\n RDD, and then flattening the results.\n\n >>> rdd = sc.parallelize([2, 3, 4])\n >>> sorted(rdd.flatMap(lambda x: range(1, x)).collect())\n [1, 1, 1, 2, 2, 3]\n >>> sorted(rdd.flatMap(lambda x: [(x, ...
Please provide a description of the function:def mapPartitions(self, f, preservesPartitioning=False): def func(s, iterator): return f(iterator) return self.mapPartitionsWithIndex(func, preservesPartitioning)
[ "\n Return a new RDD by applying a function to each partition of this RDD.\n\n >>> rdd = sc.parallelize([1, 2, 3, 4], 2)\n >>> def f(iterator): yield sum(iterator)\n >>> rdd.mapPartitions(f).collect()\n [3, 7]\n " ]
Please provide a description of the function:def mapPartitionsWithSplit(self, f, preservesPartitioning=False): warnings.warn("mapPartitionsWithSplit is deprecated; " "use mapPartitionsWithIndex instead", DeprecationWarning, stacklevel=2) return self.mapPartitionsWithIndex(...
[ "\n Deprecated: use mapPartitionsWithIndex instead.\n\n Return a new RDD by applying a function to each partition of this RDD,\n while tracking the index of the original partition.\n\n >>> rdd = sc.parallelize([1, 2, 3, 4], 4)\n >>> def f(splitIndex, iterator): yield splitIndex\n ...
Please provide a description of the function:def distinct(self, numPartitions=None): return self.map(lambda x: (x, None)) \ .reduceByKey(lambda x, _: x, numPartitions) \ .map(lambda x: x[0])
[ "\n Return a new RDD containing the distinct elements in this RDD.\n\n >>> sorted(sc.parallelize([1, 1, 2, 3]).distinct().collect())\n [1, 2, 3]\n " ]
Please provide a description of the function:def sample(self, withReplacement, fraction, seed=None): assert fraction >= 0.0, "Negative fraction value: %s" % fraction return self.mapPartitionsWithIndex(RDDSampler(withReplacement, fraction, seed).func, True)
[ "\n Return a sampled subset of this RDD.\n\n :param withReplacement: can elements be sampled multiple times (replaced when sampled out)\n :param fraction: expected size of the sample as a fraction of this RDD's size\n without replacement: probability that each element is chosen; frac...
Please provide a description of the function:def randomSplit(self, weights, seed=None): s = float(sum(weights)) cweights = [0.0] for w in weights: cweights.append(cweights[-1] + w / s) if seed is None: seed = random.randint(0, 2 ** 32 - 1) return ...
[ "\n Randomly splits this RDD with the provided weights.\n\n :param weights: weights for splits, will be normalized if they don't sum to 1\n :param seed: random seed\n :return: split RDDs in a list\n\n >>> rdd = sc.parallelize(range(500), 1)\n >>> rdd1, rdd2 = rdd.randomSpli...
Please provide a description of the function:def takeSample(self, withReplacement, num, seed=None): numStDev = 10.0 if num < 0: raise ValueError("Sample size cannot be negative.") elif num == 0: return [] initialCount = self.count() if initialCo...
[ "\n Return a fixed-size sampled subset of this RDD.\n\n .. note:: This method should only be used if the resulting array is expected\n to be small, as all the data is loaded into the driver's memory.\n\n >>> rdd = sc.parallelize(range(0, 10))\n >>> len(rdd.takeSample(True, 20,...
Please provide a description of the function:def _computeFractionForSampleSize(sampleSizeLowerBound, total, withReplacement): fraction = float(sampleSizeLowerBound) / total if withReplacement: numStDev = 5 if (sampleSizeLowerBound < 12): numStDev = 9 ...
[ "\n Returns a sampling rate that guarantees a sample of\n size >= sampleSizeLowerBound 99.99% of the time.\n\n How the sampling rate is determined:\n Let p = num / total, where num is the sample size and total is the\n total number of data points in the RDD. We're trying to comput...
Please provide a description of the function:def union(self, other): if self._jrdd_deserializer == other._jrdd_deserializer: rdd = RDD(self._jrdd.union(other._jrdd), self.ctx, self._jrdd_deserializer) else: # These RDDs contain data in different ser...
[ "\n Return the union of this RDD and another one.\n\n >>> rdd = sc.parallelize([1, 1, 2, 3])\n >>> rdd.union(rdd).collect()\n [1, 1, 2, 3, 1, 1, 2, 3]\n " ]
Please provide a description of the function:def intersection(self, other): return self.map(lambda v: (v, None)) \ .cogroup(other.map(lambda v: (v, None))) \ .filter(lambda k_vs: all(k_vs[1])) \ .keys()
[ "\n Return the intersection of this RDD and another one. The output will\n not contain any duplicate elements, even if the input RDDs did.\n\n .. note:: This method performs a shuffle internally.\n\n >>> rdd1 = sc.parallelize([1, 10, 2, 3, 4, 5])\n >>> rdd2 = sc.parallelize([1, 6,...
Please provide a description of the function:def repartitionAndSortWithinPartitions(self, numPartitions=None, partitionFunc=portable_hash, ascending=True, keyfunc=lambda x: x): if numPartitions is None: numPartitions = self._defaultReducePartitions...
[ "\n Repartition the RDD according to the given partitioner and, within each resulting partition,\n sort records by their keys.\n\n >>> rdd = sc.parallelize([(0, 5), (3, 8), (2, 6), (0, 8), (3, 8), (1, 3)])\n >>> rdd2 = rdd.repartitionAndSortWithinPartitions(2, lambda x: x % 2, True)\n ...
Please provide a description of the function:def sortByKey(self, ascending=True, numPartitions=None, keyfunc=lambda x: x): if numPartitions is None: numPartitions = self._defaultReducePartitions() memory = self._memory_limit() serializer = self._jrdd_deserializer d...
[ "\n Sorts this RDD, which is assumed to consist of (key, value) pairs.\n\n >>> tmp = [('a', 1), ('b', 2), ('1', 3), ('d', 4), ('2', 5)]\n >>> sc.parallelize(tmp).sortByKey().first()\n ('1', 3)\n >>> sc.parallelize(tmp).sortByKey(True, 1).collect()\n [('1', 3), ('2', 5), ('a...
Please provide a description of the function:def sortBy(self, keyfunc, ascending=True, numPartitions=None): return self.keyBy(keyfunc).sortByKey(ascending, numPartitions).values()
[ "\n Sorts this RDD by the given keyfunc\n\n >>> tmp = [('a', 1), ('b', 2), ('1', 3), ('d', 4), ('2', 5)]\n >>> sc.parallelize(tmp).sortBy(lambda x: x[0]).collect()\n [('1', 3), ('2', 5), ('a', 1), ('b', 2), ('d', 4)]\n >>> sc.parallelize(tmp).sortBy(lambda x: x[1]).collect()\n ...
Please provide a description of the function:def cartesian(self, other): # Due to batching, we can't use the Java cartesian method. deserializer = CartesianDeserializer(self._jrdd_deserializer, other._jrdd_deserializer) return RDD(self._jrdd....
[ "\n Return the Cartesian product of this RDD and another one, that is, the\n RDD of all pairs of elements C{(a, b)} where C{a} is in C{self} and\n C{b} is in C{other}.\n\n >>> rdd = sc.parallelize([1, 2])\n >>> sorted(rdd.cartesian(rdd).collect())\n [(1, 1), (1, 2), (2, 1),...
Please provide a description of the function:def groupBy(self, f, numPartitions=None, partitionFunc=portable_hash): return self.map(lambda x: (f(x), x)).groupByKey(numPartitions, partitionFunc)
[ "\n Return an RDD of grouped items.\n\n >>> rdd = sc.parallelize([1, 1, 2, 3, 5, 8])\n >>> result = rdd.groupBy(lambda x: x % 2).collect()\n >>> sorted([(x, sorted(y)) for (x, y) in result])\n [(0, [2, 8]), (1, [1, 1, 3, 5])]\n " ]
Please provide a description of the function:def pipe(self, command, env=None, checkCode=False): if env is None: env = dict() def func(iterator): pipe = Popen( shlex.split(command), env=env, stdin=PIPE, stdout=PIPE) def pipe_objs(out): ...
[ "\n Return an RDD created by piping elements to a forked external process.\n\n >>> sc.parallelize(['1', '2', '', '3']).pipe('cat').collect()\n [u'1', u'2', u'', u'3']\n\n :param checkCode: whether or not to check the return value of the shell command.\n " ]
Please provide a description of the function:def foreach(self, f): f = fail_on_stopiteration(f) def processPartition(iterator): for x in iterator: f(x) return iter([]) self.mapPartitions(processPartition).count()
[ "\n Applies a function to all elements of this RDD.\n\n >>> def f(x): print(x)\n >>> sc.parallelize([1, 2, 3, 4, 5]).foreach(f)\n " ]
Please provide a description of the function:def foreachPartition(self, f): def func(it): r = f(it) try: return iter(r) except TypeError: return iter([]) self.mapPartitions(func).count()
[ "\n Applies a function to each partition of this RDD.\n\n >>> def f(iterator):\n ... for x in iterator:\n ... print(x)\n >>> sc.parallelize([1, 2, 3, 4, 5]).foreachPartition(f)\n " ]
Please provide a description of the function:def collect(self): with SCCallSiteSync(self.context) as css: sock_info = self.ctx._jvm.PythonRDD.collectAndServe(self._jrdd.rdd()) return list(_load_from_socket(sock_info, self._jrdd_deserializer))
[ "\n Return a list that contains all of the elements in this RDD.\n\n .. note:: This method should only be used if the resulting array is expected\n to be small, as all the data is loaded into the driver's memory.\n " ]
Please provide a description of the function:def reduce(self, f): f = fail_on_stopiteration(f) def func(iterator): iterator = iter(iterator) try: initial = next(iterator) except StopIteration: return yield reduce(f...
[ "\n Reduces the elements of this RDD using the specified commutative and\n associative binary operator. Currently reduces partitions locally.\n\n >>> from operator import add\n >>> sc.parallelize([1, 2, 3, 4, 5]).reduce(add)\n 15\n >>> sc.parallelize((2 for _ in range(10)))...
Please provide a description of the function:def treeReduce(self, f, depth=2): if depth < 1: raise ValueError("Depth cannot be smaller than 1 but got %d." % depth) zeroValue = None, True # Use the second entry to indicate whether this is a dummy value. def op(x, y): ...
[ "\n Reduces the elements of this RDD in a multi-level tree pattern.\n\n :param depth: suggested depth of the tree (default: 2)\n\n >>> add = lambda x, y: x + y\n >>> rdd = sc.parallelize([-5, -4, -3, -2, -1, 1, 2, 3, 4], 10)\n >>> rdd.treeReduce(add)\n -5\n >>> rdd.t...
Please provide a description of the function:def fold(self, zeroValue, op): op = fail_on_stopiteration(op) def func(iterator): acc = zeroValue for obj in iterator: acc = op(acc, obj) yield acc # collecting result of mapPartitions here...
[ "\n Aggregate the elements of each partition, and then the results for all\n the partitions, using a given associative function and a neutral \"zero value.\"\n\n The function C{op(t1, t2)} is allowed to modify C{t1} and return it\n as its result value to avoid object allocation; however,...
Please provide a description of the function:def aggregate(self, zeroValue, seqOp, combOp): seqOp = fail_on_stopiteration(seqOp) combOp = fail_on_stopiteration(combOp) def func(iterator): acc = zeroValue for obj in iterator: acc = seqOp(acc, obj)...
[ "\n Aggregate the elements of each partition, and then the results for all\n the partitions, using a given combine functions and a neutral \"zero\n value.\"\n\n The functions C{op(t1, t2)} is allowed to modify C{t1} and return it\n as its result value to avoid object allocation; h...
Please provide a description of the function:def treeAggregate(self, zeroValue, seqOp, combOp, depth=2): if depth < 1: raise ValueError("Depth cannot be smaller than 1 but got %d." % depth) if self.getNumPartitions() == 0: return zeroValue def aggregatePartitio...
[ "\n Aggregates the elements of this RDD in a multi-level tree\n pattern.\n\n :param depth: suggested depth of the tree (default: 2)\n\n >>> add = lambda x, y: x + y\n >>> rdd = sc.parallelize([-5, -4, -3, -2, -1, 1, 2, 3, 4], 10)\n >>> rdd.treeAggregate(0, add, add)\n ...
Please provide a description of the function:def max(self, key=None): if key is None: return self.reduce(max) return self.reduce(lambda a, b: max(a, b, key=key))
[ "\n Find the maximum item in this RDD.\n\n :param key: A function used to generate key for comparing\n\n >>> rdd = sc.parallelize([1.0, 5.0, 43.0, 10.0])\n >>> rdd.max()\n 43.0\n >>> rdd.max(key=str)\n 5.0\n " ]
Please provide a description of the function:def min(self, key=None): if key is None: return self.reduce(min) return self.reduce(lambda a, b: min(a, b, key=key))
[ "\n Find the minimum item in this RDD.\n\n :param key: A function used to generate key for comparing\n\n >>> rdd = sc.parallelize([2.0, 5.0, 43.0, 10.0])\n >>> rdd.min()\n 2.0\n >>> rdd.min(key=str)\n 10.0\n " ]
Please provide a description of the function:def sum(self): return self.mapPartitions(lambda x: [sum(x)]).fold(0, operator.add)
[ "\n Add up the elements in this RDD.\n\n >>> sc.parallelize([1.0, 2.0, 3.0]).sum()\n 6.0\n " ]
Please provide a description of the function:def stats(self): def redFunc(left_counter, right_counter): return left_counter.mergeStats(right_counter) return self.mapPartitions(lambda i: [StatCounter(i)]).reduce(redFunc)
[ "\n Return a L{StatCounter} object that captures the mean, variance\n and count of the RDD's elements in one operation.\n " ]
Please provide a description of the function:def histogram(self, buckets): if isinstance(buckets, int): if buckets < 1: raise ValueError("number of buckets must be >= 1") # filter out non-comparable elements def comparable(x): if x i...
[ "\n Compute a histogram using the provided buckets. The buckets\n are all open to the right except for the last which is closed.\n e.g. [1,10,20,50] means the buckets are [1,10) [10,20) [20,50],\n which means 1<=x<10, 10<=x<20, 20<=x<=50. And on the input of 1\n and 50 we would ha...
Please provide a description of the function:def countByValue(self): def countPartition(iterator): counts = defaultdict(int) for obj in iterator: counts[obj] += 1 yield counts def mergeMaps(m1, m2): for k, v in m2.items(): ...
[ "\n Return the count of each unique value in this RDD as a dictionary of\n (value, count) pairs.\n\n >>> sorted(sc.parallelize([1, 2, 1, 2, 2], 2).countByValue().items())\n [(1, 2), (2, 3)]\n " ]
Please provide a description of the function:def top(self, num, key=None): def topIterator(iterator): yield heapq.nlargest(num, iterator, key=key) def merge(a, b): return heapq.nlargest(num, a + b, key=key) return self.mapPartitions(topIterator).reduce(merge)
[ "\n Get the top N elements from an RDD.\n\n .. note:: This method should only be used if the resulting array is expected\n to be small, as all the data is loaded into the driver's memory.\n\n .. note:: It returns the list sorted in descending order.\n\n >>> sc.parallelize([10,...
Please provide a description of the function:def takeOrdered(self, num, key=None): def merge(a, b): return heapq.nsmallest(num, a + b, key) return self.mapPartitions(lambda it: [heapq.nsmallest(num, it, key)]).reduce(merge)
[ "\n Get the N elements from an RDD ordered in ascending order or as\n specified by the optional key function.\n\n .. note:: this method should only be used if the resulting array is expected\n to be small, as all the data is loaded into the driver's memory.\n\n >>> sc.parallel...
Please provide a description of the function:def take(self, num): items = [] totalParts = self.getNumPartitions() partsScanned = 0 while len(items) < num and partsScanned < totalParts: # The number of partitions to try in this iteration. # It is ok for t...
[ "\n Take the first num elements of the RDD.\n\n It works by first scanning one partition, and use the results from\n that partition to estimate the number of additional partitions needed\n to satisfy the limit.\n\n Translated from the Scala implementation in RDD#take().\n\n ...
Please provide a description of the function:def saveAsNewAPIHadoopDataset(self, conf, keyConverter=None, valueConverter=None): jconf = self.ctx._dictToJavaMap(conf) pickledRDD = self._pickled() self.ctx._jvm.PythonRDD.saveAsHadoopDataset(pickledRDD._jrdd, True, jconf, ...
[ "\n Output a Python RDD of key-value pairs (of form C{RDD[(K, V)]}) to any Hadoop file\n system, using the new Hadoop OutputFormat API (mapreduce package). Keys/values are\n converted for output using either user specified converters or, by default,\n L{org.apache.spark.api.python.JavaTo...
Please provide a description of the function:def saveAsNewAPIHadoopFile(self, path, outputFormatClass, keyClass=None, valueClass=None, keyConverter=None, valueConverter=None, conf=None): jconf = self.ctx._dictToJavaMap(conf) pickledRDD = self._pickled() se...
[ "\n Output a Python RDD of key-value pairs (of form C{RDD[(K, V)]}) to any Hadoop file\n system, using the new Hadoop OutputFormat API (mapreduce package). Key and value types\n will be inferred if not specified. Keys and values are converted for output using either\n user specified conv...
Please provide a description of the function:def saveAsSequenceFile(self, path, compressionCodecClass=None): pickledRDD = self._pickled() self.ctx._jvm.PythonRDD.saveAsSequenceFile(pickledRDD._jrdd, True, path, compressionCodecClass)
[ "\n Output a Python RDD of key-value pairs (of form C{RDD[(K, V)]}) to any Hadoop file\n system, using the L{org.apache.hadoop.io.Writable} types that we convert from the\n RDD's key and value types. The mechanism is as follows:\n\n 1. Pyrolite is used to convert pickled Python RDD i...
Please provide a description of the function:def saveAsPickleFile(self, path, batchSize=10): if batchSize == 0: ser = AutoBatchedSerializer(PickleSerializer()) else: ser = BatchedSerializer(PickleSerializer(), batchSize) self._reserialize(ser)._jrdd.saveAsObjectF...
[ "\n Save this RDD as a SequenceFile of serialized objects. The serializer\n used is L{pyspark.serializers.PickleSerializer}, default batch size\n is 10.\n\n >>> tmpFile = NamedTemporaryFile(delete=True)\n >>> tmpFile.close()\n >>> sc.parallelize([1, 2, 'spark', 'rdd']).save...
Please provide a description of the function:def saveAsTextFile(self, path, compressionCodecClass=None): def func(split, iterator): for x in iterator: if not isinstance(x, (unicode, bytes)): x = unicode(x) if isinstance(x, unicode): ...
[ "\n Save this RDD as a text file, using string representations of elements.\n\n @param path: path to text file\n @param compressionCodecClass: (None by default) string i.e.\n \"org.apache.hadoop.io.compress.GzipCodec\"\n\n >>> tempFile = NamedTemporaryFile(delete=True)\n ...
Please provide a description of the function:def reduceByKey(self, func, numPartitions=None, partitionFunc=portable_hash): return self.combineByKey(lambda x: x, func, func, numPartitions, partitionFunc)
[ "\n Merge the values for each key using an associative and commutative reduce function.\n\n This will also perform the merging locally on each mapper before\n sending results to a reducer, similarly to a \"combiner\" in MapReduce.\n\n Output will be partitioned with C{numPartitions} part...
Please provide a description of the function:def reduceByKeyLocally(self, func): func = fail_on_stopiteration(func) def reducePartition(iterator): m = {} for k, v in iterator: m[k] = func(m[k], v) if k in m else v yield m def mergeMa...
[ "\n Merge the values for each key using an associative and commutative reduce function, but\n return the results immediately to the master as a dictionary.\n\n This will also perform the merging locally on each mapper before\n sending results to a reducer, similarly to a \"combiner\" in ...
Please provide a description of the function:def partitionBy(self, numPartitions, partitionFunc=portable_hash): if numPartitions is None: numPartitions = self._defaultReducePartitions() partitioner = Partitioner(numPartitions, partitionFunc) if self.partitioner == partitione...
[ "\n Return a copy of the RDD partitioned using the specified partitioner.\n\n >>> pairs = sc.parallelize([1, 2, 3, 4, 2, 4, 1]).map(lambda x: (x, x))\n >>> sets = pairs.partitionBy(2).glom().collect()\n >>> len(set(sets[0]).intersection(set(sets[1])))\n 0\n " ]
Please provide a description of the function:def combineByKey(self, createCombiner, mergeValue, mergeCombiners, numPartitions=None, partitionFunc=portable_hash): if numPartitions is None: numPartitions = self._defaultReducePartitions() serializer = self.ctx.ser...
[ "\n Generic function to combine the elements for each key using a custom\n set of aggregation functions.\n\n Turns an RDD[(K, V)] into a result of type RDD[(K, C)], for a \"combined\n type\" C.\n\n Users provide three functions:\n\n - C{createCombiner}, which turns a V ...
Please provide a description of the function:def aggregateByKey(self, zeroValue, seqFunc, combFunc, numPartitions=None, partitionFunc=portable_hash): def createZero(): return copy.deepcopy(zeroValue) return self.combineByKey( lambda v: seqFunc(cre...
[ "\n Aggregate the values of each key, using given combine functions and a neutral\n \"zero value\". This function can return a different result type, U, than the type\n of the values in this RDD, V. Thus, we need one operation for merging a V into\n a U and one operation for merging two ...
Please provide a description of the function:def foldByKey(self, zeroValue, func, numPartitions=None, partitionFunc=portable_hash): def createZero(): return copy.deepcopy(zeroValue) return self.combineByKey(lambda v: func(createZero(), v), func, func, numPartitions, ...
[ "\n Merge the values for each key using an associative function \"func\"\n and a neutral \"zeroValue\" which may be added to the result an\n arbitrary number of times, and must not change the result\n (e.g., 0 for addition, or 1 for multiplication.).\n\n >>> rdd = sc.parallelize([...
End of preview. Expand in Data Studio

No dataset card yet

Downloads last month
6