Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def groupByKey(self, numPartitions=None, partitionFunc=portable_hash):
def createCombiner(x):
return [x]
def mergeValue(xs, x):
xs.append(x)
return xs
def mergeCombiners(a, b):
a.extend(b)
... | [
"\n Group the values for each key in the RDD into a single sequence.\n Hash-partitions the resulting RDD with numPartitions partitions.\n\n .. note:: If you are grouping in order to perform an aggregation (such as a\n sum or average) over each key, using reduceByKey or aggregateByKey... |
Please provide a description of the function:def flatMapValues(self, f):
flat_map_fn = lambda kv: ((kv[0], x) for x in f(kv[1]))
return self.flatMap(flat_map_fn, preservesPartitioning=True) | [
"\n Pass each value in the key-value pair RDD through a flatMap function\n without changing the keys; this also retains the original RDD's\n partitioning.\n\n >>> x = sc.parallelize([(\"a\", [\"x\", \"y\", \"z\"]), (\"b\", [\"p\", \"r\"])])\n >>> def f(x): return x\n >>> x.... |
Please provide a description of the function:def mapValues(self, f):
map_values_fn = lambda kv: (kv[0], f(kv[1]))
return self.map(map_values_fn, preservesPartitioning=True) | [
"\n Pass each value in the key-value pair RDD through a map function\n without changing the keys; this also retains the original RDD's\n partitioning.\n\n >>> x = sc.parallelize([(\"a\", [\"apple\", \"banana\", \"lemon\"]), (\"b\", [\"grapes\"])])\n >>> def f(x): return len(x)\n ... |
Please provide a description of the function:def sampleByKey(self, withReplacement, fractions, seed=None):
for fraction in fractions.values():
assert fraction >= 0.0, "Negative fraction value: %s" % fraction
return self.mapPartitionsWithIndex(
RDDStratifiedSampler(withRe... | [
"\n Return a subset of this RDD sampled by key (via stratified sampling).\n Create a sample of this RDD using variable sampling rates for\n different keys as specified by fractions, a key to sampling rate map.\n\n >>> fractions = {\"a\": 0.2, \"b\": 0.1}\n >>> rdd = sc.parallelize... |
Please provide a description of the function:def subtractByKey(self, other, numPartitions=None):
def filter_func(pair):
key, (val1, val2) = pair
return val1 and not val2
return self.cogroup(other, numPartitions).filter(filter_func).flatMapValues(lambda x: x[0]) | [
"\n Return each (key, value) pair in C{self} that has no pair with matching\n key in C{other}.\n\n >>> x = sc.parallelize([(\"a\", 1), (\"b\", 4), (\"b\", 5), (\"a\", 2)])\n >>> y = sc.parallelize([(\"a\", 3), (\"c\", None)])\n >>> sorted(x.subtractByKey(y).collect())\n [('... |
Please provide a description of the function:def subtract(self, other, numPartitions=None):
# note: here 'True' is just a placeholder
rdd = other.map(lambda x: (x, True))
return self.map(lambda x: (x, True)).subtractByKey(rdd, numPartitions).keys() | [
"\n Return each value in C{self} that is not contained in C{other}.\n\n >>> x = sc.parallelize([(\"a\", 1), (\"b\", 4), (\"b\", 5), (\"a\", 3)])\n >>> y = sc.parallelize([(\"a\", 3), (\"c\", None)])\n >>> sorted(x.subtract(y).collect())\n [('a', 1), ('b', 4), ('b', 5)]\n "
... |
Please provide a description of the function:def coalesce(self, numPartitions, shuffle=False):
if shuffle:
# Decrease the batch size in order to distribute evenly the elements across output
# partitions. Otherwise, repartition will possibly produce highly skewed partitions.
... | [
"\n Return a new RDD that is reduced into `numPartitions` partitions.\n\n >>> sc.parallelize([1, 2, 3, 4, 5], 3).glom().collect()\n [[1], [2, 3], [4, 5]]\n >>> sc.parallelize([1, 2, 3, 4, 5], 3).coalesce(1).glom().collect()\n [[1, 2, 3, 4, 5]]\n "
] |
Please provide a description of the function:def zip(self, other):
def get_batch_size(ser):
if isinstance(ser, BatchedSerializer):
return ser.batchSize
return 1 # not batched
def batch_as(rdd, batchSize):
return rdd._reserialize(BatchedSeria... | [
"\n Zips this RDD with another one, returning key-value pairs with the\n first element in each RDD second element in each RDD, etc. Assumes\n that the two RDDs have the same number of partitions and the same\n number of elements in each partition (e.g. one was made through\n a map... |
Please provide a description of the function:def zipWithIndex(self):
starts = [0]
if self.getNumPartitions() > 1:
nums = self.mapPartitions(lambda it: [sum(1 for i in it)]).collect()
for i in range(len(nums) - 1):
starts.append(starts[-1] + nums[i])
... | [
"\n Zips this RDD with its element indices.\n\n The ordering is first based on the partition index and then the\n ordering of items within each partition. So the first item in\n the first partition gets index 0, and the last item in the last\n partition receives the largest index.... |
Please provide a description of the function:def zipWithUniqueId(self):
n = self.getNumPartitions()
def func(k, it):
for i, v in enumerate(it):
yield v, i * n + k
return self.mapPartitionsWithIndex(func) | [
"\n Zips this RDD with generated unique Long ids.\n\n Items in the kth partition will get ids k, n+k, 2*n+k, ..., where\n n is the number of partitions. So there may exist gaps, but this\n method won't trigger a spark job, which is different from\n L{zipWithIndex}\n\n >>> s... |
Please provide a description of the function:def getStorageLevel(self):
java_storage_level = self._jrdd.getStorageLevel()
storage_level = StorageLevel(java_storage_level.useDisk(),
java_storage_level.useMemory(),
java_sto... | [
"\n Get the RDD's current storage level.\n\n >>> rdd1 = sc.parallelize([1,2])\n >>> rdd1.getStorageLevel()\n StorageLevel(False, False, False, False, 1)\n >>> print(rdd1.getStorageLevel())\n Serialized 1x Replicated\n "
] |
Please provide a description of the function:def _defaultReducePartitions(self):
if self.ctx._conf.contains("spark.default.parallelism"):
return self.ctx.defaultParallelism
else:
return self.getNumPartitions() | [
"\n Returns the default number of partitions to use during reduce tasks (e.g., groupBy).\n If spark.default.parallelism is set, then we'll use the value from SparkContext\n defaultParallelism, otherwise we'll use the number of partitions in this RDD.\n\n This mirrors the behavior of the ... |
Please provide a description of the function:def lookup(self, key):
values = self.filter(lambda kv: kv[0] == key).values()
if self.partitioner is not None:
return self.ctx.runJob(values, lambda x: x, [self.partitioner(key)])
return values.collect() | [
"\n Return the list of values in the RDD for key `key`. This operation\n is done efficiently if the RDD has a known partitioner by only\n searching the partition that the key maps to.\n\n >>> l = range(1000)\n >>> rdd = sc.parallelize(zip(l, l), 10)\n >>> rdd.lookup(42) # ... |
Please provide a description of the function:def _to_java_object_rdd(self):
rdd = self._pickled()
return self.ctx._jvm.SerDeUtil.pythonToJava(rdd._jrdd, True) | [
" Return a JavaRDD of Object by unpickling\n\n It will convert each Python object into Java object by Pyrolite, whenever the\n RDD is serialized in batch or not.\n "
] |
Please provide a description of the function:def countApprox(self, timeout, confidence=0.95):
drdd = self.mapPartitions(lambda it: [float(sum(1 for i in it))])
return int(drdd.sumApprox(timeout, confidence)) | [
"\n .. note:: Experimental\n\n Approximate version of count() that returns a potentially incomplete\n result within a timeout, even if not all tasks have finished.\n\n >>> rdd = sc.parallelize(range(1000), 10)\n >>> rdd.countApprox(1000, 1.0)\n 1000\n "
] |
Please provide a description of the function:def sumApprox(self, timeout, confidence=0.95):
jrdd = self.mapPartitions(lambda it: [float(sum(it))])._to_java_object_rdd()
jdrdd = self.ctx._jvm.JavaDoubleRDD.fromRDD(jrdd.rdd())
r = jdrdd.sumApprox(timeout, confidence).getFinalValue()
... | [
"\n .. note:: Experimental\n\n Approximate operation to return the sum within a timeout\n or meet the confidence.\n\n >>> rdd = sc.parallelize(range(1000), 10)\n >>> r = sum(range(1000))\n >>> abs(rdd.sumApprox(1000) - r) / r < 0.05\n True\n "
] |
Please provide a description of the function:def meanApprox(self, timeout, confidence=0.95):
jrdd = self.map(float)._to_java_object_rdd()
jdrdd = self.ctx._jvm.JavaDoubleRDD.fromRDD(jrdd.rdd())
r = jdrdd.meanApprox(timeout, confidence).getFinalValue()
return BoundedFloat(r.mean(... | [
"\n .. note:: Experimental\n\n Approximate operation to return the mean within a timeout\n or meet the confidence.\n\n >>> rdd = sc.parallelize(range(1000), 10)\n >>> r = sum(range(1000)) / 1000.0\n >>> abs(rdd.meanApprox(1000) - r) / r < 0.05\n True\n "
] |
Please provide a description of the function:def countApproxDistinct(self, relativeSD=0.05):
if relativeSD < 0.000017:
raise ValueError("relativeSD should be greater than 0.000017")
# the hash space in Java is 2^32
hashRDD = self.map(lambda x: portable_hash(x) & 0xFFFFFFFF)
... | [
"\n .. note:: Experimental\n\n Return approximate number of distinct elements in the RDD.\n\n The algorithm used is based on streamlib's implementation of\n `\"HyperLogLog in Practice: Algorithmic Engineering of a State\n of The Art Cardinality Estimation Algorithm\", available he... |
Please provide a description of the function:def toLocalIterator(self):
with SCCallSiteSync(self.context) as css:
sock_info = self.ctx._jvm.PythonRDD.toLocalIteratorAndServe(self._jrdd.rdd())
return _load_from_socket(sock_info, self._jrdd_deserializer) | [
"\n Return an iterator that contains all of the elements in this RDD.\n The iterator will consume as much memory as the largest partition in this RDD.\n\n >>> rdd = sc.parallelize(range(10))\n >>> [x for x in rdd.toLocalIterator()]\n [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n "
] |
Please provide a description of the function:def mapPartitions(self, f, preservesPartitioning=False):
def func(s, iterator):
return f(iterator)
return PipelinedRDD(self.rdd, func, preservesPartitioning, isFromBarrier=True) | [
"\n .. note:: Experimental\n\n Returns a new RDD by applying a function to each partition of the wrapped RDD,\n where tasks are launched together in a barrier stage.\n The interface is the same as :func:`RDD.mapPartitions`.\n Please see the API doc there.\n\n .. versionadde... |
Please provide a description of the function:def _to_seq(sc, cols, converter=None):
if converter:
cols = [converter(c) for c in cols]
return sc._jvm.PythonUtils.toSeq(cols) | [
"\n Convert a list of Column (or names) into a JVM Seq of Column.\n\n An optional `converter` could be used to convert items in `cols`\n into JVM Column objects.\n "
] |
Please provide a description of the function:def _to_list(sc, cols, converter=None):
if converter:
cols = [converter(c) for c in cols]
return sc._jvm.PythonUtils.toList(cols) | [
"\n Convert a list of Column (or names) into a JVM (Scala) List of Column.\n\n An optional `converter` could be used to convert items in `cols`\n into JVM Column objects.\n "
] |
Please provide a description of the function:def _unary_op(name, doc="unary operator"):
def _(self):
jc = getattr(self._jc, name)()
return Column(jc)
_.__doc__ = doc
return _ | [
" Create a method for given unary operator "
] |
Please provide a description of the function:def _bin_op(name, doc="binary operator"):
def _(self, other):
jc = other._jc if isinstance(other, Column) else other
njc = getattr(self._jc, name)(jc)
return Column(njc)
_.__doc__ = doc
return _ | [
" Create a method for given binary operator\n "
] |
Please provide a description of the function:def _reverse_op(name, doc="binary operator"):
def _(self, other):
jother = _create_column_from_literal(other)
jc = getattr(jother, name)(self._jc)
return Column(jc)
_.__doc__ = doc
return _ | [
" Create a method for binary operator (this object is on right side)\n "
] |
Please provide a description of the function:def substr(self, startPos, length):
if type(startPos) != type(length):
raise TypeError(
"startPos and length must be the same type. "
"Got {startPos_t} and {length_t}, respectively."
.format(
... | [
"\n Return a :class:`Column` which is a substring of the column.\n\n :param startPos: start position (int or Column)\n :param length: length of the substring (int or Column)\n\n >>> df.select(df.name.substr(1, 3).alias(\"col\")).collect()\n [Row(col=u'Ali'), Row(col=u'Bob')]\n ... |
Please provide a description of the function:def isin(self, *cols):
if len(cols) == 1 and isinstance(cols[0], (list, set)):
cols = cols[0]
cols = [c._jc if isinstance(c, Column) else _create_column_from_literal(c) for c in cols]
sc = SparkContext._active_spark_context
... | [
"\n A boolean expression that is evaluated to true if the value of this\n expression is contained by the evaluated values of the arguments.\n\n >>> df[df.name.isin(\"Bob\", \"Mike\")].collect()\n [Row(age=5, name=u'Bob')]\n >>> df[df.age.isin([1, 2, 3])].collect()\n [Row(ag... |
Please provide a description of the function:def alias(self, *alias, **kwargs):
metadata = kwargs.pop('metadata', None)
assert not kwargs, 'Unexpected kwargs where passed: %s' % kwargs
sc = SparkContext._active_spark_context
if len(alias) == 1:
if metadata:
... | [
"\n Returns this column aliased with a new name or names (in the case of expressions that\n return more than one column, such as explode).\n\n :param alias: strings of desired column names (collects all positional arguments passed)\n :param metadata: a dict of information to be stored in... |
Please provide a description of the function:def cast(self, dataType):
if isinstance(dataType, basestring):
jc = self._jc.cast(dataType)
elif isinstance(dataType, DataType):
from pyspark.sql import SparkSession
spark = SparkSession.builder.getOrCreate()
... | [
" Convert the column into type ``dataType``.\n\n >>> df.select(df.age.cast(\"string\").alias('ages')).collect()\n [Row(ages=u'2'), Row(ages=u'5')]\n >>> df.select(df.age.cast(StringType()).alias('ages')).collect()\n [Row(ages=u'2'), Row(ages=u'5')]\n "
] |
Please provide a description of the function:def when(self, condition, value):
if not isinstance(condition, Column):
raise TypeError("condition should be a Column")
v = value._jc if isinstance(value, Column) else value
jc = self._jc.when(condition._jc, v)
return Colu... | [
"\n Evaluates a list of conditions and returns one of multiple possible result expressions.\n If :func:`Column.otherwise` is not invoked, None is returned for unmatched conditions.\n\n See :func:`pyspark.sql.functions.when` for example usage.\n\n :param condition: a boolean :class:`Colum... |
Please provide a description of the function:def otherwise(self, value):
v = value._jc if isinstance(value, Column) else value
jc = self._jc.otherwise(v)
return Column(jc) | [
"\n Evaluates a list of conditions and returns one of multiple possible result expressions.\n If :func:`Column.otherwise` is not invoked, None is returned for unmatched conditions.\n\n See :func:`pyspark.sql.functions.when` for example usage.\n\n :param value: a literal value, or a :clas... |
Please provide a description of the function:def over(self, window):
from pyspark.sql.window import WindowSpec
if not isinstance(window, WindowSpec):
raise TypeError("window should be WindowSpec")
jc = self._jc.over(window._jspec)
return Column(jc) | [
"\n Define a windowing column.\n\n :param window: a :class:`WindowSpec`\n :return: a Column\n\n >>> from pyspark.sql import Window\n >>> window = Window.partitionBy(\"name\").orderBy(\"age\").rowsBetween(-1, 1)\n >>> from pyspark.sql.functions import rank, min\n >>> ... |
Please provide a description of the function:def transform(self, vector):
if isinstance(vector, RDD):
vector = vector.map(_convert_to_vector)
else:
vector = _convert_to_vector(vector)
return self.call("transform", vector) | [
"\n Applies transformation on a vector or an RDD[Vector].\n\n .. note:: In Python, transform cannot currently be used within\n an RDD transformation or action.\n Call transform directly on the RDD instead.\n\n :param vector: Vector or RDD of Vector to be transformed.\n ... |
Please provide a description of the function:def fit(self, dataset):
dataset = dataset.map(_convert_to_vector)
jmodel = callMLlibFunc("fitStandardScaler", self.withMean, self.withStd, dataset)
return StandardScalerModel(jmodel) | [
"\n Computes the mean and variance and stores as a model to be used\n for later scaling.\n\n :param dataset: The data used to compute the mean and variance\n to build the transformation model.\n :return: a StandardScalarModel\n "
] |
Please provide a description of the function:def fit(self, data):
jmodel = callMLlibFunc("fitChiSqSelector", self.selectorType, self.numTopFeatures,
self.percentile, self.fpr, self.fdr, self.fwe, data)
return ChiSqSelectorModel(jmodel) | [
"\n Returns a ChiSquared feature selector.\n\n :param data: an `RDD[LabeledPoint]` containing the labeled dataset\n with categorical features. Real-valued features will be\n treated as categorical for each distinct value.\n Apply feature disc... |
Please provide a description of the function:def fit(self, data):
jmodel = callMLlibFunc("fitPCA", self.k, data)
return PCAModel(jmodel) | [
"\n Computes a [[PCAModel]] that contains the principal components of the input vectors.\n :param data: source vectors\n "
] |
Please provide a description of the function:def transform(self, document):
if isinstance(document, RDD):
return document.map(self.transform)
freq = {}
for term in document:
i = self.indexOf(term)
freq[i] = 1.0 if self.binary else freq.get(i, 0) + 1.... | [
"\n Transforms the input document (list of terms) to term frequency\n vectors, or transform the RDD of document to RDD of term\n frequency vectors.\n "
] |
Please provide a description of the function:def fit(self, dataset):
if not isinstance(dataset, RDD):
raise TypeError("dataset should be an RDD of term frequency vectors")
jmodel = callMLlibFunc("fitIDF", self.minDocFreq, dataset.map(_convert_to_vector))
return IDFModel(jmod... | [
"\n Computes the inverse document frequency.\n\n :param dataset: an RDD of term frequency vectors\n "
] |
Please provide a description of the function:def findSynonyms(self, word, num):
if not isinstance(word, basestring):
word = _convert_to_vector(word)
words, similarity = self.call("findSynonyms", word, num)
return zip(words, similarity) | [
"\n Find synonyms of a word\n\n :param word: a word or a vector representation of word\n :param num: number of synonyms to find\n :return: array of (word, cosineSimilarity)\n\n .. note:: Local use only\n "
] |
Please provide a description of the function:def load(cls, sc, path):
jmodel = sc._jvm.org.apache.spark.mllib.feature \
.Word2VecModel.load(sc._jsc.sc(), path)
model = sc._jvm.org.apache.spark.mllib.api.python.Word2VecModelWrapper(jmodel)
return Word2VecModel(model) | [
"\n Load a model from the given path.\n "
] |
Please provide a description of the function:def transform(self, vector):
if isinstance(vector, RDD):
vector = vector.map(_convert_to_vector)
else:
vector = _convert_to_vector(vector)
return callMLlibFunc("elementwiseProductVector", self.scalingVector, vector) | [
"\n Computes the Hadamard product of the vector.\n "
] |
Please provide a description of the function:def predict(self, x):
if isinstance(x, RDD):
return self.call("predict", x.map(_convert_to_vector))
else:
return self.call("predict", _convert_to_vector(x)) | [
"\n Predict values for a single data point or an RDD of points using\n the model trained.\n\n .. note:: In Python, predict cannot currently be used within an RDD\n transformation or action.\n Call predict directly on the RDD instead.\n "
] |
Please provide a description of the function:def trainClassifier(cls, data, numClasses, categoricalFeaturesInfo,
impurity="gini", maxDepth=5, maxBins=32, minInstancesPerNode=1,
minInfoGain=0.0):
return cls._train(data, "classification", numClasses, catego... | [
"\n Train a decision tree model for classification.\n\n :param data:\n Training data: RDD of LabeledPoint. Labels should take values\n {0, 1, ..., numClasses-1}.\n :param numClasses:\n Number of classes for classification.\n :param categoricalFeaturesInfo:\n ... |
Please provide a description of the function:def trainRegressor(cls, data, categoricalFeaturesInfo,
impurity="variance", maxDepth=5, maxBins=32, minInstancesPerNode=1,
minInfoGain=0.0):
return cls._train(data, "regression", 0, categoricalFeaturesInfo,
... | [
"\n Train a decision tree model for regression.\n\n :param data:\n Training data: RDD of LabeledPoint. Labels are real numbers.\n :param categoricalFeaturesInfo:\n Map storing arity of categorical features. An entry (n -> k)\n indicates that feature n is categorical w... |
Please provide a description of the function:def trainClassifier(cls, data, numClasses, categoricalFeaturesInfo, numTrees,
featureSubsetStrategy="auto", impurity="gini", maxDepth=4, maxBins=32,
seed=None):
return cls._train(data, "classification", numClas... | [
"\n Train a random forest model for binary or multiclass\n classification.\n\n :param data:\n Training dataset: RDD of LabeledPoint. Labels should take values\n {0, 1, ..., numClasses-1}.\n :param numClasses:\n Number of classes for classification.\n :pa... |
Please provide a description of the function:def trainRegressor(cls, data, categoricalFeaturesInfo, numTrees, featureSubsetStrategy="auto",
impurity="variance", maxDepth=4, maxBins=32, seed=None):
return cls._train(data, "regression", 0, categoricalFeaturesInfo, numTrees,
... | [
"\n Train a random forest model for regression.\n\n :param data:\n Training dataset: RDD of LabeledPoint. Labels are real numbers.\n :param categoricalFeaturesInfo:\n Map storing arity of categorical features. An entry (n -> k)\n indicates that feature n is categorica... |
Please provide a description of the function:def trainClassifier(cls, data, categoricalFeaturesInfo,
loss="logLoss", numIterations=100, learningRate=0.1, maxDepth=3,
maxBins=32):
return cls._train(data, "classification", categoricalFeaturesInfo,
... | [
"\n Train a gradient-boosted trees model for classification.\n\n :param data:\n Training dataset: RDD of LabeledPoint. Labels should take values\n {0, 1}.\n :param categoricalFeaturesInfo:\n Map storing arity of categorical features. An entry (n -> k)\n indic... |
Please provide a description of the function:def set(self, key, value):
# Try to set self._jconf first if JVM is created, set self._conf if JVM is not created yet.
if self._jconf is not None:
self._jconf.set(key, unicode(value))
else:
self._conf[key] = unicode(va... | [
"Set a configuration property."
] |
Please provide a description of the function:def setIfMissing(self, key, value):
if self.get(key) is None:
self.set(key, value)
return self | [
"Set a configuration property, if not already set."
] |
Please provide a description of the function:def setExecutorEnv(self, key=None, value=None, pairs=None):
if (key is not None and pairs is not None) or (key is None and pairs is None):
raise Exception("Either pass one key-value pair or a list of pairs")
elif key is not None:
... | [
"Set an environment variable to be passed to executors."
] |
Please provide a description of the function:def setAll(self, pairs):
for (k, v) in pairs:
self.set(k, v)
return self | [
"\n Set multiple parameters, passed as a list of key-value pairs.\n\n :param pairs: list of key-value pairs to set\n "
] |
Please provide a description of the function:def get(self, key, defaultValue=None):
if defaultValue is None: # Py4J doesn't call the right get() if we pass None
if self._jconf is not None:
if not self._jconf.contains(key):
return None
re... | [
"Get the configured value for some key, or return a default otherwise."
] |
Please provide a description of the function:def getAll(self):
if self._jconf is not None:
return [(elem._1(), elem._2()) for elem in self._jconf.getAll()]
else:
return self._conf.items() | [
"Get all values as a list of key-value pairs."
] |
Please provide a description of the function:def contains(self, key):
if self._jconf is not None:
return self._jconf.contains(key)
else:
return key in self._conf | [
"Does this configuration contain a given key?"
] |
Please provide a description of the function:def toDebugString(self):
if self._jconf is not None:
return self._jconf.toDebugString()
else:
return '\n'.join('%s=%s' % (k, v) for k, v in self._conf.items()) | [
"\n Returns a printable version of the configuration, as a list of\n key=value pairs, one per line.\n "
] |
Please provide a description of the function:def listDatabases(self):
iter = self._jcatalog.listDatabases().toLocalIterator()
databases = []
while iter.hasNext():
jdb = iter.next()
databases.append(Database(
name=jdb.name(),
descri... | [
"Returns a list of databases available across all sessions."
] |
Please provide a description of the function:def listTables(self, dbName=None):
if dbName is None:
dbName = self.currentDatabase()
iter = self._jcatalog.listTables(dbName).toLocalIterator()
tables = []
while iter.hasNext():
jtable = iter.next()
... | [
"Returns a list of tables/views in the specified database.\n\n If no database is specified, the current database is used.\n This includes all temporary views.\n "
] |
Please provide a description of the function:def listFunctions(self, dbName=None):
if dbName is None:
dbName = self.currentDatabase()
iter = self._jcatalog.listFunctions(dbName).toLocalIterator()
functions = []
while iter.hasNext():
jfunction = iter.next(... | [
"Returns a list of functions registered in the specified database.\n\n If no database is specified, the current database is used.\n This includes all temporary functions.\n "
] |
Please provide a description of the function:def listColumns(self, tableName, dbName=None):
if dbName is None:
dbName = self.currentDatabase()
iter = self._jcatalog.listColumns(dbName, tableName).toLocalIterator()
columns = []
while iter.hasNext():
jcolum... | [
"Returns a list of columns for the given table/view in the specified database.\n\n If no database is specified, the current database is used.\n\n Note: the order of arguments here is different from that of its JVM counterpart\n because Python does not support method overloading.\n "
] |
Please provide a description of the function:def createExternalTable(self, tableName, path=None, source=None, schema=None, **options):
warnings.warn(
"createExternalTable is deprecated since Spark 2.2, please use createTable instead.",
DeprecationWarning)
return self.cre... | [
"Creates a table based on the dataset in a data source.\n\n It returns the DataFrame associated with the external table.\n\n The data source is specified by the ``source`` and a set of ``options``.\n If ``source`` is not specified, the default data source configured by\n ``spark.sql.sour... |
Please provide a description of the function:def createTable(self, tableName, path=None, source=None, schema=None, **options):
if path is not None:
options["path"] = path
if source is None:
source = self._sparkSession._wrapped._conf.defaultDataSourceName()
if sch... | [
"Creates a table based on the dataset in a data source.\n\n It returns the DataFrame associated with the table.\n\n The data source is specified by the ``source`` and a set of ``options``.\n If ``source`` is not specified, the default data source configured by\n ``spark.sql.sources.defau... |
Please provide a description of the function:def _load_from_socket(port, auth_secret):
(sockfile, sock) = local_connect_and_auth(port, auth_secret)
# The barrier() call may block forever, so no timeout
sock.settimeout(None)
# Make a barrier() function call.
write_int(BARRIER_FUNCTION, sockfile)... | [
"\n Load data from a given socket, this is a blocking method thus only return when the socket\n connection has been closed.\n "
] |
Please provide a description of the function:def _getOrCreate(cls):
if not isinstance(cls._taskContext, BarrierTaskContext):
cls._taskContext = object.__new__(cls)
return cls._taskContext | [
"\n Internal function to get or create global BarrierTaskContext. We need to make sure\n BarrierTaskContext is returned from here because it is needed in python worker reuse\n scenario, see SPARK-25921 for more details.\n "
] |
Please provide a description of the function:def _initialize(cls, port, secret):
cls._port = port
cls._secret = secret | [
"\n Initialize BarrierTaskContext, other methods within BarrierTaskContext can only be called\n after BarrierTaskContext is initialized.\n "
] |
Please provide a description of the function:def barrier(self):
if self._port is None or self._secret is None:
raise Exception("Not supported to call barrier() before initialize " +
"BarrierTaskContext.")
else:
_load_from_socket(self._port, se... | [
"\n .. note:: Experimental\n\n Sets a global barrier and waits until all tasks in this stage hit this barrier.\n Similar to `MPI_Barrier` function in MPI, this function blocks until all tasks\n in the same stage have reached this routine.\n\n .. warning:: In a barrier stage, each ... |
Please provide a description of the function:def getTaskInfos(self):
if self._port is None or self._secret is None:
raise Exception("Not supported to call getTaskInfos() before initialize " +
"BarrierTaskContext.")
else:
addresses = self._loca... | [
"\n .. note:: Experimental\n\n Returns :class:`BarrierTaskInfo` for all tasks in this barrier stage,\n ordered by partition ID.\n\n .. versionadded:: 2.4.0\n "
] |
Please provide a description of the function:def since(version):
import re
indent_p = re.compile(r'\n( +)')
def deco(f):
indents = indent_p.findall(f.__doc__)
indent = ' ' * (min(len(m) for m in indents) if indents else 0)
f.__doc__ = f.__doc__.rstrip() + "\n\n%s.. versionadded... | [
"\n A decorator that annotates a function to append the version of Spark the function was added.\n "
] |
Please provide a description of the function:def copy_func(f, name=None, sinceversion=None, doc=None):
# See
# http://stackoverflow.com/questions/6527633/how-can-i-make-a-deepcopy-of-a-function-in-python
fn = types.FunctionType(f.__code__, f.__globals__, name or f.__name__, f.__defaults__,
... | [
"\n Returns a function with same code, globals, defaults, closure, and\n name (or provide a new name).\n "
] |
Please provide a description of the function:def keyword_only(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
if len(args) > 0:
raise TypeError("Method %s forces keyword arguments." % func.__name__)
self._input_kwargs = kwargs
return func(self, **kwargs)
retu... | [
"\n A decorator that forces keyword arguments in the wrapped method\n and saves actual input keyword arguments in `_input_kwargs`.\n\n .. note:: Should only be used to wrap a method where first arg is `self`\n "
] |
Please provide a description of the function:def _gen_param_header(name, doc, defaultValueStr, typeConverter):
template = '''class Has$Name(Params):
$name = Param(Params._dummy(), "$name", "$doc", typeConverter=$typeConverter)
def __init__(self):
super(Has$Name, self).__init__()'''
... | [
"\n Generates the header part for shared variables\n\n :param name: param name\n :param doc: param doc\n ",
"\n Mixin for param $name: $doc\n "
] |
Please provide a description of the function:def _gen_param_code(name, doc, defaultValueStr):
# TODO: How to correctly inherit instance attributes?
template = '''
def set$Name(self, value):
return self._set($name=value)
def get$Name(self):
return self.getOrDefault... | [
"\n Generates Python code for a shared param class.\n\n :param name: param name\n :param doc: param doc\n :param defaultValueStr: string representation of the default value\n :return: code string\n ",
"\n Sets the value of :py:attr:`$name`.\n ",
"\n Gets the value of $name... |
Please provide a description of the function:def train(self, rdd, k=4, maxIterations=20, minDivisibleClusterSize=1.0, seed=-1888008604):
java_model = callMLlibFunc(
"trainBisectingKMeans", rdd.map(_convert_to_vector),
k, maxIterations, minDivisibleClusterSize, seed)
retu... | [
"\n Runs the bisecting k-means algorithm return the model.\n\n :param rdd:\n Training points as an `RDD` of `Vector` or convertible\n sequence types.\n :param k:\n The desired number of leaf clusters. The actual number could\n be smaller if there are no divis... |
Please provide a description of the function:def train(cls, rdd, k, maxIterations=100, runs=1, initializationMode="k-means||",
seed=None, initializationSteps=2, epsilon=1e-4, initialModel=None):
if runs != 1:
warnings.warn("The param `runs` has no effect since Spark 2.0.0.")
... | [
"\n Train a k-means clustering model.\n\n :param rdd:\n Training points as an `RDD` of `Vector` or convertible\n sequence types.\n :param k:\n Number of clusters to create.\n :param maxIterations:\n Maximum number of iterations allowed.\n (def... |
Please provide a description of the function:def train(cls, rdd, k, convergenceTol=1e-3, maxIterations=100, seed=None, initialModel=None):
initialModelWeights = None
initialModelMu = None
initialModelSigma = None
if initialModel is not None:
if initialModel.k != k:
... | [
"\n Train a Gaussian Mixture clustering model.\n\n :param rdd:\n Training points as an `RDD` of `Vector` or convertible\n sequence types.\n :param k:\n Number of independent Gaussians in the mixture model.\n :param convergenceTol:\n Maximum change in l... |
Please provide a description of the function:def load(cls, sc, path):
model = cls._load_java(sc, path)
wrapper =\
sc._jvm.org.apache.spark.mllib.api.python.PowerIterationClusteringModelWrapper(model)
return PowerIterationClusteringModel(wrapper) | [
"\n Load a model from the given path.\n "
] |
Please provide a description of the function:def train(cls, rdd, k, maxIterations=100, initMode="random"):
r
model = callMLlibFunc("trainPowerIterationClusteringModel",
rdd.map(_convert_to_vector), int(k), int(maxIterations), initMode)
return PowerIterationClusterin... | [
"\n :param rdd:\n An RDD of (i, j, s\\ :sub:`ij`\\) tuples representing the\n affinity matrix, which is the matrix A in the PIC paper. The\n similarity s\\ :sub:`ij`\\ must be nonnegative. This is a symmetric\n matrix and hence s\\ :sub:`ij`\\ = s\\ :sub:`ji`\\ For any ... |
Please provide a description of the function:def update(self, data, decayFactor, timeUnit):
if not isinstance(data, RDD):
raise TypeError("Data should be of an RDD, got %s." % type(data))
data = data.map(_convert_to_vector)
decayFactor = float(decayFactor)
if timeUni... | [
"Update the centroids, according to data\n\n :param data:\n RDD with new data for the model update.\n :param decayFactor:\n Forgetfulness of the previous centroids.\n :param timeUnit:\n Can be \"batches\" or \"points\". If points, then the decay factor\n is r... |
Please provide a description of the function:def setHalfLife(self, halfLife, timeUnit):
self._timeUnit = timeUnit
self._decayFactor = exp(log(0.5) / halfLife)
return self | [
"\n Set number of batches after which the centroids of that\n particular batch has half the weightage.\n "
] |
Please provide a description of the function:def setInitialCenters(self, centers, weights):
self._model = StreamingKMeansModel(centers, weights)
return self | [
"\n Set initial centers. Should be set before calling trainOn.\n "
] |
Please provide a description of the function:def setRandomCenters(self, dim, weight, seed):
rng = random.RandomState(seed)
clusterCenters = rng.randn(self._k, dim)
clusterWeights = tile(weight, self._k)
self._model = StreamingKMeansModel(clusterCenters, clusterWeights)
r... | [
"\n Set the initial centres to be random samples from\n a gaussian population with constant weights.\n "
] |
Please provide a description of the function:def trainOn(self, dstream):
self._validate(dstream)
def update(rdd):
self._model.update(rdd, self._decayFactor, self._timeUnit)
dstream.foreachRDD(update) | [
"Train the model on the incoming dstream."
] |
Please provide a description of the function:def predictOn(self, dstream):
self._validate(dstream)
return dstream.map(lambda x: self._model.predict(x)) | [
"\n Make predictions on a dstream.\n Returns a transformed dstream object\n "
] |
Please provide a description of the function:def predictOnValues(self, dstream):
self._validate(dstream)
return dstream.mapValues(lambda x: self._model.predict(x)) | [
"\n Make predictions on a keyed dstream.\n Returns a transformed dstream object.\n "
] |
Please provide a description of the function:def describeTopics(self, maxTermsPerTopic=None):
if maxTermsPerTopic is None:
topics = self.call("describeTopics")
else:
topics = self.call("describeTopics", maxTermsPerTopic)
return topics | [
"Return the topics described by weighted terms.\n\n WARNING: If vocabSize and k are large, this can return a large object!\n\n :param maxTermsPerTopic:\n Maximum number of terms to collect for each topic.\n (default: vocabulary size)\n :return:\n Array over topics. Ea... |
Please provide a description of the function:def load(cls, sc, path):
if not isinstance(sc, SparkContext):
raise TypeError("sc should be a SparkContext, got type %s" % type(sc))
if not isinstance(path, basestring):
raise TypeError("path should be a basestring, got type %... | [
"Load the LDAModel from disk.\n\n :param sc:\n SparkContext.\n :param path:\n Path to where the model is stored.\n "
] |
Please provide a description of the function:def train(cls, rdd, k=10, maxIterations=20, docConcentration=-1.0,
topicConcentration=-1.0, seed=None, checkpointInterval=10, optimizer="em"):
model = callMLlibFunc("trainLDAModel", rdd, k, maxIterations,
docConcen... | [
"Train a LDA model.\n\n :param rdd:\n RDD of documents, which are tuples of document IDs and term\n (word) count vectors. The term count vectors are \"bags of\n words\" with a fixed-size vocabulary (where the vocabulary size\n is the length of the vector). Document IDs mus... |
Please provide a description of the function:def _to_java_object_rdd(rdd):
rdd = rdd._reserialize(AutoBatchedSerializer(PickleSerializer()))
return rdd.ctx._jvm.org.apache.spark.mllib.api.python.SerDe.pythonToJava(rdd._jrdd, True) | [
" Return a JavaRDD of Object by unpickling\n\n It will convert each Python object into Java object by Pyrolite, whenever the\n RDD is serialized in batch or not.\n "
] |
Please provide a description of the function:def _py2java(sc, obj):
if isinstance(obj, RDD):
obj = _to_java_object_rdd(obj)
elif isinstance(obj, DataFrame):
obj = obj._jdf
elif isinstance(obj, SparkContext):
obj = obj._jsc
elif isinstance(obj, list):
obj = [_py2java(... | [
" Convert Python object into Java "
] |
Please provide a description of the function:def callJavaFunc(sc, func, *args):
args = [_py2java(sc, a) for a in args]
return _java2py(sc, func(*args)) | [
" Call Java Function "
] |
Please provide a description of the function:def callMLlibFunc(name, *args):
sc = SparkContext.getOrCreate()
api = getattr(sc._jvm.PythonMLLibAPI(), name)
return callJavaFunc(sc, api, *args) | [
" Call API in PythonMLLibAPI "
] |
Please provide a description of the function:def inherit_doc(cls):
for name, func in vars(cls).items():
# only inherit docstring for public functions
if name.startswith("_"):
continue
if not func.__doc__:
for parent in cls.__bases__:
parent_func =... | [
"\n A decorator that makes a class inherit documentation from its parents.\n "
] |
Please provide a description of the function:def call(self, name, *a):
return callJavaFunc(self._sc, getattr(self._java_model, name), *a) | [
"Call method of java_model"
] |
Please provide a description of the function:def count(self):
return self.mapPartitions(lambda i: [sum(1 for _ in i)]).reduce(operator.add) | [
"\n Return a new DStream in which each RDD has a single element\n generated by counting each RDD of this DStream.\n "
] |
Please provide a description of the function:def filter(self, f):
def func(iterator):
return filter(f, iterator)
return self.mapPartitions(func, True) | [
"\n Return a new DStream containing only the elements that satisfy predicate.\n "
] |
Please provide a description of the function:def map(self, f, preservesPartitioning=False):
def func(iterator):
return map(f, iterator)
return self.mapPartitions(func, preservesPartitioning) | [
"\n Return a new DStream by applying a function to each element of DStream.\n "
] |
Please provide a description of the function:def mapPartitionsWithIndex(self, f, preservesPartitioning=False):
return self.transform(lambda rdd: rdd.mapPartitionsWithIndex(f, preservesPartitioning)) | [
"\n Return a new DStream in which each RDD is generated by applying\n mapPartitionsWithIndex() to each RDDs of this DStream.\n "
] |
Please provide a description of the function:def reduce(self, func):
return self.map(lambda x: (None, x)).reduceByKey(func, 1).map(lambda x: x[1]) | [
"\n Return a new DStream in which each RDD has a single element\n generated by reducing each RDD of this DStream.\n "
] |
Please provide a description of the function:def reduceByKey(self, func, numPartitions=None):
if numPartitions is None:
numPartitions = self._sc.defaultParallelism
return self.combineByKey(lambda x: x, func, func, numPartitions) | [
"\n Return a new DStream by applying reduceByKey to each RDD.\n "
] |
Please provide a description of the function:def combineByKey(self, createCombiner, mergeValue, mergeCombiners,
numPartitions=None):
if numPartitions is None:
numPartitions = self._sc.defaultParallelism
def func(rdd):
return rdd.combineByKey(createC... | [
"\n Return a new DStream by applying combineByKey to each RDD.\n "
] |
Please provide a description of the function:def partitionBy(self, numPartitions, partitionFunc=portable_hash):
return self.transform(lambda rdd: rdd.partitionBy(numPartitions, partitionFunc)) | [
"\n Return a copy of the DStream in which each RDD are partitioned\n using the specified partitioner.\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.