Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def array_repeat(col, count):
sc = SparkContext._active_spark_context
return Column(sc._jvm.functions.array_repeat(_to_java_column(col), count)) | [
"\n Collection function: creates an array containing a column repeated count times.\n\n >>> df = spark.createDataFrame([('ab',)], ['data'])\n >>> df.select(array_repeat(df.data, 3).alias('r')).collect()\n [Row(r=[u'ab', u'ab', u'ab'])]\n "
] |
Please provide a description of the function:def map_concat(*cols):
sc = SparkContext._active_spark_context
if len(cols) == 1 and isinstance(cols[0], (list, set)):
cols = cols[0]
jc = sc._jvm.functions.map_concat(_to_seq(sc, cols, _to_java_column))
return Column(jc) | [
"Returns the union of all the given maps.\n\n :param cols: list of column names (string) or list of :class:`Column` expressions\n\n >>> from pyspark.sql.functions import map_concat\n >>> df = spark.sql(\"SELECT map(1, 'a', 2, 'b') as map1, map(3, 'c', 1, 'd') as map2\")\n >>> df.select(map_concat(\"map1... |
Please provide a description of the function:def sequence(start, stop, step=None):
sc = SparkContext._active_spark_context
if step is None:
return Column(sc._jvm.functions.sequence(_to_java_column(start), _to_java_column(stop)))
else:
return Column(sc._jvm.functions.sequence(
... | [
"\n Generate a sequence of integers from `start` to `stop`, incrementing by `step`.\n If `step` is not set, incrementing by 1 if `start` is less than or equal to `stop`,\n otherwise -1.\n\n >>> df1 = spark.createDataFrame([(-2, 2)], ('C1', 'C2'))\n >>> df1.select(sequence('C1', 'C2').alias('r')).coll... |
Please provide a description of the function:def from_csv(col, schema, options={}):
sc = SparkContext._active_spark_context
if isinstance(schema, basestring):
schema = _create_column_from_literal(schema)
elif isinstance(schema, Column):
schema = _to_java_column(schema)
else:
... | [
"\n Parses a column containing a CSV string to a row with the specified schema.\n Returns `null`, in the case of an unparseable string.\n\n :param col: string column in CSV format\n :param schema: a string with schema in DDL format to use when parsing the CSV column.\n :param options: options to cont... |
Please provide a description of the function:def udf(f=None, returnType=StringType()):
# The following table shows most of Python data and SQL type conversions in normal UDFs that
# are not yet visible to the user. Some of behaviors are buggy and might be changed in the near
# future. The table might ... | [
"Creates a user defined function (UDF).\n\n .. note:: The user-defined functions are considered deterministic by default. Due to\n optimization, duplicate invocations may be eliminated or the function may even be invoked\n more times than it is present in the query. If your function is not determin... |
Please provide a description of the function:def pandas_udf(f=None, returnType=None, functionType=None):
# The following table shows most of Pandas data and SQL type conversions in Pandas UDFs that
# are not yet visible to the user. Some of behaviors are buggy and might be changed in the near
# future... | [
"\n Creates a vectorized user defined function (UDF).\n\n :param f: user-defined function. A python function if used as a standalone function\n :param returnType: the return type of the user-defined function. The value can be either a\n :class:`pyspark.sql.types.DataType` object or a DDL-formatted t... |
Please provide a description of the function:def to_str(value):
if isinstance(value, bool):
return str(value).lower()
elif value is None:
return value
else:
return str(value) | [
"\n A wrapper over str(), but converts bool values to lower case strings.\n If None is given, just returns None, instead of converting it to string \"None\".\n "
] |
Please provide a description of the function:def _set_opts(self, schema=None, **options):
if schema is not None:
self.schema(schema)
for k, v in options.items():
if v is not None:
self.option(k, v) | [
"\n Set named options (filter out those the value is None)\n "
] |
Please provide a description of the function:def format(self, source):
self._jreader = self._jreader.format(source)
return self | [
"Specifies the input data source format.\n\n :param source: string, name of the data source, e.g. 'json', 'parquet'.\n\n >>> df = spark.read.format('json').load('python/test_support/sql/people.json')\n >>> df.dtypes\n [('age', 'bigint'), ('name', 'string')]\n\n "
] |
Please provide a description of the function:def schema(self, schema):
from pyspark.sql import SparkSession
spark = SparkSession.builder.getOrCreate()
if isinstance(schema, StructType):
jschema = spark._jsparkSession.parseDataType(schema.json())
self._jreader = s... | [
"Specifies the input schema.\n\n Some data sources (e.g. JSON) can infer the input schema automatically from data.\n By specifying the schema here, the underlying data source can skip the schema\n inference step, and thus speed up data loading.\n\n :param schema: a :class:`pyspark.sql.ty... |
Please provide a description of the function:def option(self, key, value):
self._jreader = self._jreader.option(key, to_str(value))
return self | [
"Adds an input option for the underlying data source.\n\n You can set the following option(s) for reading files:\n * ``timeZone``: sets the string that indicates a timezone to be used to parse timestamps\n in the JSON/CSV datasources or partition values.\n If it isn't... |
Please provide a description of the function:def options(self, **options):
for k in options:
self._jreader = self._jreader.option(k, to_str(options[k]))
return self | [
"Adds input options for the underlying data source.\n\n You can set the following option(s) for reading files:\n * ``timeZone``: sets the string that indicates a timezone to be used to parse timestamps\n in the JSON/CSV datasources or partition values.\n If it isn't s... |
Please provide a description of the function:def load(self, path=None, format=None, schema=None, **options):
if format is not None:
self.format(format)
if schema is not None:
self.schema(schema)
self.options(**options)
if isinstance(path, basestring):
... | [
"Loads data from a data source and returns it as a :class`DataFrame`.\n\n :param path: optional string or a list of string for file-system backed data sources.\n :param format: optional string for format of the data source. Default to 'parquet'.\n :param schema: optional :class:`pyspark.sql.typ... |
Please provide a description of the function:def json(self, path, schema=None, primitivesAsString=None, prefersDecimal=None,
allowComments=None, allowUnquotedFieldNames=None, allowSingleQuotes=None,
allowNumericLeadingZero=None, allowBackslashEscapingAnyCharacter=None,
mode=None, ... | [
"\n Loads JSON files and returns the results as a :class:`DataFrame`.\n\n `JSON Lines <http://jsonlines.org/>`_ (newline-delimited JSON) is supported by default.\n For JSON (one record per file), set the ``multiLine`` parameter to ``true``.\n\n If the ``schema`` parameter is not specifie... |
Please provide a description of the function:def parquet(self, *paths):
return self._df(self._jreader.parquet(_to_seq(self._spark._sc, paths))) | [
"Loads Parquet files, returning the result as a :class:`DataFrame`.\n\n You can set the following Parquet-specific option(s) for reading Parquet files:\n * ``mergeSchema``: sets whether we should merge schemas collected from all \\\n Parquet part-files. This will override ``spark.sq... |
Please provide a description of the function:def text(self, paths, wholetext=False, lineSep=None):
self._set_opts(wholetext=wholetext, lineSep=lineSep)
if isinstance(paths, basestring):
paths = [paths]
return self._df(self._jreader.text(self._spark._sc._jvm.PythonUtils.toSeq... | [
"\n Loads text files and returns a :class:`DataFrame` whose schema starts with a\n string column named \"value\", and followed by partitioned columns if there\n are any.\n The text files must be encoded as UTF-8.\n\n By default, each line in the text file is a new row in the resul... |
Please provide a description of the function:def csv(self, path, schema=None, sep=None, encoding=None, quote=None, escape=None,
comment=None, header=None, inferSchema=None, ignoreLeadingWhiteSpace=None,
ignoreTrailingWhiteSpace=None, nullValue=None, nanValue=None, positiveInf=None,
n... | [
"Loads a CSV file and returns the result as a :class:`DataFrame`.\n\n This function will go through the input once to determine the input schema if\n ``inferSchema`` is enabled. To avoid going through the entire data once, disable\n ``inferSchema`` option or specify the schema explicitly using... |
Please provide a description of the function:def orc(self, path):
if isinstance(path, basestring):
path = [path]
return self._df(self._jreader.orc(_to_seq(self._spark._sc, path))) | [
"Loads ORC files, returning the result as a :class:`DataFrame`.\n\n >>> df = spark.read.orc('python/test_support/sql/orc_partitioned')\n >>> df.dtypes\n [('a', 'bigint'), ('b', 'int'), ('c', 'int')]\n "
] |
Please provide a description of the function:def jdbc(self, url, table, column=None, lowerBound=None, upperBound=None, numPartitions=None,
predicates=None, properties=None):
if properties is None:
properties = dict()
jprop = JavaClass("java.util.Properties", self._spark... | [
"\n Construct a :class:`DataFrame` representing the database table named ``table``\n accessible via JDBC URL ``url`` and connection ``properties``.\n\n Partitions of the table will be retrieved in parallel if either ``column`` or\n ``predicates`` is specified. ``lowerBound`, ``upperBound... |
Please provide a description of the function:def mode(self, saveMode):
# At the JVM side, the default value of mode is already set to "error".
# So, if the given saveMode is None, we will not call JVM-side's mode method.
if saveMode is not None:
self._jwrite = self._jwrite.m... | [
"Specifies the behavior when data or table already exists.\n\n Options include:\n\n * `append`: Append contents of this :class:`DataFrame` to existing data.\n * `overwrite`: Overwrite existing data.\n * `error` or `errorifexists`: Throw an exception if data already exists.\n * `ig... |
Please provide a description of the function:def format(self, source):
self._jwrite = self._jwrite.format(source)
return self | [
"Specifies the underlying output data source.\n\n :param source: string, name of the data source, e.g. 'json', 'parquet'.\n\n >>> df.write.format('json').save(os.path.join(tempfile.mkdtemp(), 'data'))\n "
] |
Please provide a description of the function:def option(self, key, value):
self._jwrite = self._jwrite.option(key, to_str(value))
return self | [
"Adds an output option for the underlying data source.\n\n You can set the following option(s) for writing files:\n * ``timeZone``: sets the string that indicates a timezone to be used to format\n timestamps in the JSON/CSV datasources or partition values.\n If it isn... |
Please provide a description of the function:def options(self, **options):
for k in options:
self._jwrite = self._jwrite.option(k, to_str(options[k]))
return self | [
"Adds output options for the underlying data source.\n\n You can set the following option(s) for writing files:\n * ``timeZone``: sets the string that indicates a timezone to be used to format\n timestamps in the JSON/CSV datasources or partition values.\n If it isn't... |
Please provide a description of the function:def partitionBy(self, *cols):
if len(cols) == 1 and isinstance(cols[0], (list, tuple)):
cols = cols[0]
self._jwrite = self._jwrite.partitionBy(_to_seq(self._spark._sc, cols))
return self | [
"Partitions the output by the given columns on the file system.\n\n If specified, the output is laid out on the file system similar\n to Hive's partitioning scheme.\n\n :param cols: name of columns\n\n >>> df.write.partitionBy('year', 'month').parquet(os.path.join(tempfile.mkdtemp(), 'da... |
Please provide a description of the function:def sortBy(self, col, *cols):
if isinstance(col, (list, tuple)):
if cols:
raise ValueError("col is a {0} but cols are not empty".format(type(col)))
col, cols = col[0], col[1:]
if not all(isinstance(c, basestr... | [
"Sorts the output in each bucket by the given columns on the file system.\n\n :param col: a name of a column, or a list of names.\n :param cols: additional names (optional). If `col` is a list it should be empty.\n\n >>> (df.write.format('parquet') # doctest: +SKIP\n ... .bucketBy(1... |
Please provide a description of the function:def save(self, path=None, format=None, mode=None, partitionBy=None, **options):
self.mode(mode).options(**options)
if partitionBy is not None:
self.partitionBy(partitionBy)
if format is not None:
self.format(format)
... | [
"Saves the contents of the :class:`DataFrame` to a data source.\n\n The data source is specified by the ``format`` and a set of ``options``.\n If ``format`` is not specified, the default data source configured by\n ``spark.sql.sources.default`` will be used.\n\n :param path: the path in ... |
Please provide a description of the function:def insertInto(self, tableName, overwrite=False):
self._jwrite.mode("overwrite" if overwrite else "append").insertInto(tableName) | [
"Inserts the content of the :class:`DataFrame` to the specified table.\n\n It requires that the schema of the class:`DataFrame` is the same as the\n schema of the table.\n\n Optionally overwriting any existing data.\n "
] |
Please provide a description of the function:def saveAsTable(self, name, format=None, mode=None, partitionBy=None, **options):
self.mode(mode).options(**options)
if partitionBy is not None:
self.partitionBy(partitionBy)
if format is not None:
self.format(format)
... | [
"Saves the content of the :class:`DataFrame` as the specified table.\n\n In the case the table already exists, behavior of this function depends on the\n save mode, specified by the `mode` function (default to throwing an exception).\n When `mode` is `Overwrite`, the schema of the :class:`DataF... |
Please provide a description of the function:def json(self, path, mode=None, compression=None, dateFormat=None, timestampFormat=None,
lineSep=None, encoding=None):
self.mode(mode)
self._set_opts(
compression=compression, dateFormat=dateFormat, timestampFormat=timestampF... | [
"Saves the content of the :class:`DataFrame` in JSON format\n (`JSON Lines text format or newline-delimited JSON <http://jsonlines.org/>`_) at the\n specified path.\n\n :param path: the path in any Hadoop supported file system\n :param mode: specifies the behavior of the save operation w... |
Please provide a description of the function:def parquet(self, path, mode=None, partitionBy=None, compression=None):
self.mode(mode)
if partitionBy is not None:
self.partitionBy(partitionBy)
self._set_opts(compression=compression)
self._jwrite.parquet(path) | [
"Saves the content of the :class:`DataFrame` in Parquet format at the specified path.\n\n :param path: the path in any Hadoop supported file system\n :param mode: specifies the behavior of the save operation when data already exists.\n\n * ``append``: Append contents of this :class:`DataFra... |
Please provide a description of the function:def text(self, path, compression=None, lineSep=None):
self._set_opts(compression=compression, lineSep=lineSep)
self._jwrite.text(path) | [
"Saves the content of the DataFrame in a text file at the specified path.\n The text files will be encoded as UTF-8.\n\n :param path: the path in any Hadoop supported file system\n :param compression: compression codec to use when saving to file. This can be one of the\n ... |
Please provide a description of the function:def csv(self, path, mode=None, compression=None, sep=None, quote=None, escape=None,
header=None, nullValue=None, escapeQuotes=None, quoteAll=None, dateFormat=None,
timestampFormat=None, ignoreLeadingWhiteSpace=None, ignoreTrailingWhiteSpace=None,
... | [
"Saves the content of the :class:`DataFrame` in CSV format at the specified path.\n\n :param path: the path in any Hadoop supported file system\n :param mode: specifies the behavior of the save operation when data already exists.\n\n * ``append``: Append contents of this :class:`DataFrame` ... |
Please provide a description of the function:def orc(self, path, mode=None, partitionBy=None, compression=None):
self.mode(mode)
if partitionBy is not None:
self.partitionBy(partitionBy)
self._set_opts(compression=compression)
self._jwrite.orc(path) | [
"Saves the content of the :class:`DataFrame` in ORC format at the specified path.\n\n :param path: the path in any Hadoop supported file system\n :param mode: specifies the behavior of the save operation when data already exists.\n\n * ``append``: Append contents of this :class:`DataFrame` ... |
Please provide a description of the function:def jdbc(self, url, table, mode=None, properties=None):
if properties is None:
properties = dict()
jprop = JavaClass("java.util.Properties", self._spark._sc._gateway._gateway_client)()
for k in properties:
jprop.setPro... | [
"Saves the content of the :class:`DataFrame` to an external database table via JDBC.\n\n .. note:: Don't create too many partitions in parallel on a large cluster;\n otherwise Spark might crash your external database systems.\n\n :param url: a JDBC URL of the form ``jdbc:subprotocol:subname... |
Please provide a description of the function:def createStream(ssc, kinesisAppName, streamName, endpointUrl, regionName,
initialPositionInStream, checkpointInterval,
storageLevel=StorageLevel.MEMORY_AND_DISK_2,
awsAccessKeyId=None, awsSecretKey=None, decoder... | [
"\n Create an input stream that pulls messages from a Kinesis stream. This uses the\n Kinesis Client Library (KCL) to pull messages from Kinesis.\n\n .. note:: The given AWS credentials will get saved in DStream checkpoints if checkpointing\n is enabled. Make sure that your checkpoin... |
Please provide a description of the function:def choose_jira_assignee(issue, asf_jira):
while True:
try:
reporter = issue.fields.reporter
commentors = map(lambda x: x.author, issue.fields.comment.comments)
candidates = set(commentors)
candidates.add(repor... | [
"\n Prompt the user to choose who to assign the issue to in jira, given a list of candidates,\n including the original reporter and all commentors\n "
] |
Please provide a description of the function:def standardize_jira_ref(text):
jira_refs = []
components = []
# If the string is compliant, no need to process any further
if (re.search(r'^\[SPARK-[0-9]{3,6}\](\[[A-Z0-9_\s,]+\] )+\S+', text)):
return text
# Extract JIRA ref(s):
patte... | [
"\n Standardize the [SPARK-XXXXX] [MODULE] prefix\n Converts \"[SPARK-XXX][mllib] Issue\", \"[MLLib] SPARK-XXX. Issue\" or \"SPARK XXX [MLLIB]: Issue\" to\n \"[SPARK-XXX][MLLIB] Issue\"\n\n >>> standardize_jira_ref(\n ... \"[SPARK-5821] [SQL] ParquetRelation2 CTAS should check if delete is succes... |
Please provide a description of the function:def _parse_libsvm_line(line):
items = line.split(None)
label = float(items[0])
nnz = len(items) - 1
indices = np.zeros(nnz, dtype=np.int32)
values = np.zeros(nnz)
for i in xrange(nnz):
index, value = items[... | [
"\n Parses a line in LIBSVM format into (label, indices, values).\n "
] |
Please provide a description of the function:def _convert_labeled_point_to_libsvm(p):
from pyspark.mllib.regression import LabeledPoint
assert isinstance(p, LabeledPoint)
items = [str(p.label)]
v = _convert_to_vector(p.features)
if isinstance(v, SparseVector):
... | [
"Converts a LabeledPoint to a string in LIBSVM format."
] |
Please provide a description of the function:def loadLibSVMFile(sc, path, numFeatures=-1, minPartitions=None):
from pyspark.mllib.regression import LabeledPoint
lines = sc.textFile(path, minPartitions)
parsed = lines.map(lambda l: MLUtils._parse_libsvm_line(l))
if numFeatures <... | [
"\n Loads labeled data in the LIBSVM format into an RDD of\n LabeledPoint. The LIBSVM format is a text-based format used by\n LIBSVM and LIBLINEAR. Each line represents a labeled sparse\n feature vector using the following format:\n\n label index1:value1 index2:value2 ...\n\n ... |
Please provide a description of the function:def saveAsLibSVMFile(data, dir):
lines = data.map(lambda p: MLUtils._convert_labeled_point_to_libsvm(p))
lines.saveAsTextFile(dir) | [
"\n Save labeled data in LIBSVM format.\n\n :param data: an RDD of LabeledPoint to be saved\n :param dir: directory to save the data\n\n >>> from tempfile import NamedTemporaryFile\n >>> from fileinput import input\n >>> from pyspark.mllib.regression import LabeledPoint\n ... |
Please provide a description of the function:def loadLabeledPoints(sc, path, minPartitions=None):
minPartitions = minPartitions or min(sc.defaultParallelism, 2)
return callMLlibFunc("loadLabeledPoints", sc, path, minPartitions) | [
"\n Load labeled points saved using RDD.saveAsTextFile.\n\n :param sc: Spark context\n :param path: file or directory path in any Hadoop-supported file\n system URI\n :param minPartitions: min number of partitions\n @return: labeled data stored as an RDD of Lab... |
Please provide a description of the function:def appendBias(data):
vec = _convert_to_vector(data)
if isinstance(vec, SparseVector):
newIndices = np.append(vec.indices, len(vec))
newValues = np.append(vec.values, 1.0)
return SparseVector(len(vec) + 1, newIndic... | [
"\n Returns a new vector with `1.0` (bias) appended to\n the end of the input vector.\n "
] |
Please provide a description of the function:def convertVectorColumnsToML(dataset, *cols):
if not isinstance(dataset, DataFrame):
raise TypeError("Input dataset must be a DataFrame but got {}.".format(type(dataset)))
return callMLlibFunc("convertVectorColumnsToML", dataset, list(col... | [
"\n Converts vector columns in an input DataFrame from the\n :py:class:`pyspark.mllib.linalg.Vector` type to the new\n :py:class:`pyspark.ml.linalg.Vector` type under the `spark.ml`\n package.\n\n :param dataset:\n input dataset\n :param cols:\n a list of ... |
Please provide a description of the function:def generateLinearInput(intercept, weights, xMean, xVariance,
nPoints, seed, eps):
weights = [float(weight) for weight in weights]
xMean = [float(mean) for mean in xMean]
xVariance = [float(var) for var in xVarianc... | [
"\n :param: intercept bias factor, the term c in X'w + c\n :param: weights feature vector, the term w in X'w + c\n :param: xMean Point around which the data X is centered.\n :param: xVariance Variance of the given data\n :param: nPoints Number of points to be generated\n ... |
Please provide a description of the function:def generateLinearRDD(sc, nexamples, nfeatures, eps,
nParts=2, intercept=0.0):
return callMLlibFunc(
"generateLinearRDDWrapper", sc, int(nexamples), int(nfeatures),
float(eps), int(nParts), float(intercept)) | [
"\n Generate an RDD of LabeledPoints.\n "
] |
Please provide a description of the function:def train(cls, data, iterations=100, step=1.0, miniBatchFraction=1.0,
initialWeights=None, regParam=0.0, regType=None, intercept=False,
validateData=True, convergenceTol=0.001):
warnings.warn(
"Deprecated in 2.0.0. Use... | [
"\n Train a linear regression model using Stochastic Gradient\n Descent (SGD). This solves the least squares regression\n formulation\n\n f(weights) = 1/(2n) ||A weights - y||^2\n\n which is the mean squared error. Here the data matrix has n rows,\n and the input RDD ho... |
Please provide a description of the function:def predict(self, x):
if isinstance(x, RDD):
return x.map(lambda v: self.predict(v))
return np.interp(x, self.boundaries, self.predictions) | [
"\n Predict labels for provided features.\n Using a piecewise linear function.\n 1) If x exactly matches a boundary then associated prediction\n is returned. In case there are multiple predictions with the\n same boundary then one of them is returned. Which one is\n undefin... |
Please provide a description of the function:def save(self, sc, path):
java_boundaries = _py2java(sc, self.boundaries.tolist())
java_predictions = _py2java(sc, self.predictions.tolist())
java_model = sc._jvm.org.apache.spark.mllib.regression.IsotonicRegressionModel(
java_bou... | [
"Save an IsotonicRegressionModel."
] |
Please provide a description of the function:def load(cls, sc, path):
java_model = sc._jvm.org.apache.spark.mllib.regression.IsotonicRegressionModel.load(
sc._jsc.sc(), path)
py_boundaries = _java2py(sc, java_model.boundaryVector()).toArray()
py_predictions = _java2py(sc, ja... | [
"Load an IsotonicRegressionModel."
] |
Please provide a description of the function:def train(cls, data, isotonic=True):
boundaries, predictions = callMLlibFunc("trainIsotonicRegressionModel",
data.map(_convert_to_vector), bool(isotonic))
return IsotonicRegressionModel(boundaries.toArr... | [
"\n Train an isotonic regression model on the given data.\n\n :param data:\n RDD of (label, feature, weight) tuples.\n :param isotonic:\n Whether this is isotonic (which is default) or antitonic.\n (default: True)\n "
] |
Please provide a description of the function:def columnSimilarities(self, threshold=0.0):
java_sims_mat = self._java_matrix_wrapper.call("columnSimilarities", float(threshold))
return CoordinateMatrix(java_sims_mat) | [
"\n Compute similarities between columns of this matrix.\n\n The threshold parameter is a trade-off knob between estimate\n quality and computational cost.\n\n The default threshold setting of 0 guarantees deterministically\n correct results, but uses the brute-force approach of c... |
Please provide a description of the function:def tallSkinnyQR(self, computeQ=False):
decomp = JavaModelWrapper(self._java_matrix_wrapper.call("tallSkinnyQR", computeQ))
if computeQ:
java_Q = decomp.call("Q")
Q = RowMatrix(java_Q)
else:
Q = None
... | [
"\n Compute the QR decomposition of this RowMatrix.\n\n The implementation is designed to optimize the QR decomposition\n (factorization) for the RowMatrix of a tall and skinny shape.\n\n Reference:\n Paul G. Constantine, David F. Gleich. \"Tall and skinny QR\n factorizat... |
Please provide a description of the function:def computeSVD(self, k, computeU=False, rCond=1e-9):
j_model = self._java_matrix_wrapper.call(
"computeSVD", int(k), bool(computeU), float(rCond))
return SingularValueDecomposition(j_model) | [
"\n Computes the singular value decomposition of the RowMatrix.\n\n The given row matrix A of dimension (m X n) is decomposed into\n U * s * V'T where\n\n * U: (m X k) (left singular vectors) is a RowMatrix whose\n columns are the eigenvectors of (A X A')\n * s: DenseV... |
Please provide a description of the function:def multiply(self, matrix):
if not isinstance(matrix, DenseMatrix):
raise ValueError("Only multiplication with DenseMatrix "
"is supported.")
j_model = self._java_matrix_wrapper.call("multiply", matrix)
... | [
"\n Multiply this matrix by a local dense matrix on the right.\n\n :param matrix: a local dense matrix whose number of rows must match the number of columns\n of this matrix\n :returns: :py:class:`RowMatrix`\n\n >>> rm = RowMatrix(sc.parallelize([[0, 1], [2, 3]]))\n... |
Please provide a description of the function:def U(self):
u = self.call("U")
if u is not None:
mat_name = u.getClass().getSimpleName()
if mat_name == "RowMatrix":
return RowMatrix(u)
elif mat_name == "IndexedRowMatrix":
return ... | [
"\n Returns a distributed matrix whose columns are the left\n singular vectors of the SingularValueDecomposition if computeU was set to be True.\n "
] |
Please provide a description of the function:def rows(self):
# We use DataFrames for serialization of IndexedRows from
# Java, so we first convert the RDD of rows to a DataFrame
# on the Scala/Java side. Then we map each Row in the
# DataFrame back to an IndexedRow on this side.... | [
"\n Rows of the IndexedRowMatrix stored as an RDD of IndexedRows.\n\n >>> mat = IndexedRowMatrix(sc.parallelize([IndexedRow(0, [1, 2, 3]),\n ... IndexedRow(1, [4, 5, 6])]))\n >>> rows = mat.rows\n >>> rows.first()\n IndexedRow(0, [1.0,... |
Please provide a description of the function:def toBlockMatrix(self, rowsPerBlock=1024, colsPerBlock=1024):
java_block_matrix = self._java_matrix_wrapper.call("toBlockMatrix",
rowsPerBlock,
... | [
"\n Convert this matrix to a BlockMatrix.\n\n :param rowsPerBlock: Number of rows that make up each block.\n The blocks forming the final rows are not\n required to have the given number of rows.\n :param colsPerBlock: Number of columns th... |
Please provide a description of the function:def multiply(self, matrix):
if not isinstance(matrix, DenseMatrix):
raise ValueError("Only multiplication with DenseMatrix "
"is supported.")
return IndexedRowMatrix(self._java_matrix_wrapper.call("multiply", ... | [
"\n Multiply this matrix by a local dense matrix on the right.\n\n :param matrix: a local dense matrix whose number of rows must match the number of columns\n of this matrix\n :returns: :py:class:`IndexedRowMatrix`\n\n >>> mat = IndexedRowMatrix(sc.parallelize([(0, ... |
Please provide a description of the function:def entries(self):
# We use DataFrames for serialization of MatrixEntry entries
# from Java, so we first convert the RDD of entries to a
# DataFrame on the Scala/Java side. Then we map each Row in
# the DataFrame back to a MatrixEntry... | [
"\n Entries of the CoordinateMatrix stored as an RDD of\n MatrixEntries.\n\n >>> mat = CoordinateMatrix(sc.parallelize([MatrixEntry(0, 0, 1.2),\n ... MatrixEntry(6, 4, 2.1)]))\n >>> entries = mat.entries\n >>> entries.first()\n ... |
Please provide a description of the function:def blocks(self):
# We use DataFrames for serialization of sub-matrix blocks
# from Java, so we first convert the RDD of blocks to a
# DataFrame on the Scala/Java side. Then we map each Row in
# the DataFrame back to a sub-matrix bloc... | [
"\n The RDD of sub-matrix blocks\n ((blockRowIndex, blockColIndex), sub-matrix) that form this\n distributed matrix.\n\n >>> mat = BlockMatrix(\n ... sc.parallelize([((0, 0), Matrices.dense(3, 2, [1, 2, 3, 4, 5, 6])),\n ... ((1, 0), Matrices.dense(3,... |
Please provide a description of the function:def persist(self, storageLevel):
if not isinstance(storageLevel, StorageLevel):
raise TypeError("`storageLevel` should be a StorageLevel, got %s" % type(storageLevel))
javaStorageLevel = self._java_matrix_wrapper._sc._getJavaStorageLevel(... | [
"\n Persists the underlying RDD with the specified storage level.\n "
] |
Please provide a description of the function:def add(self, other):
if not isinstance(other, BlockMatrix):
raise TypeError("Other should be a BlockMatrix, got %s" % type(other))
other_java_block_matrix = other._java_matrix_wrapper._java_model
java_block_matrix = self._java_m... | [
"\n Adds two block matrices together. The matrices must have the\n same size and matching `rowsPerBlock` and `colsPerBlock` values.\n If one of the sub matrix blocks that are being added is a\n SparseMatrix, the resulting sub matrix block will also be a\n SparseMatrix, even if it ... |
Please provide a description of the function:def transpose(self):
java_transposed_matrix = self._java_matrix_wrapper.call("transpose")
return BlockMatrix(java_transposed_matrix, self.colsPerBlock, self.rowsPerBlock) | [
"\n Transpose this BlockMatrix. Returns a new BlockMatrix\n instance sharing the same underlying data. Is a lazy operation.\n\n >>> blocks = sc.parallelize([((0, 0), Matrices.dense(3, 2, [1, 2, 3, 4, 5, 6])),\n ... ((1, 0), Matrices.dense(3, 2, [7, 8, 9, 10, 11, ... |
Please provide a description of the function:def _vector_size(v):
if isinstance(v, Vector):
return len(v)
elif type(v) in (array.array, list, tuple, xrange):
return len(v)
elif type(v) == np.ndarray:
if v.ndim == 1 or (v.ndim == 2 and v.shape[1] == 1):
return len(v)
... | [
"\n Returns the size of the vector.\n\n >>> _vector_size([1., 2., 3.])\n 3\n >>> _vector_size((1., 2., 3.))\n 3\n >>> _vector_size(array.array('d', [1., 2., 3.]))\n 3\n >>> _vector_size(np.zeros(3))\n 3\n >>> _vector_size(np.zeros((3, 1)))\n 3\n >>> _vector_size(np.zeros((1, 3)))... |
Please provide a description of the function:def parse(s):
start = s.find('[')
if start == -1:
raise ValueError("Array should start with '['.")
end = s.find(']')
if end == -1:
raise ValueError("Array should end with ']'.")
s = s[start + 1: end]
... | [
"\n Parse string representation back into the DenseVector.\n\n >>> DenseVector.parse(' [ 0.0,1.0,2.0, 3.0]')\n DenseVector([0.0, 1.0, 2.0, 3.0])\n "
] |
Please provide a description of the function:def dot(self, other):
if type(other) == np.ndarray:
if other.ndim > 1:
assert len(self) == other.shape[0], "dimension mismatch"
return np.dot(self.array, other)
elif _have_scipy and scipy.sparse.issparse(other)... | [
"\n Compute the dot product of two Vectors. We support\n (Numpy array, list, SparseVector, or SciPy sparse)\n and a target NumPy array that is either 1- or 2-dimensional.\n Equivalent to calling numpy.dot of the two vectors.\n\n >>> dense = DenseVector(array.array('d', [1., 2.]))\... |
Please provide a description of the function:def squared_distance(self, other):
assert len(self) == _vector_size(other), "dimension mismatch"
if isinstance(other, SparseVector):
return other.squared_distance(self)
elif _have_scipy and scipy.sparse.issparse(other):
... | [
"\n Squared distance of two Vectors.\n\n >>> dense1 = DenseVector(array.array('d', [1., 2.]))\n >>> dense1.squared_distance(dense1)\n 0.0\n >>> dense2 = np.array([2., 1.])\n >>> dense1.squared_distance(dense2)\n 2.0\n >>> dense3 = [2., 1.]\n >>> dense1.... |
Please provide a description of the function:def parse(s):
start = s.find('(')
if start == -1:
raise ValueError("Tuple should start with '('")
end = s.find(')')
if end == -1:
raise ValueError("Tuple should end with ')'")
s = s[start + 1: end].stri... | [
"\n Parse string representation back into the SparseVector.\n\n >>> SparseVector.parse(' (4, [0,1 ],[ 4.0,5.0] )')\n SparseVector(4, {0: 4.0, 1: 5.0})\n "
] |
Please provide a description of the function:def dot(self, other):
if isinstance(other, np.ndarray):
if other.ndim not in [2, 1]:
raise ValueError("Cannot call dot with %d-dimensional array" % other.ndim)
assert len(self) == other.shape[0], "dimension mismatch"
... | [
"\n Dot product with a SparseVector or 1- or 2-dimensional Numpy array.\n\n >>> a = SparseVector(4, [1, 3], [3.0, 4.0])\n >>> a.dot(a)\n 25.0\n >>> a.dot(array.array('d', [1., 2., 3., 4.]))\n 22.0\n >>> b = SparseVector(4, [2], [1.0])\n >>> a.dot(b)\n 0... |
Please provide a description of the function:def squared_distance(self, other):
assert len(self) == _vector_size(other), "dimension mismatch"
if isinstance(other, np.ndarray) or isinstance(other, DenseVector):
if isinstance(other, np.ndarray) and other.ndim != 1:
ra... | [
"\n Squared distance from a SparseVector or 1-dimensional NumPy array.\n\n >>> a = SparseVector(4, [1, 3], [3.0, 4.0])\n >>> a.squared_distance(a)\n 0.0\n >>> a.squared_distance(array.array('d', [1., 2., 3., 4.]))\n 11.0\n >>> a.squared_distance(np.array([1., 2., 3.,... |
Please provide a description of the function:def toArray(self):
arr = np.zeros((self.size,), dtype=np.float64)
arr[self.indices] = self.values
return arr | [
"\n Returns a copy of this SparseVector as a 1-dimensional NumPy array.\n "
] |
Please provide a description of the function:def asML(self):
return newlinalg.SparseVector(self.size, self.indices, self.values) | [
"\n Convert this vector to the new mllib-local representation.\n This does NOT copy the data; it copies references.\n\n :return: :py:class:`pyspark.ml.linalg.SparseVector`\n\n .. versionadded:: 2.0.0\n "
] |
Please provide a description of the function:def dense(*elements):
if len(elements) == 1 and not isinstance(elements[0], (float, int, long)):
# it's list, numpy.array or other iterable object.
elements = elements[0]
return DenseVector(elements) | [
"\n Create a dense vector of 64-bit floats from a Python list or numbers.\n\n >>> Vectors.dense([1, 2, 3])\n DenseVector([1.0, 2.0, 3.0])\n >>> Vectors.dense(1.0, 2.0)\n DenseVector([1.0, 2.0])\n "
] |
Please provide a description of the function:def fromML(vec):
if isinstance(vec, newlinalg.DenseVector):
return DenseVector(vec.array)
elif isinstance(vec, newlinalg.SparseVector):
return SparseVector(vec.size, vec.indices, vec.values)
else:
raise Typ... | [
"\n Convert a vector from the new mllib-local representation.\n This does NOT copy the data; it copies references.\n\n :param vec: a :py:class:`pyspark.ml.linalg.Vector`\n :return: a :py:class:`pyspark.mllib.linalg.Vector`\n\n .. versionadded:: 2.0.0\n "
] |
Please provide a description of the function:def squared_distance(v1, v2):
v1, v2 = _convert_to_vector(v1), _convert_to_vector(v2)
return v1.squared_distance(v2) | [
"\n Squared distance between two vectors.\n a and b can be of type SparseVector, DenseVector, np.ndarray\n or array.array.\n\n >>> a = Vectors.sparse(4, [(0, 1), (3, 4)])\n >>> b = Vectors.dense([2, 5, 4, 1])\n >>> a.squared_distance(b)\n 51.0\n "
] |
Please provide a description of the function:def parse(s):
if s.find('(') == -1 and s.find('[') != -1:
return DenseVector.parse(s)
elif s.find('(') != -1:
return SparseVector.parse(s)
else:
raise ValueError(
"Cannot find tokens '[' or ... | [
"Parse a string representation back into the Vector.\n\n >>> Vectors.parse('[2,1,2 ]')\n DenseVector([2.0, 1.0, 2.0])\n >>> Vectors.parse(' ( 100, [0], [2])')\n SparseVector(100, {0: 2.0})\n "
] |
Please provide a description of the function:def _equals(v1_indices, v1_values, v2_indices, v2_values):
v1_size = len(v1_values)
v2_size = len(v2_values)
k1 = 0
k2 = 0
all_equal = True
while all_equal:
while k1 < v1_size and v1_values[k1] == 0:
... | [
"\n Check equality between sparse/dense vectors,\n v1_indices and v2_indices assume to be strictly increasing.\n "
] |
Please provide a description of the function:def _convert_to_array(array_like, dtype):
if isinstance(array_like, bytes):
return np.frombuffer(array_like, dtype=dtype)
return np.asarray(array_like, dtype=dtype) | [
"\n Convert Matrix attributes which are array-like or buffer to array.\n "
] |
Please provide a description of the function:def toArray(self):
if self.isTransposed:
return np.asfortranarray(
self.values.reshape((self.numRows, self.numCols)))
else:
return self.values.reshape((self.numRows, self.numCols), order='F') | [
"\n Return an numpy.ndarray\n\n >>> m = DenseMatrix(2, 2, range(4))\n >>> m.toArray()\n array([[ 0., 2.],\n [ 1., 3.]])\n "
] |
Please provide a description of the function:def toSparse(self):
if self.isTransposed:
values = np.ravel(self.toArray(), order='F')
else:
values = self.values
indices = np.nonzero(values)[0]
colCounts = np.bincount(indices // self.numRows)
colPtrs... | [
"Convert to SparseMatrix"
] |
Please provide a description of the function:def asML(self):
return newlinalg.DenseMatrix(self.numRows, self.numCols, self.values, self.isTransposed) | [
"\n Convert this matrix to the new mllib-local representation.\n This does NOT copy the data; it copies references.\n\n :return: :py:class:`pyspark.ml.linalg.DenseMatrix`\n\n .. versionadded:: 2.0.0\n "
] |
Please provide a description of the function:def toArray(self):
A = np.zeros((self.numRows, self.numCols), dtype=np.float64, order='F')
for k in xrange(self.colPtrs.size - 1):
startptr = self.colPtrs[k]
endptr = self.colPtrs[k + 1]
if self.isTransposed:
... | [
"\n Return an numpy.ndarray\n "
] |
Please provide a description of the function:def asML(self):
return newlinalg.SparseMatrix(self.numRows, self.numCols, self.colPtrs, self.rowIndices,
self.values, self.isTransposed) | [
"\n Convert this matrix to the new mllib-local representation.\n This does NOT copy the data; it copies references.\n\n :return: :py:class:`pyspark.ml.linalg.SparseMatrix`\n\n .. versionadded:: 2.0.0\n "
] |
Please provide a description of the function:def sparse(numRows, numCols, colPtrs, rowIndices, values):
return SparseMatrix(numRows, numCols, colPtrs, rowIndices, values) | [
"\n Create a SparseMatrix\n "
] |
Please provide a description of the function:def fromML(mat):
if isinstance(mat, newlinalg.DenseMatrix):
return DenseMatrix(mat.numRows, mat.numCols, mat.values, mat.isTransposed)
elif isinstance(mat, newlinalg.SparseMatrix):
return SparseMatrix(mat.numRows, mat.numCols,... | [
"\n Convert a matrix from the new mllib-local representation.\n This does NOT copy the data; it copies references.\n\n :param mat: a :py:class:`pyspark.ml.linalg.Matrix`\n :return: a :py:class:`pyspark.mllib.linalg.Matrix`\n\n .. versionadded:: 2.0.0\n "
] |
Please provide a description of the function:def approxNearestNeighbors(self, dataset, key, numNearestNeighbors, distCol="distCol"):
return self._call_java("approxNearestNeighbors", dataset, key, numNearestNeighbors,
distCol) | [
"\n Given a large dataset and an item, approximately find at most k items which have the\n closest distance to the item. If the :py:attr:`outputCol` is missing, the method will\n transform the data; if the :py:attr:`outputCol` exists, it will use that. This allows\n caching of the transf... |
Please provide a description of the function:def approxSimilarityJoin(self, datasetA, datasetB, threshold, distCol="distCol"):
threshold = TypeConverters.toFloat(threshold)
return self._call_java("approxSimilarityJoin", datasetA, datasetB, threshold, distCol) | [
"\n Join two datasets to approximately find all pairs of rows whose distance are smaller than\n the threshold. If the :py:attr:`outputCol` is missing, the method will transform the data;\n if the :py:attr:`outputCol` exists, it will use that. This allows caching of the\n transformed data... |
Please provide a description of the function:def from_labels(cls, labels, inputCol, outputCol=None, handleInvalid=None):
sc = SparkContext._active_spark_context
java_class = sc._gateway.jvm.java.lang.String
jlabels = StringIndexerModel._new_java_array(labels, java_class)
model =... | [
"\n Construct the model directly from an array of label strings,\n requires an active SparkContext.\n "
] |
Please provide a description of the function:def from_arrays_of_labels(cls, arrayOfLabels, inputCols, outputCols=None,
handleInvalid=None):
sc = SparkContext._active_spark_context
java_class = sc._gateway.jvm.java.lang.String
jlabels = StringIndexerModel._n... | [
"\n Construct the model directly from an array of array of label strings,\n requires an active SparkContext.\n "
] |
Please provide a description of the function:def setParams(self, inputCol=None, outputCol=None, stopWords=None, caseSensitive=False,
locale=None):
kwargs = self._input_kwargs
return self._set(**kwargs) | [
"\n setParams(self, inputCol=None, outputCol=None, stopWords=None, caseSensitive=false, \\\n locale=None)\n Sets params for this StopWordRemover.\n "
] |
Please provide a description of the function:def loadDefaultStopWords(language):
stopWordsObj = _jvm().org.apache.spark.ml.feature.StopWordsRemover
return list(stopWordsObj.loadDefaultStopWords(language)) | [
"\n Loads the default stop words for the given language.\n Supported languages: danish, dutch, english, finnish, french, german, hungarian,\n italian, norwegian, portuguese, russian, spanish, swedish, turkish\n "
] |
Please provide a description of the function:def findSynonyms(self, word, num):
if not isinstance(word, basestring):
word = _convert_to_vector(word)
return self._call_java("findSynonyms", word, num) | [
"\n Find \"num\" number of words closest in similarity to \"word\".\n word can be a string or vector representation.\n Returns a dataframe with two fields word and similarity (which\n gives the cosine similarity).\n "
] |
Please provide a description of the function:def findSynonymsArray(self, word, num):
if not isinstance(word, basestring):
word = _convert_to_vector(word)
tuples = self._java_obj.findSynonymsArray(word, num)
return list(map(lambda st: (st._1(), st._2()), list(tuples))) | [
"\n Find \"num\" number of words closest in similarity to \"word\".\n word can be a string or vector representation.\n Returns an array with two fields word and similarity (which\n gives the cosine similarity).\n "
] |
Please provide a description of the function:def install_exception_handler():
original = py4j.protocol.get_return_value
# The original `get_return_value` is not patched, it's idempotent.
patched = capture_sql_exception(original)
# only patch the one used in py4j.java_gateway (call Java API)
py4... | [
"\n Hook an exception handler into Py4j, which could capture some SQL exceptions in Java.\n\n When calling Java API, it will call `get_return_value` to parse the returned object.\n If any exception happened in JVM, the result will be Java exception object, it raise\n py4j.protocol.Py4JJavaError. We repl... |
Please provide a description of the function:def toJArray(gateway, jtype, arr):
jarr = gateway.new_array(jtype, len(arr))
for i in range(0, len(arr)):
jarr[i] = arr[i]
return jarr | [
"\n Convert python list to java type array\n :param gateway: Py4j Gateway\n :param jtype: java type of element in array\n :param arr: python type list\n "
] |
Please provide a description of the function:def require_minimum_pandas_version():
# TODO(HyukjinKwon): Relocate and deduplicate the version specification.
minimum_pandas_version = "0.19.2"
from distutils.version import LooseVersion
try:
import pandas
have_pandas = True
except ... | [
" Raise ImportError if minimum version of Pandas is not installed\n "
] |
Please provide a description of the function:def require_minimum_pyarrow_version():
# TODO(HyukjinKwon): Relocate and deduplicate the version specification.
minimum_pyarrow_version = "0.12.1"
from distutils.version import LooseVersion
try:
import pyarrow
have_arrow = True
excep... | [
" Raise ImportError if minimum version of pyarrow is not installed\n "
] |
Please provide a description of the function:def launch_gateway(conf=None, popen_kwargs=None):
if "PYSPARK_GATEWAY_PORT" in os.environ:
gateway_port = int(os.environ["PYSPARK_GATEWAY_PORT"])
gateway_secret = os.environ["PYSPARK_GATEWAY_SECRET"]
# Process already exists
proc = No... | [
"\n launch jvm gateway\n :param conf: spark configuration passed to spark-submit\n :param popen_kwargs: Dictionary of kwargs to pass to Popen when spawning\n the py4j JVM. This is a developer feature intended for use in\n customizing how pyspark interacts with the py4j JVM (e.g., capturing\n ... |
Please provide a description of the function:def _do_server_auth(conn, auth_secret):
write_with_length(auth_secret.encode("utf-8"), conn)
conn.flush()
reply = UTF8Deserializer().loads(conn)
if reply != "ok":
conn.close()
raise Exception("Unexpected reply from iterator server.") | [
"\n Performs the authentication protocol defined by the SocketAuthHelper class on the given\n file-like object 'conn'.\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.