repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
apple/turicreate
src/unity/python/turicreate/toolkits/text_analytics/_util.py
count_words
def count_words(text, to_lower=True, delimiters=DEFAULT_DELIMITERS): """ If `text` is an SArray of strings or an SArray of lists of strings, the occurances of word are counted for each row in the SArray. If `text` is an SArray of dictionaries, the keys are tokenized and the values are the counts. Counts for the same word, in the same row, are added together. This output is commonly known as the "bag-of-words" representation of text data. Parameters ---------- text : SArray[str | dict | list] SArray of type: string, dict or list. to_lower : bool, optional If True, all strings are converted to lower case before counting. delimiters : list[str], None, optional Input strings are tokenized using `delimiters` characters in this list. Each entry in this list must contain a single character. If set to `None`, then a Penn treebank-style tokenization is used, which contains smart handling of punctuations. Returns ------- out : SArray[dict] An SArray with the same length as the`text` input. For each row, the keys of the dictionary are the words and the values are the corresponding counts. See Also -------- count_ngrams, tf_idf, tokenize, References ---------- - `Bag of words model <http://en.wikipedia.org/wiki/Bag-of-words_model>`_ - `Penn treebank tokenization <https://web.archive.org/web/19970614072242/http://www.cis.upenn.edu:80/~treebank/tokenization.html>`_ Examples -------- .. sourcecode:: python >>> import turicreate # Create input data >>> sa = turicreate.SArray(["The quick brown fox jumps.", "Word word WORD, word!!!word"]) # Run count_words >>> turicreate.text_analytics.count_words(sa) dtype: dict Rows: 2 [{'quick': 1, 'brown': 1, 'the': 1, 'fox': 1, 'jumps.': 1}, {'word,': 5}] # Run count_words with Penn treebank style tokenization to handle # punctuations >>> turicreate.text_analytics.count_words(sa, delimiters=None) dtype: dict Rows: 2 [{'brown': 1, 'jumps': 1, 'fox': 1, '.': 1, 'quick': 1, 'the': 1}, {'word': 3, 'word!!!word': 1, ',': 1}] # Run count_words with dictionary input >>> sa = turicreate.SArray([{'alice bob': 1, 'Bob alice': 0.5}, {'a dog': 0, 'a dog cat': 5}]) >>> turicreate.text_analytics.count_words(sa) dtype: dict Rows: 2 [{'bob': 1.5, 'alice': 1.5}, {'a': 5, 'dog': 5, 'cat': 5}] # Run count_words with list input >>> sa = turicreate.SArray([['one', 'bar bah'], ['a dog', 'a dog cat']]) >>> turicreate.text_analytics.count_words(sa) dtype: dict Rows: 2 [{'bar': 1, 'bah': 1, 'one': 1}, {'a': 2, 'dog': 2, 'cat': 1}] """ _raise_error_if_not_sarray(text, "text") ## Compute word counts sf = _turicreate.SFrame({'docs': text}) fe = _feature_engineering.WordCounter(features='docs', to_lower=to_lower, delimiters=delimiters, output_column_prefix=None) output_sf = fe.fit_transform(sf) return output_sf['docs']
python
def count_words(text, to_lower=True, delimiters=DEFAULT_DELIMITERS): """ If `text` is an SArray of strings or an SArray of lists of strings, the occurances of word are counted for each row in the SArray. If `text` is an SArray of dictionaries, the keys are tokenized and the values are the counts. Counts for the same word, in the same row, are added together. This output is commonly known as the "bag-of-words" representation of text data. Parameters ---------- text : SArray[str | dict | list] SArray of type: string, dict or list. to_lower : bool, optional If True, all strings are converted to lower case before counting. delimiters : list[str], None, optional Input strings are tokenized using `delimiters` characters in this list. Each entry in this list must contain a single character. If set to `None`, then a Penn treebank-style tokenization is used, which contains smart handling of punctuations. Returns ------- out : SArray[dict] An SArray with the same length as the`text` input. For each row, the keys of the dictionary are the words and the values are the corresponding counts. See Also -------- count_ngrams, tf_idf, tokenize, References ---------- - `Bag of words model <http://en.wikipedia.org/wiki/Bag-of-words_model>`_ - `Penn treebank tokenization <https://web.archive.org/web/19970614072242/http://www.cis.upenn.edu:80/~treebank/tokenization.html>`_ Examples -------- .. sourcecode:: python >>> import turicreate # Create input data >>> sa = turicreate.SArray(["The quick brown fox jumps.", "Word word WORD, word!!!word"]) # Run count_words >>> turicreate.text_analytics.count_words(sa) dtype: dict Rows: 2 [{'quick': 1, 'brown': 1, 'the': 1, 'fox': 1, 'jumps.': 1}, {'word,': 5}] # Run count_words with Penn treebank style tokenization to handle # punctuations >>> turicreate.text_analytics.count_words(sa, delimiters=None) dtype: dict Rows: 2 [{'brown': 1, 'jumps': 1, 'fox': 1, '.': 1, 'quick': 1, 'the': 1}, {'word': 3, 'word!!!word': 1, ',': 1}] # Run count_words with dictionary input >>> sa = turicreate.SArray([{'alice bob': 1, 'Bob alice': 0.5}, {'a dog': 0, 'a dog cat': 5}]) >>> turicreate.text_analytics.count_words(sa) dtype: dict Rows: 2 [{'bob': 1.5, 'alice': 1.5}, {'a': 5, 'dog': 5, 'cat': 5}] # Run count_words with list input >>> sa = turicreate.SArray([['one', 'bar bah'], ['a dog', 'a dog cat']]) >>> turicreate.text_analytics.count_words(sa) dtype: dict Rows: 2 [{'bar': 1, 'bah': 1, 'one': 1}, {'a': 2, 'dog': 2, 'cat': 1}] """ _raise_error_if_not_sarray(text, "text") ## Compute word counts sf = _turicreate.SFrame({'docs': text}) fe = _feature_engineering.WordCounter(features='docs', to_lower=to_lower, delimiters=delimiters, output_column_prefix=None) output_sf = fe.fit_transform(sf) return output_sf['docs']
[ "def", "count_words", "(", "text", ",", "to_lower", "=", "True", ",", "delimiters", "=", "DEFAULT_DELIMITERS", ")", ":", "_raise_error_if_not_sarray", "(", "text", ",", "\"text\"", ")", "## Compute word counts", "sf", "=", "_turicreate", ".", "SFrame", "(", "{", "'docs'", ":", "text", "}", ")", "fe", "=", "_feature_engineering", ".", "WordCounter", "(", "features", "=", "'docs'", ",", "to_lower", "=", "to_lower", ",", "delimiters", "=", "delimiters", ",", "output_column_prefix", "=", "None", ")", "output_sf", "=", "fe", ".", "fit_transform", "(", "sf", ")", "return", "output_sf", "[", "'docs'", "]" ]
If `text` is an SArray of strings or an SArray of lists of strings, the occurances of word are counted for each row in the SArray. If `text` is an SArray of dictionaries, the keys are tokenized and the values are the counts. Counts for the same word, in the same row, are added together. This output is commonly known as the "bag-of-words" representation of text data. Parameters ---------- text : SArray[str | dict | list] SArray of type: string, dict or list. to_lower : bool, optional If True, all strings are converted to lower case before counting. delimiters : list[str], None, optional Input strings are tokenized using `delimiters` characters in this list. Each entry in this list must contain a single character. If set to `None`, then a Penn treebank-style tokenization is used, which contains smart handling of punctuations. Returns ------- out : SArray[dict] An SArray with the same length as the`text` input. For each row, the keys of the dictionary are the words and the values are the corresponding counts. See Also -------- count_ngrams, tf_idf, tokenize, References ---------- - `Bag of words model <http://en.wikipedia.org/wiki/Bag-of-words_model>`_ - `Penn treebank tokenization <https://web.archive.org/web/19970614072242/http://www.cis.upenn.edu:80/~treebank/tokenization.html>`_ Examples -------- .. sourcecode:: python >>> import turicreate # Create input data >>> sa = turicreate.SArray(["The quick brown fox jumps.", "Word word WORD, word!!!word"]) # Run count_words >>> turicreate.text_analytics.count_words(sa) dtype: dict Rows: 2 [{'quick': 1, 'brown': 1, 'the': 1, 'fox': 1, 'jumps.': 1}, {'word,': 5}] # Run count_words with Penn treebank style tokenization to handle # punctuations >>> turicreate.text_analytics.count_words(sa, delimiters=None) dtype: dict Rows: 2 [{'brown': 1, 'jumps': 1, 'fox': 1, '.': 1, 'quick': 1, 'the': 1}, {'word': 3, 'word!!!word': 1, ',': 1}] # Run count_words with dictionary input >>> sa = turicreate.SArray([{'alice bob': 1, 'Bob alice': 0.5}, {'a dog': 0, 'a dog cat': 5}]) >>> turicreate.text_analytics.count_words(sa) dtype: dict Rows: 2 [{'bob': 1.5, 'alice': 1.5}, {'a': 5, 'dog': 5, 'cat': 5}] # Run count_words with list input >>> sa = turicreate.SArray([['one', 'bar bah'], ['a dog', 'a dog cat']]) >>> turicreate.text_analytics.count_words(sa) dtype: dict Rows: 2 [{'bar': 1, 'bah': 1, 'one': 1}, {'a': 2, 'dog': 2, 'cat': 1}]
[ "If", "text", "is", "an", "SArray", "of", "strings", "or", "an", "SArray", "of", "lists", "of", "strings", "the", "occurances", "of", "word", "are", "counted", "for", "each", "row", "in", "the", "SArray", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/text_analytics/_util.py#L24-L117
train
apple/turicreate
src/unity/python/turicreate/toolkits/text_analytics/_util.py
count_ngrams
def count_ngrams(text, n=2, method="word", to_lower=True, delimiters=DEFAULT_DELIMITERS, ignore_punct=True, ignore_space=True): """ Return an SArray of ``dict`` type where each element contains the count for each of the n-grams that appear in the corresponding input element. The n-grams can be specified to be either character n-grams or word n-grams. The input SArray could contain strings, dicts with string keys and numeric values, or lists of strings. Parameters ---------- Text : SArray[str | dict | list] Input text data. n : int, optional The number of words in each n-gram. An ``n`` value of 1 returns word counts. method : {'word', 'character'}, optional If "word", the function performs a count of word n-grams. If "character", does a character n-gram count. to_lower : bool, optional If True, all words are converted to lower case before counting. delimiters : list[str], None, optional If method is "word", input strings are tokenized using `delimiters` characters in this list. Each entry in this list must contain a single character. If set to `None`, then a Penn treebank-style tokenization is used, which contains smart handling of punctuations. If method is "character," this option is ignored. ignore_punct : bool, optional If method is "character", indicates if *punctuations* between words are counted as part of the n-gram. For instance, with the input SArray element of "fun.games", if this parameter is set to False one tri-gram would be 'n.g'. If ``ignore_punct`` is set to True, there would be no such tri-gram (there would still be 'nga'). This parameter has no effect if the method is set to "word". ignore_space : bool, optional If method is "character", indicates if *spaces* between words are counted as part of the n-gram. For instance, with the input SArray element of "fun games", if this parameter is set to False one tri-gram would be 'n g'. If ``ignore_space`` is set to True, there would be no such tri-gram (there would still be 'nga'). This parameter has no effect if the method is set to "word". Returns ------- out : SArray[dict] An SArray of dictionary type, where each key is the n-gram string and each value is its count. See Also -------- count_words, tokenize, Notes ----- - Ignoring case (with ``to_lower``) involves a full string copy of the SArray data. To increase speed for large documents, set ``to_lower`` to False. - Punctuation and spaces are both delimiters by default when counting word n-grams. When counting character n-grams, one may choose to ignore punctuations, spaces, neither, or both. References ---------- - `N-gram wikipedia article <http://en.wikipedia.org/wiki/N-gram>`_ - `Penn treebank tokenization <https://web.archive.org/web/19970614072242/http://www.cis.upenn.edu:80/~treebank/tokenization.html>`_ Examples -------- .. sourcecode:: python >>> import turicreate # Counting word n-grams: >>> sa = turicreate.SArray(['I like big dogs. I LIKE BIG DOGS.']) >>> turicreate.text_analytics.count_ngrams(sa, 3) dtype: dict Rows: 1 [{'big dogs i': 1, 'like big dogs': 2, 'dogs i like': 1, 'i like big': 2}] # Counting character n-grams: >>> sa = turicreate.SArray(['Fun. Is. Fun']) >>> turicreate.text_analytics.count_ngrams(sa, 3, "character") dtype: dict Rows: 1 {'fun': 2, 'nis': 1, 'sfu': 1, 'isf': 1, 'uni': 1}] # Run count_ngrams with dictionary input >>> sa = turicreate.SArray([{'alice bob': 1, 'Bob alice': 0.5}, {'a dog': 0, 'a dog cat': 5}]) >>> turicreate.text_analytics.count_ngrams(sa) dtype: dict Rows: 2 [{'bob alice': 0.5, 'alice bob': 1}, {'dog cat': 5, 'a dog': 5}] # Run count_ngrams with list input >>> sa = turicreate.SArray([['one', 'bar bah'], ['a dog', 'a dog cat']]) >>> turicreate.text_analytics.count_ngrams(sa) dtype: dict Rows: 2 [{'bar bah': 1}, {'dog cat': 1, 'a dog': 2}] """ _raise_error_if_not_sarray(text, "text") # Compute ngrams counts sf = _turicreate.SFrame({'docs': text}) fe = _feature_engineering.NGramCounter(features='docs', n=n, method=method, to_lower=to_lower, delimiters=delimiters, ignore_punct=ignore_punct, ignore_space=ignore_space, output_column_prefix=None) output_sf = fe.fit_transform(sf) return output_sf['docs']
python
def count_ngrams(text, n=2, method="word", to_lower=True, delimiters=DEFAULT_DELIMITERS, ignore_punct=True, ignore_space=True): """ Return an SArray of ``dict`` type where each element contains the count for each of the n-grams that appear in the corresponding input element. The n-grams can be specified to be either character n-grams or word n-grams. The input SArray could contain strings, dicts with string keys and numeric values, or lists of strings. Parameters ---------- Text : SArray[str | dict | list] Input text data. n : int, optional The number of words in each n-gram. An ``n`` value of 1 returns word counts. method : {'word', 'character'}, optional If "word", the function performs a count of word n-grams. If "character", does a character n-gram count. to_lower : bool, optional If True, all words are converted to lower case before counting. delimiters : list[str], None, optional If method is "word", input strings are tokenized using `delimiters` characters in this list. Each entry in this list must contain a single character. If set to `None`, then a Penn treebank-style tokenization is used, which contains smart handling of punctuations. If method is "character," this option is ignored. ignore_punct : bool, optional If method is "character", indicates if *punctuations* between words are counted as part of the n-gram. For instance, with the input SArray element of "fun.games", if this parameter is set to False one tri-gram would be 'n.g'. If ``ignore_punct`` is set to True, there would be no such tri-gram (there would still be 'nga'). This parameter has no effect if the method is set to "word". ignore_space : bool, optional If method is "character", indicates if *spaces* between words are counted as part of the n-gram. For instance, with the input SArray element of "fun games", if this parameter is set to False one tri-gram would be 'n g'. If ``ignore_space`` is set to True, there would be no such tri-gram (there would still be 'nga'). This parameter has no effect if the method is set to "word". Returns ------- out : SArray[dict] An SArray of dictionary type, where each key is the n-gram string and each value is its count. See Also -------- count_words, tokenize, Notes ----- - Ignoring case (with ``to_lower``) involves a full string copy of the SArray data. To increase speed for large documents, set ``to_lower`` to False. - Punctuation and spaces are both delimiters by default when counting word n-grams. When counting character n-grams, one may choose to ignore punctuations, spaces, neither, or both. References ---------- - `N-gram wikipedia article <http://en.wikipedia.org/wiki/N-gram>`_ - `Penn treebank tokenization <https://web.archive.org/web/19970614072242/http://www.cis.upenn.edu:80/~treebank/tokenization.html>`_ Examples -------- .. sourcecode:: python >>> import turicreate # Counting word n-grams: >>> sa = turicreate.SArray(['I like big dogs. I LIKE BIG DOGS.']) >>> turicreate.text_analytics.count_ngrams(sa, 3) dtype: dict Rows: 1 [{'big dogs i': 1, 'like big dogs': 2, 'dogs i like': 1, 'i like big': 2}] # Counting character n-grams: >>> sa = turicreate.SArray(['Fun. Is. Fun']) >>> turicreate.text_analytics.count_ngrams(sa, 3, "character") dtype: dict Rows: 1 {'fun': 2, 'nis': 1, 'sfu': 1, 'isf': 1, 'uni': 1}] # Run count_ngrams with dictionary input >>> sa = turicreate.SArray([{'alice bob': 1, 'Bob alice': 0.5}, {'a dog': 0, 'a dog cat': 5}]) >>> turicreate.text_analytics.count_ngrams(sa) dtype: dict Rows: 2 [{'bob alice': 0.5, 'alice bob': 1}, {'dog cat': 5, 'a dog': 5}] # Run count_ngrams with list input >>> sa = turicreate.SArray([['one', 'bar bah'], ['a dog', 'a dog cat']]) >>> turicreate.text_analytics.count_ngrams(sa) dtype: dict Rows: 2 [{'bar bah': 1}, {'dog cat': 1, 'a dog': 2}] """ _raise_error_if_not_sarray(text, "text") # Compute ngrams counts sf = _turicreate.SFrame({'docs': text}) fe = _feature_engineering.NGramCounter(features='docs', n=n, method=method, to_lower=to_lower, delimiters=delimiters, ignore_punct=ignore_punct, ignore_space=ignore_space, output_column_prefix=None) output_sf = fe.fit_transform(sf) return output_sf['docs']
[ "def", "count_ngrams", "(", "text", ",", "n", "=", "2", ",", "method", "=", "\"word\"", ",", "to_lower", "=", "True", ",", "delimiters", "=", "DEFAULT_DELIMITERS", ",", "ignore_punct", "=", "True", ",", "ignore_space", "=", "True", ")", ":", "_raise_error_if_not_sarray", "(", "text", ",", "\"text\"", ")", "# Compute ngrams counts", "sf", "=", "_turicreate", ".", "SFrame", "(", "{", "'docs'", ":", "text", "}", ")", "fe", "=", "_feature_engineering", ".", "NGramCounter", "(", "features", "=", "'docs'", ",", "n", "=", "n", ",", "method", "=", "method", ",", "to_lower", "=", "to_lower", ",", "delimiters", "=", "delimiters", ",", "ignore_punct", "=", "ignore_punct", ",", "ignore_space", "=", "ignore_space", ",", "output_column_prefix", "=", "None", ")", "output_sf", "=", "fe", ".", "fit_transform", "(", "sf", ")", "return", "output_sf", "[", "'docs'", "]" ]
Return an SArray of ``dict`` type where each element contains the count for each of the n-grams that appear in the corresponding input element. The n-grams can be specified to be either character n-grams or word n-grams. The input SArray could contain strings, dicts with string keys and numeric values, or lists of strings. Parameters ---------- Text : SArray[str | dict | list] Input text data. n : int, optional The number of words in each n-gram. An ``n`` value of 1 returns word counts. method : {'word', 'character'}, optional If "word", the function performs a count of word n-grams. If "character", does a character n-gram count. to_lower : bool, optional If True, all words are converted to lower case before counting. delimiters : list[str], None, optional If method is "word", input strings are tokenized using `delimiters` characters in this list. Each entry in this list must contain a single character. If set to `None`, then a Penn treebank-style tokenization is used, which contains smart handling of punctuations. If method is "character," this option is ignored. ignore_punct : bool, optional If method is "character", indicates if *punctuations* between words are counted as part of the n-gram. For instance, with the input SArray element of "fun.games", if this parameter is set to False one tri-gram would be 'n.g'. If ``ignore_punct`` is set to True, there would be no such tri-gram (there would still be 'nga'). This parameter has no effect if the method is set to "word". ignore_space : bool, optional If method is "character", indicates if *spaces* between words are counted as part of the n-gram. For instance, with the input SArray element of "fun games", if this parameter is set to False one tri-gram would be 'n g'. If ``ignore_space`` is set to True, there would be no such tri-gram (there would still be 'nga'). This parameter has no effect if the method is set to "word". Returns ------- out : SArray[dict] An SArray of dictionary type, where each key is the n-gram string and each value is its count. See Also -------- count_words, tokenize, Notes ----- - Ignoring case (with ``to_lower``) involves a full string copy of the SArray data. To increase speed for large documents, set ``to_lower`` to False. - Punctuation and spaces are both delimiters by default when counting word n-grams. When counting character n-grams, one may choose to ignore punctuations, spaces, neither, or both. References ---------- - `N-gram wikipedia article <http://en.wikipedia.org/wiki/N-gram>`_ - `Penn treebank tokenization <https://web.archive.org/web/19970614072242/http://www.cis.upenn.edu:80/~treebank/tokenization.html>`_ Examples -------- .. sourcecode:: python >>> import turicreate # Counting word n-grams: >>> sa = turicreate.SArray(['I like big dogs. I LIKE BIG DOGS.']) >>> turicreate.text_analytics.count_ngrams(sa, 3) dtype: dict Rows: 1 [{'big dogs i': 1, 'like big dogs': 2, 'dogs i like': 1, 'i like big': 2}] # Counting character n-grams: >>> sa = turicreate.SArray(['Fun. Is. Fun']) >>> turicreate.text_analytics.count_ngrams(sa, 3, "character") dtype: dict Rows: 1 {'fun': 2, 'nis': 1, 'sfu': 1, 'isf': 1, 'uni': 1}] # Run count_ngrams with dictionary input >>> sa = turicreate.SArray([{'alice bob': 1, 'Bob alice': 0.5}, {'a dog': 0, 'a dog cat': 5}]) >>> turicreate.text_analytics.count_ngrams(sa) dtype: dict Rows: 2 [{'bob alice': 0.5, 'alice bob': 1}, {'dog cat': 5, 'a dog': 5}] # Run count_ngrams with list input >>> sa = turicreate.SArray([['one', 'bar bah'], ['a dog', 'a dog cat']]) >>> turicreate.text_analytics.count_ngrams(sa) dtype: dict Rows: 2 [{'bar bah': 1}, {'dog cat': 1, 'a dog': 2}]
[ "Return", "an", "SArray", "of", "dict", "type", "where", "each", "element", "contains", "the", "count", "for", "each", "of", "the", "n", "-", "grams", "that", "appear", "in", "the", "corresponding", "input", "element", ".", "The", "n", "-", "grams", "can", "be", "specified", "to", "be", "either", "character", "n", "-", "grams", "or", "word", "n", "-", "grams", ".", "The", "input", "SArray", "could", "contain", "strings", "dicts", "with", "string", "keys", "and", "numeric", "values", "or", "lists", "of", "strings", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/text_analytics/_util.py#L119-L243
train
apple/turicreate
src/unity/python/turicreate/toolkits/text_analytics/_util.py
tf_idf
def tf_idf(text): """ Compute the TF-IDF scores for each word in each document. The collection of documents must be in bag-of-words format. .. math:: \mbox{TF-IDF}(w, d) = tf(w, d) * log(N / f(w)) where :math:`tf(w, d)` is the number of times word :math:`w` appeared in document :math:`d`, :math:`f(w)` is the number of documents word :math:`w` appeared in, :math:`N` is the number of documents, and we use the natural logarithm. Parameters ---------- text : SArray[str | dict | list] Input text data. Returns ------- out : SArray[dict] The same document corpus where each score has been replaced by the TF-IDF transformation. See Also -------- count_words, count_ngrams, tokenize, References ---------- - `Wikipedia - TF-IDF <https://en.wikipedia.org/wiki/TFIDF>`_ Examples -------- .. sourcecode:: python >>> import turicreate >>> docs = turicreate.SArray('https://static.turi.com/datasets/nips-text') >>> docs_tfidf = turicreate.text_analytics.tf_idf(docs) """ _raise_error_if_not_sarray(text, "text") if len(text) == 0: return _turicreate.SArray() dataset = _turicreate.SFrame({'docs': text}) scores = _feature_engineering.TFIDF('docs').fit_transform(dataset) return scores['docs']
python
def tf_idf(text): """ Compute the TF-IDF scores for each word in each document. The collection of documents must be in bag-of-words format. .. math:: \mbox{TF-IDF}(w, d) = tf(w, d) * log(N / f(w)) where :math:`tf(w, d)` is the number of times word :math:`w` appeared in document :math:`d`, :math:`f(w)` is the number of documents word :math:`w` appeared in, :math:`N` is the number of documents, and we use the natural logarithm. Parameters ---------- text : SArray[str | dict | list] Input text data. Returns ------- out : SArray[dict] The same document corpus where each score has been replaced by the TF-IDF transformation. See Also -------- count_words, count_ngrams, tokenize, References ---------- - `Wikipedia - TF-IDF <https://en.wikipedia.org/wiki/TFIDF>`_ Examples -------- .. sourcecode:: python >>> import turicreate >>> docs = turicreate.SArray('https://static.turi.com/datasets/nips-text') >>> docs_tfidf = turicreate.text_analytics.tf_idf(docs) """ _raise_error_if_not_sarray(text, "text") if len(text) == 0: return _turicreate.SArray() dataset = _turicreate.SFrame({'docs': text}) scores = _feature_engineering.TFIDF('docs').fit_transform(dataset) return scores['docs']
[ "def", "tf_idf", "(", "text", ")", ":", "_raise_error_if_not_sarray", "(", "text", ",", "\"text\"", ")", "if", "len", "(", "text", ")", "==", "0", ":", "return", "_turicreate", ".", "SArray", "(", ")", "dataset", "=", "_turicreate", ".", "SFrame", "(", "{", "'docs'", ":", "text", "}", ")", "scores", "=", "_feature_engineering", ".", "TFIDF", "(", "'docs'", ")", ".", "fit_transform", "(", "dataset", ")", "return", "scores", "[", "'docs'", "]" ]
Compute the TF-IDF scores for each word in each document. The collection of documents must be in bag-of-words format. .. math:: \mbox{TF-IDF}(w, d) = tf(w, d) * log(N / f(w)) where :math:`tf(w, d)` is the number of times word :math:`w` appeared in document :math:`d`, :math:`f(w)` is the number of documents word :math:`w` appeared in, :math:`N` is the number of documents, and we use the natural logarithm. Parameters ---------- text : SArray[str | dict | list] Input text data. Returns ------- out : SArray[dict] The same document corpus where each score has been replaced by the TF-IDF transformation. See Also -------- count_words, count_ngrams, tokenize, References ---------- - `Wikipedia - TF-IDF <https://en.wikipedia.org/wiki/TFIDF>`_ Examples -------- .. sourcecode:: python >>> import turicreate >>> docs = turicreate.SArray('https://static.turi.com/datasets/nips-text') >>> docs_tfidf = turicreate.text_analytics.tf_idf(docs)
[ "Compute", "the", "TF", "-", "IDF", "scores", "for", "each", "word", "in", "each", "document", ".", "The", "collection", "of", "documents", "must", "be", "in", "bag", "-", "of", "-", "words", "format", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/text_analytics/_util.py#L246-L295
train
apple/turicreate
src/unity/python/turicreate/toolkits/text_analytics/_util.py
drop_words
def drop_words(text, threshold=2, to_lower=True, delimiters=DEFAULT_DELIMITERS, stop_words=None): ''' Remove words that occur below a certain number of times in an SArray. This is a common method of cleaning text before it is used, and can increase the quality and explainability of the models learned on the transformed data. RareWordTrimmer can be applied to all the string-, dictionary-, and list-typed columns in an SArray. * **string** : The string is first tokenized. By default, all letters are first converted to lower case, then tokenized by space characters. Each token is taken to be a word, and the words occurring below a threshold number of times across the entire column are removed, then the remaining tokens are concatenated back into a string. * **list** : Each element of the list must be a string, where each element is assumed to be a token. The remaining tokens are then filtered by count occurrences and a threshold value. * **dict** : The method first obtains the list of keys in the dictionary. This list is then processed as a standard list, except the value of each key must be of integer type and is considered to be the count of that key. Parameters ---------- text : SArray[str | dict | list] The input text data. threshold : int, optional The count below which words are removed from the input. stop_words: list[str], optional A manually specified list of stop words, which are removed regardless of count. to_lower : bool, optional Indicates whether to map the input strings to lower case before counting. delimiters: list[string], optional A list of delimiter characters for tokenization. By default, the list is defined to be the list of space characters. The user can define any custom list of single-character delimiters. Alternatively, setting `delimiters=None` will use a Penn treebank type tokenization, which is better at handling punctuations. (See reference below for details.) Returns ------- out : SArray. An SArray with words below a threshold removed. See Also -------- count_ngrams, tf_idf, tokenize, References ---------- - `Penn treebank tokenization <https://web.archive.org/web/19970614072242/http://www.cis.upenn.edu:80/~treebank/tokenization.html>`_ Examples -------- .. sourcecode:: python >>> import turicreate # Create input data >>> sa = turicreate.SArray(["The quick brown fox jumps in a fox like way.", "Word word WORD, word!!!word"]) # Run drop_words >>> turicreate.text_analytics.drop_words(sa) dtype: str Rows: 2 ['fox fox', 'word word'] # Run drop_words with Penn treebank style tokenization to handle # punctuations >>> turicreate.text_analytics.drop_words(sa, delimiters=None) dtype: str Rows: 2 ['fox fox', 'word word word'] # Run drop_words with dictionary input >>> sa = turicreate.SArray([{'alice bob': 1, 'Bob alice': 2}, {'a dog': 0, 'a dog cat': 5}]) >>> turicreate.text_analytics.drop_words(sa) dtype: dict Rows: 2 [{'bob alice': 2}, {'a dog cat': 5}] # Run drop_words with list input >>> sa = turicreate.SArray([['one', 'bar bah', 'One'], ['a dog', 'a dog cat', 'A DOG']]) >>> turicreate.text_analytics.drop_words(sa) dtype: list Rows: 2 [['one', 'one'], ['a dog', 'a dog']] ''' _raise_error_if_not_sarray(text, "text") ## Compute word counts sf = _turicreate.SFrame({'docs': text}) fe = _feature_engineering.RareWordTrimmer(features='docs', threshold=threshold, to_lower=to_lower, delimiters=delimiters, stopwords=stop_words, output_column_prefix=None) tokens = fe.fit_transform(sf) return tokens['docs']
python
def drop_words(text, threshold=2, to_lower=True, delimiters=DEFAULT_DELIMITERS, stop_words=None): ''' Remove words that occur below a certain number of times in an SArray. This is a common method of cleaning text before it is used, and can increase the quality and explainability of the models learned on the transformed data. RareWordTrimmer can be applied to all the string-, dictionary-, and list-typed columns in an SArray. * **string** : The string is first tokenized. By default, all letters are first converted to lower case, then tokenized by space characters. Each token is taken to be a word, and the words occurring below a threshold number of times across the entire column are removed, then the remaining tokens are concatenated back into a string. * **list** : Each element of the list must be a string, where each element is assumed to be a token. The remaining tokens are then filtered by count occurrences and a threshold value. * **dict** : The method first obtains the list of keys in the dictionary. This list is then processed as a standard list, except the value of each key must be of integer type and is considered to be the count of that key. Parameters ---------- text : SArray[str | dict | list] The input text data. threshold : int, optional The count below which words are removed from the input. stop_words: list[str], optional A manually specified list of stop words, which are removed regardless of count. to_lower : bool, optional Indicates whether to map the input strings to lower case before counting. delimiters: list[string], optional A list of delimiter characters for tokenization. By default, the list is defined to be the list of space characters. The user can define any custom list of single-character delimiters. Alternatively, setting `delimiters=None` will use a Penn treebank type tokenization, which is better at handling punctuations. (See reference below for details.) Returns ------- out : SArray. An SArray with words below a threshold removed. See Also -------- count_ngrams, tf_idf, tokenize, References ---------- - `Penn treebank tokenization <https://web.archive.org/web/19970614072242/http://www.cis.upenn.edu:80/~treebank/tokenization.html>`_ Examples -------- .. sourcecode:: python >>> import turicreate # Create input data >>> sa = turicreate.SArray(["The quick brown fox jumps in a fox like way.", "Word word WORD, word!!!word"]) # Run drop_words >>> turicreate.text_analytics.drop_words(sa) dtype: str Rows: 2 ['fox fox', 'word word'] # Run drop_words with Penn treebank style tokenization to handle # punctuations >>> turicreate.text_analytics.drop_words(sa, delimiters=None) dtype: str Rows: 2 ['fox fox', 'word word word'] # Run drop_words with dictionary input >>> sa = turicreate.SArray([{'alice bob': 1, 'Bob alice': 2}, {'a dog': 0, 'a dog cat': 5}]) >>> turicreate.text_analytics.drop_words(sa) dtype: dict Rows: 2 [{'bob alice': 2}, {'a dog cat': 5}] # Run drop_words with list input >>> sa = turicreate.SArray([['one', 'bar bah', 'One'], ['a dog', 'a dog cat', 'A DOG']]) >>> turicreate.text_analytics.drop_words(sa) dtype: list Rows: 2 [['one', 'one'], ['a dog', 'a dog']] ''' _raise_error_if_not_sarray(text, "text") ## Compute word counts sf = _turicreate.SFrame({'docs': text}) fe = _feature_engineering.RareWordTrimmer(features='docs', threshold=threshold, to_lower=to_lower, delimiters=delimiters, stopwords=stop_words, output_column_prefix=None) tokens = fe.fit_transform(sf) return tokens['docs']
[ "def", "drop_words", "(", "text", ",", "threshold", "=", "2", ",", "to_lower", "=", "True", ",", "delimiters", "=", "DEFAULT_DELIMITERS", ",", "stop_words", "=", "None", ")", ":", "_raise_error_if_not_sarray", "(", "text", ",", "\"text\"", ")", "## Compute word counts", "sf", "=", "_turicreate", ".", "SFrame", "(", "{", "'docs'", ":", "text", "}", ")", "fe", "=", "_feature_engineering", ".", "RareWordTrimmer", "(", "features", "=", "'docs'", ",", "threshold", "=", "threshold", ",", "to_lower", "=", "to_lower", ",", "delimiters", "=", "delimiters", ",", "stopwords", "=", "stop_words", ",", "output_column_prefix", "=", "None", ")", "tokens", "=", "fe", ".", "fit_transform", "(", "sf", ")", "return", "tokens", "[", "'docs'", "]" ]
Remove words that occur below a certain number of times in an SArray. This is a common method of cleaning text before it is used, and can increase the quality and explainability of the models learned on the transformed data. RareWordTrimmer can be applied to all the string-, dictionary-, and list-typed columns in an SArray. * **string** : The string is first tokenized. By default, all letters are first converted to lower case, then tokenized by space characters. Each token is taken to be a word, and the words occurring below a threshold number of times across the entire column are removed, then the remaining tokens are concatenated back into a string. * **list** : Each element of the list must be a string, where each element is assumed to be a token. The remaining tokens are then filtered by count occurrences and a threshold value. * **dict** : The method first obtains the list of keys in the dictionary. This list is then processed as a standard list, except the value of each key must be of integer type and is considered to be the count of that key. Parameters ---------- text : SArray[str | dict | list] The input text data. threshold : int, optional The count below which words are removed from the input. stop_words: list[str], optional A manually specified list of stop words, which are removed regardless of count. to_lower : bool, optional Indicates whether to map the input strings to lower case before counting. delimiters: list[string], optional A list of delimiter characters for tokenization. By default, the list is defined to be the list of space characters. The user can define any custom list of single-character delimiters. Alternatively, setting `delimiters=None` will use a Penn treebank type tokenization, which is better at handling punctuations. (See reference below for details.) Returns ------- out : SArray. An SArray with words below a threshold removed. See Also -------- count_ngrams, tf_idf, tokenize, References ---------- - `Penn treebank tokenization <https://web.archive.org/web/19970614072242/http://www.cis.upenn.edu:80/~treebank/tokenization.html>`_ Examples -------- .. sourcecode:: python >>> import turicreate # Create input data >>> sa = turicreate.SArray(["The quick brown fox jumps in a fox like way.", "Word word WORD, word!!!word"]) # Run drop_words >>> turicreate.text_analytics.drop_words(sa) dtype: str Rows: 2 ['fox fox', 'word word'] # Run drop_words with Penn treebank style tokenization to handle # punctuations >>> turicreate.text_analytics.drop_words(sa, delimiters=None) dtype: str Rows: 2 ['fox fox', 'word word word'] # Run drop_words with dictionary input >>> sa = turicreate.SArray([{'alice bob': 1, 'Bob alice': 2}, {'a dog': 0, 'a dog cat': 5}]) >>> turicreate.text_analytics.drop_words(sa) dtype: dict Rows: 2 [{'bob alice': 2}, {'a dog cat': 5}] # Run drop_words with list input >>> sa = turicreate.SArray([['one', 'bar bah', 'One'], ['a dog', 'a dog cat', 'A DOG']]) >>> turicreate.text_analytics.drop_words(sa) dtype: list Rows: 2 [['one', 'one'], ['a dog', 'a dog']]
[ "Remove", "words", "that", "occur", "below", "a", "certain", "number", "of", "times", "in", "an", "SArray", ".", "This", "is", "a", "common", "method", "of", "cleaning", "text", "before", "it", "is", "used", "and", "can", "increase", "the", "quality", "and", "explainability", "of", "the", "models", "learned", "on", "the", "transformed", "data", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/text_analytics/_util.py#L298-L410
train
apple/turicreate
src/unity/python/turicreate/toolkits/text_analytics/_util.py
tokenize
def tokenize(text, to_lower=False, delimiters=DEFAULT_DELIMITERS): """ Tokenize the input SArray of text strings and return the list of tokens. Parameters ---------- text : SArray[str] Input data of strings representing English text. This tokenizer is not intended to process XML, HTML, or other structured text formats. to_lower : bool, optional If True, all strings are converted to lower case before tokenization. delimiters : list[str], None, optional Input strings are tokenized using delimiter characters in this list. Each entry in this list must contain a single character. If set to `None`, then a Penn treebank-style tokenization is used, which contains smart handling of punctuations. Returns ------- out : SArray[list] Each text string in the input is mapped to a list of tokens. See Also -------- count_words, count_ngrams, tf_idf References ---------- - `Penn treebank tokenization <https://web.archive.org/web/19970614072242/http://www.cis.upenn.edu:80/~treebank/tokenization.html>`_ Examples -------- .. sourcecode:: python >>> import turicreate >>> docs = turicreate.SArray(['This is the first sentence.', "This one, it's the second sentence."]) # Default tokenization by space characters >>> turicreate.text_analytics.tokenize(docs) dtype: list Rows: 2 [['This', 'is', 'the', 'first', 'sentence.'], ['This', 'one,', "it's", 'the', 'second', 'sentence.']] # Penn treebank-style tokenization >>> turicreate.text_analytics.tokenize(docs, delimiters=None) dtype: list Rows: 2 [['This', 'is', 'the', 'first', 'sentence', '.'], ['This', 'one', ',', 'it', "'s", 'the', 'second', 'sentence', '.']] """ _raise_error_if_not_sarray(text, "text") ## Compute word counts sf = _turicreate.SFrame({'docs': text}) fe = _feature_engineering.Tokenizer(features='docs', to_lower=to_lower, delimiters=delimiters, output_column_prefix=None) tokens = fe.fit_transform(sf) return tokens['docs']
python
def tokenize(text, to_lower=False, delimiters=DEFAULT_DELIMITERS): """ Tokenize the input SArray of text strings and return the list of tokens. Parameters ---------- text : SArray[str] Input data of strings representing English text. This tokenizer is not intended to process XML, HTML, or other structured text formats. to_lower : bool, optional If True, all strings are converted to lower case before tokenization. delimiters : list[str], None, optional Input strings are tokenized using delimiter characters in this list. Each entry in this list must contain a single character. If set to `None`, then a Penn treebank-style tokenization is used, which contains smart handling of punctuations. Returns ------- out : SArray[list] Each text string in the input is mapped to a list of tokens. See Also -------- count_words, count_ngrams, tf_idf References ---------- - `Penn treebank tokenization <https://web.archive.org/web/19970614072242/http://www.cis.upenn.edu:80/~treebank/tokenization.html>`_ Examples -------- .. sourcecode:: python >>> import turicreate >>> docs = turicreate.SArray(['This is the first sentence.', "This one, it's the second sentence."]) # Default tokenization by space characters >>> turicreate.text_analytics.tokenize(docs) dtype: list Rows: 2 [['This', 'is', 'the', 'first', 'sentence.'], ['This', 'one,', "it's", 'the', 'second', 'sentence.']] # Penn treebank-style tokenization >>> turicreate.text_analytics.tokenize(docs, delimiters=None) dtype: list Rows: 2 [['This', 'is', 'the', 'first', 'sentence', '.'], ['This', 'one', ',', 'it', "'s", 'the', 'second', 'sentence', '.']] """ _raise_error_if_not_sarray(text, "text") ## Compute word counts sf = _turicreate.SFrame({'docs': text}) fe = _feature_engineering.Tokenizer(features='docs', to_lower=to_lower, delimiters=delimiters, output_column_prefix=None) tokens = fe.fit_transform(sf) return tokens['docs']
[ "def", "tokenize", "(", "text", ",", "to_lower", "=", "False", ",", "delimiters", "=", "DEFAULT_DELIMITERS", ")", ":", "_raise_error_if_not_sarray", "(", "text", ",", "\"text\"", ")", "## Compute word counts", "sf", "=", "_turicreate", ".", "SFrame", "(", "{", "'docs'", ":", "text", "}", ")", "fe", "=", "_feature_engineering", ".", "Tokenizer", "(", "features", "=", "'docs'", ",", "to_lower", "=", "to_lower", ",", "delimiters", "=", "delimiters", ",", "output_column_prefix", "=", "None", ")", "tokens", "=", "fe", ".", "fit_transform", "(", "sf", ")", "return", "tokens", "[", "'docs'", "]" ]
Tokenize the input SArray of text strings and return the list of tokens. Parameters ---------- text : SArray[str] Input data of strings representing English text. This tokenizer is not intended to process XML, HTML, or other structured text formats. to_lower : bool, optional If True, all strings are converted to lower case before tokenization. delimiters : list[str], None, optional Input strings are tokenized using delimiter characters in this list. Each entry in this list must contain a single character. If set to `None`, then a Penn treebank-style tokenization is used, which contains smart handling of punctuations. Returns ------- out : SArray[list] Each text string in the input is mapped to a list of tokens. See Also -------- count_words, count_ngrams, tf_idf References ---------- - `Penn treebank tokenization <https://web.archive.org/web/19970614072242/http://www.cis.upenn.edu:80/~treebank/tokenization.html>`_ Examples -------- .. sourcecode:: python >>> import turicreate >>> docs = turicreate.SArray(['This is the first sentence.', "This one, it's the second sentence."]) # Default tokenization by space characters >>> turicreate.text_analytics.tokenize(docs) dtype: list Rows: 2 [['This', 'is', 'the', 'first', 'sentence.'], ['This', 'one,', "it's", 'the', 'second', 'sentence.']] # Penn treebank-style tokenization >>> turicreate.text_analytics.tokenize(docs, delimiters=None) dtype: list Rows: 2 [['This', 'is', 'the', 'first', 'sentence', '.'], ['This', 'one', ',', 'it', "'s", 'the', 'second', 'sentence', '.']]
[ "Tokenize", "the", "input", "SArray", "of", "text", "strings", "and", "return", "the", "list", "of", "tokens", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/text_analytics/_util.py#L412-L478
train
apple/turicreate
src/unity/python/turicreate/toolkits/text_analytics/_util.py
bm25
def bm25(dataset, query, k1=1.5, b=.75): """ For a given query and set of documents, compute the BM25 score for each document. If we have a query with words q_1, ..., q_n the BM25 score for a document is: .. math:: \sum_{i=1}^N IDF(q_i)\\frac{f(q_i) * (k_1+1)}{f(q_i) + k_1 * (1-b+b*|D|/d_avg))} where * :math:`\mbox{IDF}(q_i) = log((N - n(q_i) + .5)/(n(q_i) + .5)` * :math:`f(q_i)` is the number of times q_i occurs in the document * :math:`n(q_i)` is the number of documents containing q_i * :math:`|D|` is the number of words in the document * :math:`d_avg` is the average number of words per document in the corpus * :math:`k_1` and :math:`b` are free parameters. Parameters ---------- dataset : SArray of type dict, list, or str An SArray where each element either represents a document in: * **dict** : a bag-of-words format, where each key is a word and each value is the number of times that word occurs in the document. * **list** : The list is converted to bag of words of format, where the keys are the unique elements in the list and the values are the counts of those unique elements. After this step, the behaviour is identical to dict. * **string** : Behaves identically to a **dict**, where the dictionary is generated by converting the string into a bag-of-words format. For example, 'I really like really fluffy dogs" would get converted to {'I' : 1, 'really': 2, 'like': 1, 'fluffy': 1, 'dogs':1}. query : A list, set, or SArray of type str A list, set or SArray where each element is a word. k1 : float, optional Free parameter which controls the relative importance of term frequencies. Recommended values are [1.2, 2.0]. b : float, optional Free parameter which controls how much to downweight scores for long documents. Recommended value is 0.75. Returns ------- out : SFrame An SFrame containing the BM25 score for each document containing one of the query words. The doc_id column is the row number of the document. Examples -------- .. sourcecode:: python >>> import turicreate >>> dataset = turicreate.SArray([ {'a':5, 'b':7, 'c':10}, {'a':3, 'c':1, 'd':2}, {'a':10, 'b':3, 'e':5}, {'a':1}, {'f':5}]) >>> query = ['a', 'b', 'c'] >>> turicreate.text_analytics.bm25(dataset, query) References ---------- .. [BM25] `"Okapi BM-25" <http://en.wikipedia.org/wiki/Okapi_BM25>`_ """ if type(dataset) != _turicreate.SArray: raise TypeError('bm25 requires an SArray of dict, list, or str type'+\ ', where each dictionary whose keys are words and whose values' + \ ' are word frequency.') sf = _SFrame({'docs' : dataset}) if type(query) is dict: # For backwards compatibility query = list(query.keys()) if type(query) is _turicreate.SArray: query = list(query) if type(query) is set: query = list(query) if type(query) is not list: raise TypeError('The query must either be an SArray of str type, '+\ ' a list of strings, or a set of strings.') # Calculate BM25 sf = sf.add_row_number('doc_id') sf = sf.dropna('docs') # Drop missing documents scores = _feature_engineering.BM25('docs',query, k1, b, output_column_name = 'bm25').fit_transform(sf) # Find documents with query words if scores['docs'].dtype is dict: scores['doc_terms'] = scores['docs'].dict_keys() elif scores['docs'].dtype is list: scores['doc_terms'] = scores['docs'].apply(lambda x: list(set(x))) elif scores['docs'].dtype is str: scores['doc_terms'] = count_words(scores['docs']).dict_keys() else: # This should never occur (handled by BM25) raise TypeError('bm25 requires an SArray of dict, list, or str type') scores['doc_counts'] = scores['doc_terms'].apply(lambda x: len([word for word in query if word in x])) scores = scores[scores['doc_counts'] > 0] # Drop documents without query word scores = scores.select_columns(['doc_id','bm25']) return scores
python
def bm25(dataset, query, k1=1.5, b=.75): """ For a given query and set of documents, compute the BM25 score for each document. If we have a query with words q_1, ..., q_n the BM25 score for a document is: .. math:: \sum_{i=1}^N IDF(q_i)\\frac{f(q_i) * (k_1+1)}{f(q_i) + k_1 * (1-b+b*|D|/d_avg))} where * :math:`\mbox{IDF}(q_i) = log((N - n(q_i) + .5)/(n(q_i) + .5)` * :math:`f(q_i)` is the number of times q_i occurs in the document * :math:`n(q_i)` is the number of documents containing q_i * :math:`|D|` is the number of words in the document * :math:`d_avg` is the average number of words per document in the corpus * :math:`k_1` and :math:`b` are free parameters. Parameters ---------- dataset : SArray of type dict, list, or str An SArray where each element either represents a document in: * **dict** : a bag-of-words format, where each key is a word and each value is the number of times that word occurs in the document. * **list** : The list is converted to bag of words of format, where the keys are the unique elements in the list and the values are the counts of those unique elements. After this step, the behaviour is identical to dict. * **string** : Behaves identically to a **dict**, where the dictionary is generated by converting the string into a bag-of-words format. For example, 'I really like really fluffy dogs" would get converted to {'I' : 1, 'really': 2, 'like': 1, 'fluffy': 1, 'dogs':1}. query : A list, set, or SArray of type str A list, set or SArray where each element is a word. k1 : float, optional Free parameter which controls the relative importance of term frequencies. Recommended values are [1.2, 2.0]. b : float, optional Free parameter which controls how much to downweight scores for long documents. Recommended value is 0.75. Returns ------- out : SFrame An SFrame containing the BM25 score for each document containing one of the query words. The doc_id column is the row number of the document. Examples -------- .. sourcecode:: python >>> import turicreate >>> dataset = turicreate.SArray([ {'a':5, 'b':7, 'c':10}, {'a':3, 'c':1, 'd':2}, {'a':10, 'b':3, 'e':5}, {'a':1}, {'f':5}]) >>> query = ['a', 'b', 'c'] >>> turicreate.text_analytics.bm25(dataset, query) References ---------- .. [BM25] `"Okapi BM-25" <http://en.wikipedia.org/wiki/Okapi_BM25>`_ """ if type(dataset) != _turicreate.SArray: raise TypeError('bm25 requires an SArray of dict, list, or str type'+\ ', where each dictionary whose keys are words and whose values' + \ ' are word frequency.') sf = _SFrame({'docs' : dataset}) if type(query) is dict: # For backwards compatibility query = list(query.keys()) if type(query) is _turicreate.SArray: query = list(query) if type(query) is set: query = list(query) if type(query) is not list: raise TypeError('The query must either be an SArray of str type, '+\ ' a list of strings, or a set of strings.') # Calculate BM25 sf = sf.add_row_number('doc_id') sf = sf.dropna('docs') # Drop missing documents scores = _feature_engineering.BM25('docs',query, k1, b, output_column_name = 'bm25').fit_transform(sf) # Find documents with query words if scores['docs'].dtype is dict: scores['doc_terms'] = scores['docs'].dict_keys() elif scores['docs'].dtype is list: scores['doc_terms'] = scores['docs'].apply(lambda x: list(set(x))) elif scores['docs'].dtype is str: scores['doc_terms'] = count_words(scores['docs']).dict_keys() else: # This should never occur (handled by BM25) raise TypeError('bm25 requires an SArray of dict, list, or str type') scores['doc_counts'] = scores['doc_terms'].apply(lambda x: len([word for word in query if word in x])) scores = scores[scores['doc_counts'] > 0] # Drop documents without query word scores = scores.select_columns(['doc_id','bm25']) return scores
[ "def", "bm25", "(", "dataset", ",", "query", ",", "k1", "=", "1.5", ",", "b", "=", ".75", ")", ":", "if", "type", "(", "dataset", ")", "!=", "_turicreate", ".", "SArray", ":", "raise", "TypeError", "(", "'bm25 requires an SArray of dict, list, or str type'", "+", "', where each dictionary whose keys are words and whose values'", "+", "' are word frequency.'", ")", "sf", "=", "_SFrame", "(", "{", "'docs'", ":", "dataset", "}", ")", "if", "type", "(", "query", ")", "is", "dict", ":", "# For backwards compatibility", "query", "=", "list", "(", "query", ".", "keys", "(", ")", ")", "if", "type", "(", "query", ")", "is", "_turicreate", ".", "SArray", ":", "query", "=", "list", "(", "query", ")", "if", "type", "(", "query", ")", "is", "set", ":", "query", "=", "list", "(", "query", ")", "if", "type", "(", "query", ")", "is", "not", "list", ":", "raise", "TypeError", "(", "'The query must either be an SArray of str type, '", "+", "' a list of strings, or a set of strings.'", ")", "# Calculate BM25", "sf", "=", "sf", ".", "add_row_number", "(", "'doc_id'", ")", "sf", "=", "sf", ".", "dropna", "(", "'docs'", ")", "# Drop missing documents", "scores", "=", "_feature_engineering", ".", "BM25", "(", "'docs'", ",", "query", ",", "k1", ",", "b", ",", "output_column_name", "=", "'bm25'", ")", ".", "fit_transform", "(", "sf", ")", "# Find documents with query words", "if", "scores", "[", "'docs'", "]", ".", "dtype", "is", "dict", ":", "scores", "[", "'doc_terms'", "]", "=", "scores", "[", "'docs'", "]", ".", "dict_keys", "(", ")", "elif", "scores", "[", "'docs'", "]", ".", "dtype", "is", "list", ":", "scores", "[", "'doc_terms'", "]", "=", "scores", "[", "'docs'", "]", ".", "apply", "(", "lambda", "x", ":", "list", "(", "set", "(", "x", ")", ")", ")", "elif", "scores", "[", "'docs'", "]", ".", "dtype", "is", "str", ":", "scores", "[", "'doc_terms'", "]", "=", "count_words", "(", "scores", "[", "'docs'", "]", ")", ".", "dict_keys", "(", ")", "else", ":", "# This should never occur (handled by BM25)", "raise", "TypeError", "(", "'bm25 requires an SArray of dict, list, or str type'", ")", "scores", "[", "'doc_counts'", "]", "=", "scores", "[", "'doc_terms'", "]", ".", "apply", "(", "lambda", "x", ":", "len", "(", "[", "word", "for", "word", "in", "query", "if", "word", "in", "x", "]", ")", ")", "scores", "=", "scores", "[", "scores", "[", "'doc_counts'", "]", ">", "0", "]", "# Drop documents without query word", "scores", "=", "scores", ".", "select_columns", "(", "[", "'doc_id'", ",", "'bm25'", "]", ")", "return", "scores" ]
For a given query and set of documents, compute the BM25 score for each document. If we have a query with words q_1, ..., q_n the BM25 score for a document is: .. math:: \sum_{i=1}^N IDF(q_i)\\frac{f(q_i) * (k_1+1)}{f(q_i) + k_1 * (1-b+b*|D|/d_avg))} where * :math:`\mbox{IDF}(q_i) = log((N - n(q_i) + .5)/(n(q_i) + .5)` * :math:`f(q_i)` is the number of times q_i occurs in the document * :math:`n(q_i)` is the number of documents containing q_i * :math:`|D|` is the number of words in the document * :math:`d_avg` is the average number of words per document in the corpus * :math:`k_1` and :math:`b` are free parameters. Parameters ---------- dataset : SArray of type dict, list, or str An SArray where each element either represents a document in: * **dict** : a bag-of-words format, where each key is a word and each value is the number of times that word occurs in the document. * **list** : The list is converted to bag of words of format, where the keys are the unique elements in the list and the values are the counts of those unique elements. After this step, the behaviour is identical to dict. * **string** : Behaves identically to a **dict**, where the dictionary is generated by converting the string into a bag-of-words format. For example, 'I really like really fluffy dogs" would get converted to {'I' : 1, 'really': 2, 'like': 1, 'fluffy': 1, 'dogs':1}. query : A list, set, or SArray of type str A list, set or SArray where each element is a word. k1 : float, optional Free parameter which controls the relative importance of term frequencies. Recommended values are [1.2, 2.0]. b : float, optional Free parameter which controls how much to downweight scores for long documents. Recommended value is 0.75. Returns ------- out : SFrame An SFrame containing the BM25 score for each document containing one of the query words. The doc_id column is the row number of the document. Examples -------- .. sourcecode:: python >>> import turicreate >>> dataset = turicreate.SArray([ {'a':5, 'b':7, 'c':10}, {'a':3, 'c':1, 'd':2}, {'a':10, 'b':3, 'e':5}, {'a':1}, {'f':5}]) >>> query = ['a', 'b', 'c'] >>> turicreate.text_analytics.bm25(dataset, query) References ---------- .. [BM25] `"Okapi BM-25" <http://en.wikipedia.org/wiki/Okapi_BM25>`_
[ "For", "a", "given", "query", "and", "set", "of", "documents", "compute", "the", "BM25", "score", "for", "each", "document", ".", "If", "we", "have", "a", "query", "with", "words", "q_1", "...", "q_n", "the", "BM25", "score", "for", "a", "document", "is", ":" ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/text_analytics/_util.py#L480-L590
train
apple/turicreate
src/unity/python/turicreate/toolkits/text_analytics/_util.py
parse_sparse
def parse_sparse(filename, vocab_filename): """ Parse a file that's in libSVM format. In libSVM format each line of the text file represents a document in bag of words format: num_unique_words_in_doc word_id:count another_id:count The word_ids have 0-based indexing, i.e. 0 corresponds to the first word in the vocab filename. Parameters ---------- filename : str The name of the file to parse. vocab_filename : str A list of words that are used for this data set. Returns ------- out : SArray Each element represents a document in bag-of-words format. Examples -------- If we have two documents: 1. "It was the best of times, it was the worst of times" 2. "It was the age of wisdom, it was the age of foolishness" Then the vocabulary file might contain the unique words, with a word on each line, in the following order: it, was, the, best, of, times, worst, age, wisdom, foolishness In this case, the file in libSVM format would have two lines: 7 0:2 1:2 2:2 3:1 4:2 5:1 6:1 7 0:2 1:2 2:2 7:2 8:1 9:1 10:1 The following command will parse the above two files into an SArray of type dict. >>> file = 'https://static.turi.com/datasets/text/ap.dat' >>> vocab = 'https://static.turi.com/datasets/text/ap.vocab.txt' >>> docs = turicreate.text_analytics.parse_sparse(file, vocab) """ vocab = _turicreate.SFrame.read_csv(vocab_filename, header=None)['X1'] vocab = list(vocab) docs = _turicreate.SFrame.read_csv(filename, header=None) # Remove first word docs = docs['X1'].apply(lambda x: x.split(' ')[1:]) # Helper function that checks whether we get too large a word id def get_word(word_id): assert int(word_id) < len(vocab), \ "Text data contains integers that are larger than the \ size of the provided vocabulary." return vocab[word_id] def make_dict(pairs): pairs = [z.split(':') for z in pairs] ret = {} for k, v in pairs: ret[get_word(int(k))] = int(v) return ret # Split word_id and count and make into a dictionary docs = docs.apply(lambda x: make_dict(x)) return docs
python
def parse_sparse(filename, vocab_filename): """ Parse a file that's in libSVM format. In libSVM format each line of the text file represents a document in bag of words format: num_unique_words_in_doc word_id:count another_id:count The word_ids have 0-based indexing, i.e. 0 corresponds to the first word in the vocab filename. Parameters ---------- filename : str The name of the file to parse. vocab_filename : str A list of words that are used for this data set. Returns ------- out : SArray Each element represents a document in bag-of-words format. Examples -------- If we have two documents: 1. "It was the best of times, it was the worst of times" 2. "It was the age of wisdom, it was the age of foolishness" Then the vocabulary file might contain the unique words, with a word on each line, in the following order: it, was, the, best, of, times, worst, age, wisdom, foolishness In this case, the file in libSVM format would have two lines: 7 0:2 1:2 2:2 3:1 4:2 5:1 6:1 7 0:2 1:2 2:2 7:2 8:1 9:1 10:1 The following command will parse the above two files into an SArray of type dict. >>> file = 'https://static.turi.com/datasets/text/ap.dat' >>> vocab = 'https://static.turi.com/datasets/text/ap.vocab.txt' >>> docs = turicreate.text_analytics.parse_sparse(file, vocab) """ vocab = _turicreate.SFrame.read_csv(vocab_filename, header=None)['X1'] vocab = list(vocab) docs = _turicreate.SFrame.read_csv(filename, header=None) # Remove first word docs = docs['X1'].apply(lambda x: x.split(' ')[1:]) # Helper function that checks whether we get too large a word id def get_word(word_id): assert int(word_id) < len(vocab), \ "Text data contains integers that are larger than the \ size of the provided vocabulary." return vocab[word_id] def make_dict(pairs): pairs = [z.split(':') for z in pairs] ret = {} for k, v in pairs: ret[get_word(int(k))] = int(v) return ret # Split word_id and count and make into a dictionary docs = docs.apply(lambda x: make_dict(x)) return docs
[ "def", "parse_sparse", "(", "filename", ",", "vocab_filename", ")", ":", "vocab", "=", "_turicreate", ".", "SFrame", ".", "read_csv", "(", "vocab_filename", ",", "header", "=", "None", ")", "[", "'X1'", "]", "vocab", "=", "list", "(", "vocab", ")", "docs", "=", "_turicreate", ".", "SFrame", ".", "read_csv", "(", "filename", ",", "header", "=", "None", ")", "# Remove first word", "docs", "=", "docs", "[", "'X1'", "]", ".", "apply", "(", "lambda", "x", ":", "x", ".", "split", "(", "' '", ")", "[", "1", ":", "]", ")", "# Helper function that checks whether we get too large a word id", "def", "get_word", "(", "word_id", ")", ":", "assert", "int", "(", "word_id", ")", "<", "len", "(", "vocab", ")", ",", "\"Text data contains integers that are larger than the \\\n size of the provided vocabulary.\"", "return", "vocab", "[", "word_id", "]", "def", "make_dict", "(", "pairs", ")", ":", "pairs", "=", "[", "z", ".", "split", "(", "':'", ")", "for", "z", "in", "pairs", "]", "ret", "=", "{", "}", "for", "k", ",", "v", "in", "pairs", ":", "ret", "[", "get_word", "(", "int", "(", "k", ")", ")", "]", "=", "int", "(", "v", ")", "return", "ret", "# Split word_id and count and make into a dictionary", "docs", "=", "docs", ".", "apply", "(", "lambda", "x", ":", "make_dict", "(", "x", ")", ")", "return", "docs" ]
Parse a file that's in libSVM format. In libSVM format each line of the text file represents a document in bag of words format: num_unique_words_in_doc word_id:count another_id:count The word_ids have 0-based indexing, i.e. 0 corresponds to the first word in the vocab filename. Parameters ---------- filename : str The name of the file to parse. vocab_filename : str A list of words that are used for this data set. Returns ------- out : SArray Each element represents a document in bag-of-words format. Examples -------- If we have two documents: 1. "It was the best of times, it was the worst of times" 2. "It was the age of wisdom, it was the age of foolishness" Then the vocabulary file might contain the unique words, with a word on each line, in the following order: it, was, the, best, of, times, worst, age, wisdom, foolishness In this case, the file in libSVM format would have two lines: 7 0:2 1:2 2:2 3:1 4:2 5:1 6:1 7 0:2 1:2 2:2 7:2 8:1 9:1 10:1 The following command will parse the above two files into an SArray of type dict. >>> file = 'https://static.turi.com/datasets/text/ap.dat' >>> vocab = 'https://static.turi.com/datasets/text/ap.vocab.txt' >>> docs = turicreate.text_analytics.parse_sparse(file, vocab)
[ "Parse", "a", "file", "that", "s", "in", "libSVM", "format", ".", "In", "libSVM", "format", "each", "line", "of", "the", "text", "file", "represents", "a", "document", "in", "bag", "of", "words", "format", ":" ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/text_analytics/_util.py#L593-L662
train
apple/turicreate
src/unity/python/turicreate/toolkits/text_analytics/_util.py
parse_docword
def parse_docword(filename, vocab_filename): """ Parse a file that's in "docword" format. This consists of a 3-line header comprised of the document count, the vocabulary count, and the number of tokens, i.e. unique (doc_id, word_id) pairs. After the header, each line contains a space-separated triple of (doc_id, word_id, frequency), where frequency is the number of times word_id occurred in document doc_id. This format assumes that documents and words are identified by a positive integer (whose lowest value is 1). Thus, the first word in the vocabulary file has word_id=1. 2 272 5 1 5 1 1 105 3 1 272 5 2 1 3 ... Parameters ---------- filename : str The name of the file to parse. vocab_filename : str A list of words that are used for this data set. Returns ------- out : SArray Each element represents a document in bag-of-words format. Examples -------- >>> textfile = 'https://static.turi.com/datasets/text/docword.nips.txt') >>> vocab = 'https://static.turi.com/datasets/text/vocab.nips.txt') >>> docs = turicreate.text_analytics.parse_docword(textfile, vocab) """ vocab = _turicreate.SFrame.read_csv(vocab_filename, header=None)['X1'] vocab = list(vocab) sf = _turicreate.SFrame.read_csv(filename, header=False) sf = sf[3:] sf['X2'] = sf['X1'].apply(lambda x: [int(z) for z in x.split(' ')]) del sf['X1'] sf = sf.unpack('X2', column_name_prefix='', column_types=[int,int,int]) docs = sf.unstack(['1', '2'], 'bow').sort('0')['bow'] docs = docs.apply(lambda x: {vocab[k-1]:v for (k, v) in six.iteritems(x)}) return docs
python
def parse_docword(filename, vocab_filename): """ Parse a file that's in "docword" format. This consists of a 3-line header comprised of the document count, the vocabulary count, and the number of tokens, i.e. unique (doc_id, word_id) pairs. After the header, each line contains a space-separated triple of (doc_id, word_id, frequency), where frequency is the number of times word_id occurred in document doc_id. This format assumes that documents and words are identified by a positive integer (whose lowest value is 1). Thus, the first word in the vocabulary file has word_id=1. 2 272 5 1 5 1 1 105 3 1 272 5 2 1 3 ... Parameters ---------- filename : str The name of the file to parse. vocab_filename : str A list of words that are used for this data set. Returns ------- out : SArray Each element represents a document in bag-of-words format. Examples -------- >>> textfile = 'https://static.turi.com/datasets/text/docword.nips.txt') >>> vocab = 'https://static.turi.com/datasets/text/vocab.nips.txt') >>> docs = turicreate.text_analytics.parse_docword(textfile, vocab) """ vocab = _turicreate.SFrame.read_csv(vocab_filename, header=None)['X1'] vocab = list(vocab) sf = _turicreate.SFrame.read_csv(filename, header=False) sf = sf[3:] sf['X2'] = sf['X1'].apply(lambda x: [int(z) for z in x.split(' ')]) del sf['X1'] sf = sf.unpack('X2', column_name_prefix='', column_types=[int,int,int]) docs = sf.unstack(['1', '2'], 'bow').sort('0')['bow'] docs = docs.apply(lambda x: {vocab[k-1]:v for (k, v) in six.iteritems(x)}) return docs
[ "def", "parse_docword", "(", "filename", ",", "vocab_filename", ")", ":", "vocab", "=", "_turicreate", ".", "SFrame", ".", "read_csv", "(", "vocab_filename", ",", "header", "=", "None", ")", "[", "'X1'", "]", "vocab", "=", "list", "(", "vocab", ")", "sf", "=", "_turicreate", ".", "SFrame", ".", "read_csv", "(", "filename", ",", "header", "=", "False", ")", "sf", "=", "sf", "[", "3", ":", "]", "sf", "[", "'X2'", "]", "=", "sf", "[", "'X1'", "]", ".", "apply", "(", "lambda", "x", ":", "[", "int", "(", "z", ")", "for", "z", "in", "x", ".", "split", "(", "' '", ")", "]", ")", "del", "sf", "[", "'X1'", "]", "sf", "=", "sf", ".", "unpack", "(", "'X2'", ",", "column_name_prefix", "=", "''", ",", "column_types", "=", "[", "int", ",", "int", ",", "int", "]", ")", "docs", "=", "sf", ".", "unstack", "(", "[", "'1'", ",", "'2'", "]", ",", "'bow'", ")", ".", "sort", "(", "'0'", ")", "[", "'bow'", "]", "docs", "=", "docs", ".", "apply", "(", "lambda", "x", ":", "{", "vocab", "[", "k", "-", "1", "]", ":", "v", "for", "(", "k", ",", "v", ")", "in", "six", ".", "iteritems", "(", "x", ")", "}", ")", "return", "docs" ]
Parse a file that's in "docword" format. This consists of a 3-line header comprised of the document count, the vocabulary count, and the number of tokens, i.e. unique (doc_id, word_id) pairs. After the header, each line contains a space-separated triple of (doc_id, word_id, frequency), where frequency is the number of times word_id occurred in document doc_id. This format assumes that documents and words are identified by a positive integer (whose lowest value is 1). Thus, the first word in the vocabulary file has word_id=1. 2 272 5 1 5 1 1 105 3 1 272 5 2 1 3 ... Parameters ---------- filename : str The name of the file to parse. vocab_filename : str A list of words that are used for this data set. Returns ------- out : SArray Each element represents a document in bag-of-words format. Examples -------- >>> textfile = 'https://static.turi.com/datasets/text/docword.nips.txt') >>> vocab = 'https://static.turi.com/datasets/text/vocab.nips.txt') >>> docs = turicreate.text_analytics.parse_docword(textfile, vocab)
[ "Parse", "a", "file", "that", "s", "in", "docword", "format", ".", "This", "consists", "of", "a", "3", "-", "line", "header", "comprised", "of", "the", "document", "count", "the", "vocabulary", "count", "and", "the", "number", "of", "tokens", "i", ".", "e", ".", "unique", "(", "doc_id", "word_id", ")", "pairs", ".", "After", "the", "header", "each", "line", "contains", "a", "space", "-", "separated", "triple", "of", "(", "doc_id", "word_id", "frequency", ")", "where", "frequency", "is", "the", "number", "of", "times", "word_id", "occurred", "in", "document", "doc_id", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/text_analytics/_util.py#L665-L716
train
apple/turicreate
src/unity/python/turicreate/toolkits/text_analytics/_util.py
random_split
def random_split(dataset, prob=.5): """ Utility for performing a random split for text data that is already in bag-of-words format. For each (word, count) pair in a particular element, the counts are uniformly partitioned in either a training set or a test set. Parameters ---------- dataset : SArray of type dict, SFrame with columns of type dict A data set in bag-of-words format. prob : float, optional Probability for sampling a word to be placed in the test set. Returns ------- train, test : SArray Two data sets in bag-of-words format, where the combined counts are equal to the counts in the original data set. Examples -------- >>> docs = turicreate.SArray([{'are':5, 'you':3, 'not': 1, 'entertained':10}]) >>> train, test = turicreate.text_analytics.random_split(docs) >>> print(train) [{'not': 1.0, 'you': 3.0, 'are': 3.0, 'entertained': 7.0}] >>> print(test) [{'are': 2.0, 'entertained': 3.0}] """ def grab_values(x, train=True): if train: ix = 0 else: ix = 1 return dict([(key, value[ix]) for key, value in six.iteritems(x) \ if value[ix] != 0]) def word_count_split(n, p): num_in_test = 0 for i in range(n): if random.random() < p: num_in_test += 1 return [n - num_in_test, num_in_test] # Get an SArray where each word has a 2 element list containing # the count that will be for the training set and the count that will # be assigned to the test set. data = dataset.apply(lambda x: dict([(key, word_count_split(int(value), prob)) \ for key, value in six.iteritems(x)])) # Materialize the data set data.__materialize__() # Grab respective counts for each data set train = data.apply(lambda x: grab_values(x, train=True)) test = data.apply(lambda x: grab_values(x, train=False)) return train, test
python
def random_split(dataset, prob=.5): """ Utility for performing a random split for text data that is already in bag-of-words format. For each (word, count) pair in a particular element, the counts are uniformly partitioned in either a training set or a test set. Parameters ---------- dataset : SArray of type dict, SFrame with columns of type dict A data set in bag-of-words format. prob : float, optional Probability for sampling a word to be placed in the test set. Returns ------- train, test : SArray Two data sets in bag-of-words format, where the combined counts are equal to the counts in the original data set. Examples -------- >>> docs = turicreate.SArray([{'are':5, 'you':3, 'not': 1, 'entertained':10}]) >>> train, test = turicreate.text_analytics.random_split(docs) >>> print(train) [{'not': 1.0, 'you': 3.0, 'are': 3.0, 'entertained': 7.0}] >>> print(test) [{'are': 2.0, 'entertained': 3.0}] """ def grab_values(x, train=True): if train: ix = 0 else: ix = 1 return dict([(key, value[ix]) for key, value in six.iteritems(x) \ if value[ix] != 0]) def word_count_split(n, p): num_in_test = 0 for i in range(n): if random.random() < p: num_in_test += 1 return [n - num_in_test, num_in_test] # Get an SArray where each word has a 2 element list containing # the count that will be for the training set and the count that will # be assigned to the test set. data = dataset.apply(lambda x: dict([(key, word_count_split(int(value), prob)) \ for key, value in six.iteritems(x)])) # Materialize the data set data.__materialize__() # Grab respective counts for each data set train = data.apply(lambda x: grab_values(x, train=True)) test = data.apply(lambda x: grab_values(x, train=False)) return train, test
[ "def", "random_split", "(", "dataset", ",", "prob", "=", ".5", ")", ":", "def", "grab_values", "(", "x", ",", "train", "=", "True", ")", ":", "if", "train", ":", "ix", "=", "0", "else", ":", "ix", "=", "1", "return", "dict", "(", "[", "(", "key", ",", "value", "[", "ix", "]", ")", "for", "key", ",", "value", "in", "six", ".", "iteritems", "(", "x", ")", "if", "value", "[", "ix", "]", "!=", "0", "]", ")", "def", "word_count_split", "(", "n", ",", "p", ")", ":", "num_in_test", "=", "0", "for", "i", "in", "range", "(", "n", ")", ":", "if", "random", ".", "random", "(", ")", "<", "p", ":", "num_in_test", "+=", "1", "return", "[", "n", "-", "num_in_test", ",", "num_in_test", "]", "# Get an SArray where each word has a 2 element list containing", "# the count that will be for the training set and the count that will", "# be assigned to the test set.", "data", "=", "dataset", ".", "apply", "(", "lambda", "x", ":", "dict", "(", "[", "(", "key", ",", "word_count_split", "(", "int", "(", "value", ")", ",", "prob", ")", ")", "for", "key", ",", "value", "in", "six", ".", "iteritems", "(", "x", ")", "]", ")", ")", "# Materialize the data set", "data", ".", "__materialize__", "(", ")", "# Grab respective counts for each data set", "train", "=", "data", ".", "apply", "(", "lambda", "x", ":", "grab_values", "(", "x", ",", "train", "=", "True", ")", ")", "test", "=", "data", ".", "apply", "(", "lambda", "x", ":", "grab_values", "(", "x", ",", "train", "=", "False", ")", ")", "return", "train", ",", "test" ]
Utility for performing a random split for text data that is already in bag-of-words format. For each (word, count) pair in a particular element, the counts are uniformly partitioned in either a training set or a test set. Parameters ---------- dataset : SArray of type dict, SFrame with columns of type dict A data set in bag-of-words format. prob : float, optional Probability for sampling a word to be placed in the test set. Returns ------- train, test : SArray Two data sets in bag-of-words format, where the combined counts are equal to the counts in the original data set. Examples -------- >>> docs = turicreate.SArray([{'are':5, 'you':3, 'not': 1, 'entertained':10}]) >>> train, test = turicreate.text_analytics.random_split(docs) >>> print(train) [{'not': 1.0, 'you': 3.0, 'are': 3.0, 'entertained': 7.0}] >>> print(test) [{'are': 2.0, 'entertained': 3.0}]
[ "Utility", "for", "performing", "a", "random", "split", "for", "text", "data", "that", "is", "already", "in", "bag", "-", "of", "-", "words", "format", ".", "For", "each", "(", "word", "count", ")", "pair", "in", "a", "particular", "element", "the", "counts", "are", "uniformly", "partitioned", "in", "either", "a", "training", "set", "or", "a", "test", "set", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/text_analytics/_util.py#L719-L778
train
apple/turicreate
src/external/xgboost/python-package/xgboost/training.py
train
def train(params, dtrain, num_boost_round=10, evals=(), obj=None, feval=None, maximize=False, early_stopping_rounds=None, evals_result=None, verbose_eval=True, learning_rates=None, xgb_model=None): # pylint: disable=too-many-statements,too-many-branches, attribute-defined-outside-init """Train a booster with given parameters. Parameters ---------- params : dict Booster params. dtrain : DMatrix Data to be trained. num_boost_round: int Number of boosting iterations. watchlist (evals): list of pairs (DMatrix, string) List of items to be evaluated during training, this allows user to watch performance on the validation set. obj : function Customized objective function. feval : function Customized evaluation function. maximize : bool Whether to maximize feval. early_stopping_rounds: int Activates early stopping. Validation error needs to decrease at least every <early_stopping_rounds> round(s) to continue training. Requires at least one item in evals. If there's more than one, will use the last. Returns the model from the last iteration (not the best one). If early stopping occurs, the model will have two additional fields: bst.best_score and bst.best_iteration. evals_result: dict This dictionary stores the evaluation results of all the items in watchlist. Example: with a watchlist containing [(dtest,'eval'), (dtrain,'train')] and and a paramater containing ('eval_metric', 'logloss') Returns: {'train': {'logloss': ['0.48253', '0.35953']}, 'eval': {'logloss': ['0.480385', '0.357756']}} verbose_eval : bool If `verbose_eval` then the evaluation metric on the validation set, if given, is printed at each boosting stage. learning_rates: list or function Learning rate for each boosting round (yields learning rate decay). - list l: eta = l[boosting round] - function f: eta = f(boosting round, num_boost_round) xgb_model : file name of stored xgb model or 'Booster' instance Xgb model to be loaded before training (allows training continuation). Returns ------- booster : a trained booster model """ evals = list(evals) ntrees = 0 if xgb_model is not None: if not isinstance(xgb_model, STRING_TYPES): xgb_model = xgb_model.save_raw() bst = Booster(params, [dtrain] + [d[0] for d in evals], model_file=xgb_model) ntrees = len(bst.get_dump()) else: bst = Booster(params, [dtrain] + [d[0] for d in evals]) if evals_result is not None: if not isinstance(evals_result, dict): raise TypeError('evals_result has to be a dictionary') else: evals_name = [d[1] for d in evals] evals_result.clear() evals_result.update({key: {} for key in evals_name}) if not early_stopping_rounds: for i in range(num_boost_round): bst.update(dtrain, i, obj) ntrees += 1 if len(evals) != 0: bst_eval_set = bst.eval_set(evals, i, feval) if isinstance(bst_eval_set, STRING_TYPES): msg = bst_eval_set else: msg = bst_eval_set.decode() if verbose_eval: sys.stderr.write(msg + '\n') if evals_result is not None: res = re.findall("([0-9a-zA-Z@]+[-]*):-?([0-9.]+).", msg) for key in evals_name: evals_idx = evals_name.index(key) res_per_eval = len(res) // len(evals_name) for r in range(res_per_eval): res_item = res[(evals_idx*res_per_eval) + r] res_key = res_item[0] res_val = res_item[1] if res_key in evals_result[key]: evals_result[key][res_key].append(res_val) else: evals_result[key][res_key] = [res_val] bst.best_iteration = (ntrees - 1) return bst else: # early stopping if len(evals) < 1: raise ValueError('For early stopping you need at least one set in evals.') if verbose_eval: sys.stderr.write("Will train until {} error hasn't decreased in {} rounds.\n".format(\ evals[-1][1], early_stopping_rounds)) # is params a list of tuples? are we using multiple eval metrics? if isinstance(params, list): if len(params) != len(dict(params).items()): raise ValueError('Check your params.'\ 'Early stopping works with single eval metric only.') params = dict(params) # either minimize loss or maximize AUC/MAP/NDCG maximize_score = False if 'eval_metric' in params: maximize_metrics = ('auc', 'map', 'ndcg') if any(params['eval_metric'].startswith(x) for x in maximize_metrics): maximize_score = True if feval is not None: maximize_score = maximize if maximize_score: best_score = 0.0 else: best_score = float('inf') best_msg = '' best_score_i = ntrees if isinstance(learning_rates, list) and len(learning_rates) != num_boost_round: raise ValueError("Length of list 'learning_rates' has to equal 'num_boost_round'.") for i in range(num_boost_round): if learning_rates is not None: if isinstance(learning_rates, list): bst.set_param({'eta': learning_rates[i]}) else: bst.set_param({'eta': learning_rates(i, num_boost_round)}) bst.update(dtrain, i, obj) ntrees += 1 bst_eval_set = bst.eval_set(evals, i, feval) if isinstance(bst_eval_set, STRING_TYPES): msg = bst_eval_set else: msg = bst_eval_set.decode() if verbose_eval: sys.stderr.write(msg + '\n') if evals_result is not None: res = re.findall("([0-9a-zA-Z@]+[-]*):-?([0-9.]+).", msg) for key in evals_name: evals_idx = evals_name.index(key) res_per_eval = len(res) // len(evals_name) for r in range(res_per_eval): res_item = res[(evals_idx*res_per_eval) + r] res_key = res_item[0] res_val = res_item[1] if res_key in evals_result[key]: evals_result[key][res_key].append(res_val) else: evals_result[key][res_key] = [res_val] score = float(msg.rsplit(':', 1)[1]) if (maximize_score and score > best_score) or \ (not maximize_score and score < best_score): best_score = score best_score_i = (ntrees - 1) best_msg = msg elif i - best_score_i >= early_stopping_rounds: sys.stderr.write("Stopping. Best iteration:\n{}\n\n".format(best_msg)) bst.best_score = best_score bst.best_iteration = best_score_i break bst.best_score = best_score bst.best_iteration = best_score_i return bst
python
def train(params, dtrain, num_boost_round=10, evals=(), obj=None, feval=None, maximize=False, early_stopping_rounds=None, evals_result=None, verbose_eval=True, learning_rates=None, xgb_model=None): # pylint: disable=too-many-statements,too-many-branches, attribute-defined-outside-init """Train a booster with given parameters. Parameters ---------- params : dict Booster params. dtrain : DMatrix Data to be trained. num_boost_round: int Number of boosting iterations. watchlist (evals): list of pairs (DMatrix, string) List of items to be evaluated during training, this allows user to watch performance on the validation set. obj : function Customized objective function. feval : function Customized evaluation function. maximize : bool Whether to maximize feval. early_stopping_rounds: int Activates early stopping. Validation error needs to decrease at least every <early_stopping_rounds> round(s) to continue training. Requires at least one item in evals. If there's more than one, will use the last. Returns the model from the last iteration (not the best one). If early stopping occurs, the model will have two additional fields: bst.best_score and bst.best_iteration. evals_result: dict This dictionary stores the evaluation results of all the items in watchlist. Example: with a watchlist containing [(dtest,'eval'), (dtrain,'train')] and and a paramater containing ('eval_metric', 'logloss') Returns: {'train': {'logloss': ['0.48253', '0.35953']}, 'eval': {'logloss': ['0.480385', '0.357756']}} verbose_eval : bool If `verbose_eval` then the evaluation metric on the validation set, if given, is printed at each boosting stage. learning_rates: list or function Learning rate for each boosting round (yields learning rate decay). - list l: eta = l[boosting round] - function f: eta = f(boosting round, num_boost_round) xgb_model : file name of stored xgb model or 'Booster' instance Xgb model to be loaded before training (allows training continuation). Returns ------- booster : a trained booster model """ evals = list(evals) ntrees = 0 if xgb_model is not None: if not isinstance(xgb_model, STRING_TYPES): xgb_model = xgb_model.save_raw() bst = Booster(params, [dtrain] + [d[0] for d in evals], model_file=xgb_model) ntrees = len(bst.get_dump()) else: bst = Booster(params, [dtrain] + [d[0] for d in evals]) if evals_result is not None: if not isinstance(evals_result, dict): raise TypeError('evals_result has to be a dictionary') else: evals_name = [d[1] for d in evals] evals_result.clear() evals_result.update({key: {} for key in evals_name}) if not early_stopping_rounds: for i in range(num_boost_round): bst.update(dtrain, i, obj) ntrees += 1 if len(evals) != 0: bst_eval_set = bst.eval_set(evals, i, feval) if isinstance(bst_eval_set, STRING_TYPES): msg = bst_eval_set else: msg = bst_eval_set.decode() if verbose_eval: sys.stderr.write(msg + '\n') if evals_result is not None: res = re.findall("([0-9a-zA-Z@]+[-]*):-?([0-9.]+).", msg) for key in evals_name: evals_idx = evals_name.index(key) res_per_eval = len(res) // len(evals_name) for r in range(res_per_eval): res_item = res[(evals_idx*res_per_eval) + r] res_key = res_item[0] res_val = res_item[1] if res_key in evals_result[key]: evals_result[key][res_key].append(res_val) else: evals_result[key][res_key] = [res_val] bst.best_iteration = (ntrees - 1) return bst else: # early stopping if len(evals) < 1: raise ValueError('For early stopping you need at least one set in evals.') if verbose_eval: sys.stderr.write("Will train until {} error hasn't decreased in {} rounds.\n".format(\ evals[-1][1], early_stopping_rounds)) # is params a list of tuples? are we using multiple eval metrics? if isinstance(params, list): if len(params) != len(dict(params).items()): raise ValueError('Check your params.'\ 'Early stopping works with single eval metric only.') params = dict(params) # either minimize loss or maximize AUC/MAP/NDCG maximize_score = False if 'eval_metric' in params: maximize_metrics = ('auc', 'map', 'ndcg') if any(params['eval_metric'].startswith(x) for x in maximize_metrics): maximize_score = True if feval is not None: maximize_score = maximize if maximize_score: best_score = 0.0 else: best_score = float('inf') best_msg = '' best_score_i = ntrees if isinstance(learning_rates, list) and len(learning_rates) != num_boost_round: raise ValueError("Length of list 'learning_rates' has to equal 'num_boost_round'.") for i in range(num_boost_round): if learning_rates is not None: if isinstance(learning_rates, list): bst.set_param({'eta': learning_rates[i]}) else: bst.set_param({'eta': learning_rates(i, num_boost_round)}) bst.update(dtrain, i, obj) ntrees += 1 bst_eval_set = bst.eval_set(evals, i, feval) if isinstance(bst_eval_set, STRING_TYPES): msg = bst_eval_set else: msg = bst_eval_set.decode() if verbose_eval: sys.stderr.write(msg + '\n') if evals_result is not None: res = re.findall("([0-9a-zA-Z@]+[-]*):-?([0-9.]+).", msg) for key in evals_name: evals_idx = evals_name.index(key) res_per_eval = len(res) // len(evals_name) for r in range(res_per_eval): res_item = res[(evals_idx*res_per_eval) + r] res_key = res_item[0] res_val = res_item[1] if res_key in evals_result[key]: evals_result[key][res_key].append(res_val) else: evals_result[key][res_key] = [res_val] score = float(msg.rsplit(':', 1)[1]) if (maximize_score and score > best_score) or \ (not maximize_score and score < best_score): best_score = score best_score_i = (ntrees - 1) best_msg = msg elif i - best_score_i >= early_stopping_rounds: sys.stderr.write("Stopping. Best iteration:\n{}\n\n".format(best_msg)) bst.best_score = best_score bst.best_iteration = best_score_i break bst.best_score = best_score bst.best_iteration = best_score_i return bst
[ "def", "train", "(", "params", ",", "dtrain", ",", "num_boost_round", "=", "10", ",", "evals", "=", "(", ")", ",", "obj", "=", "None", ",", "feval", "=", "None", ",", "maximize", "=", "False", ",", "early_stopping_rounds", "=", "None", ",", "evals_result", "=", "None", ",", "verbose_eval", "=", "True", ",", "learning_rates", "=", "None", ",", "xgb_model", "=", "None", ")", ":", "# pylint: disable=too-many-statements,too-many-branches, attribute-defined-outside-init", "evals", "=", "list", "(", "evals", ")", "ntrees", "=", "0", "if", "xgb_model", "is", "not", "None", ":", "if", "not", "isinstance", "(", "xgb_model", ",", "STRING_TYPES", ")", ":", "xgb_model", "=", "xgb_model", ".", "save_raw", "(", ")", "bst", "=", "Booster", "(", "params", ",", "[", "dtrain", "]", "+", "[", "d", "[", "0", "]", "for", "d", "in", "evals", "]", ",", "model_file", "=", "xgb_model", ")", "ntrees", "=", "len", "(", "bst", ".", "get_dump", "(", ")", ")", "else", ":", "bst", "=", "Booster", "(", "params", ",", "[", "dtrain", "]", "+", "[", "d", "[", "0", "]", "for", "d", "in", "evals", "]", ")", "if", "evals_result", "is", "not", "None", ":", "if", "not", "isinstance", "(", "evals_result", ",", "dict", ")", ":", "raise", "TypeError", "(", "'evals_result has to be a dictionary'", ")", "else", ":", "evals_name", "=", "[", "d", "[", "1", "]", "for", "d", "in", "evals", "]", "evals_result", ".", "clear", "(", ")", "evals_result", ".", "update", "(", "{", "key", ":", "{", "}", "for", "key", "in", "evals_name", "}", ")", "if", "not", "early_stopping_rounds", ":", "for", "i", "in", "range", "(", "num_boost_round", ")", ":", "bst", ".", "update", "(", "dtrain", ",", "i", ",", "obj", ")", "ntrees", "+=", "1", "if", "len", "(", "evals", ")", "!=", "0", ":", "bst_eval_set", "=", "bst", ".", "eval_set", "(", "evals", ",", "i", ",", "feval", ")", "if", "isinstance", "(", "bst_eval_set", ",", "STRING_TYPES", ")", ":", "msg", "=", "bst_eval_set", "else", ":", "msg", "=", "bst_eval_set", ".", "decode", "(", ")", "if", "verbose_eval", ":", "sys", ".", "stderr", ".", "write", "(", "msg", "+", "'\\n'", ")", "if", "evals_result", "is", "not", "None", ":", "res", "=", "re", ".", "findall", "(", "\"([0-9a-zA-Z@]+[-]*):-?([0-9.]+).\"", ",", "msg", ")", "for", "key", "in", "evals_name", ":", "evals_idx", "=", "evals_name", ".", "index", "(", "key", ")", "res_per_eval", "=", "len", "(", "res", ")", "//", "len", "(", "evals_name", ")", "for", "r", "in", "range", "(", "res_per_eval", ")", ":", "res_item", "=", "res", "[", "(", "evals_idx", "*", "res_per_eval", ")", "+", "r", "]", "res_key", "=", "res_item", "[", "0", "]", "res_val", "=", "res_item", "[", "1", "]", "if", "res_key", "in", "evals_result", "[", "key", "]", ":", "evals_result", "[", "key", "]", "[", "res_key", "]", ".", "append", "(", "res_val", ")", "else", ":", "evals_result", "[", "key", "]", "[", "res_key", "]", "=", "[", "res_val", "]", "bst", ".", "best_iteration", "=", "(", "ntrees", "-", "1", ")", "return", "bst", "else", ":", "# early stopping", "if", "len", "(", "evals", ")", "<", "1", ":", "raise", "ValueError", "(", "'For early stopping you need at least one set in evals.'", ")", "if", "verbose_eval", ":", "sys", ".", "stderr", ".", "write", "(", "\"Will train until {} error hasn't decreased in {} rounds.\\n\"", ".", "format", "(", "evals", "[", "-", "1", "]", "[", "1", "]", ",", "early_stopping_rounds", ")", ")", "# is params a list of tuples? are we using multiple eval metrics?", "if", "isinstance", "(", "params", ",", "list", ")", ":", "if", "len", "(", "params", ")", "!=", "len", "(", "dict", "(", "params", ")", ".", "items", "(", ")", ")", ":", "raise", "ValueError", "(", "'Check your params.'", "'Early stopping works with single eval metric only.'", ")", "params", "=", "dict", "(", "params", ")", "# either minimize loss or maximize AUC/MAP/NDCG", "maximize_score", "=", "False", "if", "'eval_metric'", "in", "params", ":", "maximize_metrics", "=", "(", "'auc'", ",", "'map'", ",", "'ndcg'", ")", "if", "any", "(", "params", "[", "'eval_metric'", "]", ".", "startswith", "(", "x", ")", "for", "x", "in", "maximize_metrics", ")", ":", "maximize_score", "=", "True", "if", "feval", "is", "not", "None", ":", "maximize_score", "=", "maximize", "if", "maximize_score", ":", "best_score", "=", "0.0", "else", ":", "best_score", "=", "float", "(", "'inf'", ")", "best_msg", "=", "''", "best_score_i", "=", "ntrees", "if", "isinstance", "(", "learning_rates", ",", "list", ")", "and", "len", "(", "learning_rates", ")", "!=", "num_boost_round", ":", "raise", "ValueError", "(", "\"Length of list 'learning_rates' has to equal 'num_boost_round'.\"", ")", "for", "i", "in", "range", "(", "num_boost_round", ")", ":", "if", "learning_rates", "is", "not", "None", ":", "if", "isinstance", "(", "learning_rates", ",", "list", ")", ":", "bst", ".", "set_param", "(", "{", "'eta'", ":", "learning_rates", "[", "i", "]", "}", ")", "else", ":", "bst", ".", "set_param", "(", "{", "'eta'", ":", "learning_rates", "(", "i", ",", "num_boost_round", ")", "}", ")", "bst", ".", "update", "(", "dtrain", ",", "i", ",", "obj", ")", "ntrees", "+=", "1", "bst_eval_set", "=", "bst", ".", "eval_set", "(", "evals", ",", "i", ",", "feval", ")", "if", "isinstance", "(", "bst_eval_set", ",", "STRING_TYPES", ")", ":", "msg", "=", "bst_eval_set", "else", ":", "msg", "=", "bst_eval_set", ".", "decode", "(", ")", "if", "verbose_eval", ":", "sys", ".", "stderr", ".", "write", "(", "msg", "+", "'\\n'", ")", "if", "evals_result", "is", "not", "None", ":", "res", "=", "re", ".", "findall", "(", "\"([0-9a-zA-Z@]+[-]*):-?([0-9.]+).\"", ",", "msg", ")", "for", "key", "in", "evals_name", ":", "evals_idx", "=", "evals_name", ".", "index", "(", "key", ")", "res_per_eval", "=", "len", "(", "res", ")", "//", "len", "(", "evals_name", ")", "for", "r", "in", "range", "(", "res_per_eval", ")", ":", "res_item", "=", "res", "[", "(", "evals_idx", "*", "res_per_eval", ")", "+", "r", "]", "res_key", "=", "res_item", "[", "0", "]", "res_val", "=", "res_item", "[", "1", "]", "if", "res_key", "in", "evals_result", "[", "key", "]", ":", "evals_result", "[", "key", "]", "[", "res_key", "]", ".", "append", "(", "res_val", ")", "else", ":", "evals_result", "[", "key", "]", "[", "res_key", "]", "=", "[", "res_val", "]", "score", "=", "float", "(", "msg", ".", "rsplit", "(", "':'", ",", "1", ")", "[", "1", "]", ")", "if", "(", "maximize_score", "and", "score", ">", "best_score", ")", "or", "(", "not", "maximize_score", "and", "score", "<", "best_score", ")", ":", "best_score", "=", "score", "best_score_i", "=", "(", "ntrees", "-", "1", ")", "best_msg", "=", "msg", "elif", "i", "-", "best_score_i", ">=", "early_stopping_rounds", ":", "sys", ".", "stderr", ".", "write", "(", "\"Stopping. Best iteration:\\n{}\\n\\n\"", ".", "format", "(", "best_msg", ")", ")", "bst", ".", "best_score", "=", "best_score", "bst", ".", "best_iteration", "=", "best_score_i", "break", "bst", ".", "best_score", "=", "best_score", "bst", ".", "best_iteration", "=", "best_score_i", "return", "bst" ]
Train a booster with given parameters. Parameters ---------- params : dict Booster params. dtrain : DMatrix Data to be trained. num_boost_round: int Number of boosting iterations. watchlist (evals): list of pairs (DMatrix, string) List of items to be evaluated during training, this allows user to watch performance on the validation set. obj : function Customized objective function. feval : function Customized evaluation function. maximize : bool Whether to maximize feval. early_stopping_rounds: int Activates early stopping. Validation error needs to decrease at least every <early_stopping_rounds> round(s) to continue training. Requires at least one item in evals. If there's more than one, will use the last. Returns the model from the last iteration (not the best one). If early stopping occurs, the model will have two additional fields: bst.best_score and bst.best_iteration. evals_result: dict This dictionary stores the evaluation results of all the items in watchlist. Example: with a watchlist containing [(dtest,'eval'), (dtrain,'train')] and and a paramater containing ('eval_metric', 'logloss') Returns: {'train': {'logloss': ['0.48253', '0.35953']}, 'eval': {'logloss': ['0.480385', '0.357756']}} verbose_eval : bool If `verbose_eval` then the evaluation metric on the validation set, if given, is printed at each boosting stage. learning_rates: list or function Learning rate for each boosting round (yields learning rate decay). - list l: eta = l[boosting round] - function f: eta = f(boosting round, num_boost_round) xgb_model : file name of stored xgb model or 'Booster' instance Xgb model to be loaded before training (allows training continuation). Returns ------- booster : a trained booster model
[ "Train", "a", "booster", "with", "given", "parameters", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/python-package/xgboost/training.py#L12-L192
train
apple/turicreate
src/external/xgboost/python-package/xgboost/training.py
mknfold
def mknfold(dall, nfold, param, seed, evals=(), fpreproc=None): """ Make an n-fold list of CVPack from random indices. """ evals = list(evals) np.random.seed(seed) randidx = np.random.permutation(dall.num_row()) kstep = len(randidx) / nfold idset = [randidx[(i * kstep): min(len(randidx), (i + 1) * kstep)] for i in range(nfold)] ret = [] for k in range(nfold): dtrain = dall.slice(np.concatenate([idset[i] for i in range(nfold) if k != i])) dtest = dall.slice(idset[k]) # run preprocessing on the data set if needed if fpreproc is not None: dtrain, dtest, tparam = fpreproc(dtrain, dtest, param.copy()) else: tparam = param plst = list(tparam.items()) + [('eval_metric', itm) for itm in evals] ret.append(CVPack(dtrain, dtest, plst)) return ret
python
def mknfold(dall, nfold, param, seed, evals=(), fpreproc=None): """ Make an n-fold list of CVPack from random indices. """ evals = list(evals) np.random.seed(seed) randidx = np.random.permutation(dall.num_row()) kstep = len(randidx) / nfold idset = [randidx[(i * kstep): min(len(randidx), (i + 1) * kstep)] for i in range(nfold)] ret = [] for k in range(nfold): dtrain = dall.slice(np.concatenate([idset[i] for i in range(nfold) if k != i])) dtest = dall.slice(idset[k]) # run preprocessing on the data set if needed if fpreproc is not None: dtrain, dtest, tparam = fpreproc(dtrain, dtest, param.copy()) else: tparam = param plst = list(tparam.items()) + [('eval_metric', itm) for itm in evals] ret.append(CVPack(dtrain, dtest, plst)) return ret
[ "def", "mknfold", "(", "dall", ",", "nfold", ",", "param", ",", "seed", ",", "evals", "=", "(", ")", ",", "fpreproc", "=", "None", ")", ":", "evals", "=", "list", "(", "evals", ")", "np", ".", "random", ".", "seed", "(", "seed", ")", "randidx", "=", "np", ".", "random", ".", "permutation", "(", "dall", ".", "num_row", "(", ")", ")", "kstep", "=", "len", "(", "randidx", ")", "/", "nfold", "idset", "=", "[", "randidx", "[", "(", "i", "*", "kstep", ")", ":", "min", "(", "len", "(", "randidx", ")", ",", "(", "i", "+", "1", ")", "*", "kstep", ")", "]", "for", "i", "in", "range", "(", "nfold", ")", "]", "ret", "=", "[", "]", "for", "k", "in", "range", "(", "nfold", ")", ":", "dtrain", "=", "dall", ".", "slice", "(", "np", ".", "concatenate", "(", "[", "idset", "[", "i", "]", "for", "i", "in", "range", "(", "nfold", ")", "if", "k", "!=", "i", "]", ")", ")", "dtest", "=", "dall", ".", "slice", "(", "idset", "[", "k", "]", ")", "# run preprocessing on the data set if needed", "if", "fpreproc", "is", "not", "None", ":", "dtrain", ",", "dtest", ",", "tparam", "=", "fpreproc", "(", "dtrain", ",", "dtest", ",", "param", ".", "copy", "(", ")", ")", "else", ":", "tparam", "=", "param", "plst", "=", "list", "(", "tparam", ".", "items", "(", ")", ")", "+", "[", "(", "'eval_metric'", ",", "itm", ")", "for", "itm", "in", "evals", "]", "ret", ".", "append", "(", "CVPack", "(", "dtrain", ",", "dtest", ",", "plst", ")", ")", "return", "ret" ]
Make an n-fold list of CVPack from random indices.
[ "Make", "an", "n", "-", "fold", "list", "of", "CVPack", "from", "random", "indices", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/python-package/xgboost/training.py#L213-L233
train
apple/turicreate
src/external/xgboost/python-package/xgboost/training.py
aggcv
def aggcv(rlist, show_stdv=True, show_progress=None, as_pandas=True): # pylint: disable=invalid-name """ Aggregate cross-validation results. """ cvmap = {} idx = rlist[0].split()[0] for line in rlist: arr = line.split() assert idx == arr[0] for it in arr[1:]: if not isinstance(it, STRING_TYPES): it = it.decode() k, v = it.split(':') if k not in cvmap: cvmap[k] = [] cvmap[k].append(float(v)) msg = idx if show_stdv: fmt = '\tcv-{0}:{1}+{2}' else: fmt = '\tcv-{0}:{1}' index = [] results = [] for k, v in sorted(cvmap.items(), key=lambda x: x[0]): v = np.array(v) if not isinstance(msg, STRING_TYPES): msg = msg.decode() mean, std = np.mean(v), np.std(v) msg += fmt.format(k, mean, std) index.extend([k + '-mean', k + '-std']) results.extend([mean, std]) if as_pandas: try: import pandas as pd results = pd.Series(results, index=index) except ImportError: if show_progress is None: show_progress = True else: # if show_progress is default (None), # result will be np.ndarray as it can't hold column name if show_progress is None: show_progress = True if show_progress: sys.stderr.write(msg + '\n') return results
python
def aggcv(rlist, show_stdv=True, show_progress=None, as_pandas=True): # pylint: disable=invalid-name """ Aggregate cross-validation results. """ cvmap = {} idx = rlist[0].split()[0] for line in rlist: arr = line.split() assert idx == arr[0] for it in arr[1:]: if not isinstance(it, STRING_TYPES): it = it.decode() k, v = it.split(':') if k not in cvmap: cvmap[k] = [] cvmap[k].append(float(v)) msg = idx if show_stdv: fmt = '\tcv-{0}:{1}+{2}' else: fmt = '\tcv-{0}:{1}' index = [] results = [] for k, v in sorted(cvmap.items(), key=lambda x: x[0]): v = np.array(v) if not isinstance(msg, STRING_TYPES): msg = msg.decode() mean, std = np.mean(v), np.std(v) msg += fmt.format(k, mean, std) index.extend([k + '-mean', k + '-std']) results.extend([mean, std]) if as_pandas: try: import pandas as pd results = pd.Series(results, index=index) except ImportError: if show_progress is None: show_progress = True else: # if show_progress is default (None), # result will be np.ndarray as it can't hold column name if show_progress is None: show_progress = True if show_progress: sys.stderr.write(msg + '\n') return results
[ "def", "aggcv", "(", "rlist", ",", "show_stdv", "=", "True", ",", "show_progress", "=", "None", ",", "as_pandas", "=", "True", ")", ":", "# pylint: disable=invalid-name", "cvmap", "=", "{", "}", "idx", "=", "rlist", "[", "0", "]", ".", "split", "(", ")", "[", "0", "]", "for", "line", "in", "rlist", ":", "arr", "=", "line", ".", "split", "(", ")", "assert", "idx", "==", "arr", "[", "0", "]", "for", "it", "in", "arr", "[", "1", ":", "]", ":", "if", "not", "isinstance", "(", "it", ",", "STRING_TYPES", ")", ":", "it", "=", "it", ".", "decode", "(", ")", "k", ",", "v", "=", "it", ".", "split", "(", "':'", ")", "if", "k", "not", "in", "cvmap", ":", "cvmap", "[", "k", "]", "=", "[", "]", "cvmap", "[", "k", "]", ".", "append", "(", "float", "(", "v", ")", ")", "msg", "=", "idx", "if", "show_stdv", ":", "fmt", "=", "'\\tcv-{0}:{1}+{2}'", "else", ":", "fmt", "=", "'\\tcv-{0}:{1}'", "index", "=", "[", "]", "results", "=", "[", "]", "for", "k", ",", "v", "in", "sorted", "(", "cvmap", ".", "items", "(", ")", ",", "key", "=", "lambda", "x", ":", "x", "[", "0", "]", ")", ":", "v", "=", "np", ".", "array", "(", "v", ")", "if", "not", "isinstance", "(", "msg", ",", "STRING_TYPES", ")", ":", "msg", "=", "msg", ".", "decode", "(", ")", "mean", ",", "std", "=", "np", ".", "mean", "(", "v", ")", ",", "np", ".", "std", "(", "v", ")", "msg", "+=", "fmt", ".", "format", "(", "k", ",", "mean", ",", "std", ")", "index", ".", "extend", "(", "[", "k", "+", "'-mean'", ",", "k", "+", "'-std'", "]", ")", "results", ".", "extend", "(", "[", "mean", ",", "std", "]", ")", "if", "as_pandas", ":", "try", ":", "import", "pandas", "as", "pd", "results", "=", "pd", ".", "Series", "(", "results", ",", "index", "=", "index", ")", "except", "ImportError", ":", "if", "show_progress", "is", "None", ":", "show_progress", "=", "True", "else", ":", "# if show_progress is default (None),", "# result will be np.ndarray as it can't hold column name", "if", "show_progress", "is", "None", ":", "show_progress", "=", "True", "if", "show_progress", ":", "sys", ".", "stderr", ".", "write", "(", "msg", "+", "'\\n'", ")", "return", "results" ]
Aggregate cross-validation results.
[ "Aggregate", "cross", "-", "validation", "results", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/python-package/xgboost/training.py#L236-L291
train
apple/turicreate
src/external/xgboost/python-package/xgboost/training.py
cv
def cv(params, dtrain, num_boost_round=10, nfold=3, metrics=(), obj=None, feval=None, fpreproc=None, as_pandas=True, show_progress=None, show_stdv=True, seed=0): # pylint: disable = invalid-name """Cross-validation with given paramaters. Parameters ---------- params : dict Booster params. dtrain : DMatrix Data to be trained. num_boost_round : int Number of boosting iterations. nfold : int Number of folds in CV. metrics : list of strings Evaluation metrics to be watched in CV. obj : function Custom objective function. feval : function Custom evaluation function. fpreproc : function Preprocessing function that takes (dtrain, dtest, param) and returns transformed versions of those. as_pandas : bool, default True Return pd.DataFrame when pandas is installed. If False or pandas is not installed, return np.ndarray show_progress : bool or None, default None Whether to display the progress. If None, progress will be displayed when np.ndarray is returned. show_stdv : bool, default True Whether to display the standard deviation in progress. Results are not affected, and always contains std. seed : int Seed used to generate the folds (passed to numpy.random.seed). Returns ------- evaluation history : list(string) """ results = [] cvfolds = mknfold(dtrain, nfold, params, seed, metrics, fpreproc) for i in range(num_boost_round): for fold in cvfolds: fold.update(i, obj) res = aggcv([f.eval(i, feval) for f in cvfolds], show_stdv=show_stdv, show_progress=show_progress, as_pandas=as_pandas) results.append(res) if as_pandas: try: import pandas as pd results = pd.DataFrame(results) except ImportError: results = np.array(results) else: results = np.array(results) return results
python
def cv(params, dtrain, num_boost_round=10, nfold=3, metrics=(), obj=None, feval=None, fpreproc=None, as_pandas=True, show_progress=None, show_stdv=True, seed=0): # pylint: disable = invalid-name """Cross-validation with given paramaters. Parameters ---------- params : dict Booster params. dtrain : DMatrix Data to be trained. num_boost_round : int Number of boosting iterations. nfold : int Number of folds in CV. metrics : list of strings Evaluation metrics to be watched in CV. obj : function Custom objective function. feval : function Custom evaluation function. fpreproc : function Preprocessing function that takes (dtrain, dtest, param) and returns transformed versions of those. as_pandas : bool, default True Return pd.DataFrame when pandas is installed. If False or pandas is not installed, return np.ndarray show_progress : bool or None, default None Whether to display the progress. If None, progress will be displayed when np.ndarray is returned. show_stdv : bool, default True Whether to display the standard deviation in progress. Results are not affected, and always contains std. seed : int Seed used to generate the folds (passed to numpy.random.seed). Returns ------- evaluation history : list(string) """ results = [] cvfolds = mknfold(dtrain, nfold, params, seed, metrics, fpreproc) for i in range(num_boost_round): for fold in cvfolds: fold.update(i, obj) res = aggcv([f.eval(i, feval) for f in cvfolds], show_stdv=show_stdv, show_progress=show_progress, as_pandas=as_pandas) results.append(res) if as_pandas: try: import pandas as pd results = pd.DataFrame(results) except ImportError: results = np.array(results) else: results = np.array(results) return results
[ "def", "cv", "(", "params", ",", "dtrain", ",", "num_boost_round", "=", "10", ",", "nfold", "=", "3", ",", "metrics", "=", "(", ")", ",", "obj", "=", "None", ",", "feval", "=", "None", ",", "fpreproc", "=", "None", ",", "as_pandas", "=", "True", ",", "show_progress", "=", "None", ",", "show_stdv", "=", "True", ",", "seed", "=", "0", ")", ":", "# pylint: disable = invalid-name", "results", "=", "[", "]", "cvfolds", "=", "mknfold", "(", "dtrain", ",", "nfold", ",", "params", ",", "seed", ",", "metrics", ",", "fpreproc", ")", "for", "i", "in", "range", "(", "num_boost_round", ")", ":", "for", "fold", "in", "cvfolds", ":", "fold", ".", "update", "(", "i", ",", "obj", ")", "res", "=", "aggcv", "(", "[", "f", ".", "eval", "(", "i", ",", "feval", ")", "for", "f", "in", "cvfolds", "]", ",", "show_stdv", "=", "show_stdv", ",", "show_progress", "=", "show_progress", ",", "as_pandas", "=", "as_pandas", ")", "results", ".", "append", "(", "res", ")", "if", "as_pandas", ":", "try", ":", "import", "pandas", "as", "pd", "results", "=", "pd", ".", "DataFrame", "(", "results", ")", "except", "ImportError", ":", "results", "=", "np", ".", "array", "(", "results", ")", "else", ":", "results", "=", "np", ".", "array", "(", "results", ")", "return", "results" ]
Cross-validation with given paramaters. Parameters ---------- params : dict Booster params. dtrain : DMatrix Data to be trained. num_boost_round : int Number of boosting iterations. nfold : int Number of folds in CV. metrics : list of strings Evaluation metrics to be watched in CV. obj : function Custom objective function. feval : function Custom evaluation function. fpreproc : function Preprocessing function that takes (dtrain, dtest, param) and returns transformed versions of those. as_pandas : bool, default True Return pd.DataFrame when pandas is installed. If False or pandas is not installed, return np.ndarray show_progress : bool or None, default None Whether to display the progress. If None, progress will be displayed when np.ndarray is returned. show_stdv : bool, default True Whether to display the standard deviation in progress. Results are not affected, and always contains std. seed : int Seed used to generate the folds (passed to numpy.random.seed). Returns ------- evaluation history : list(string)
[ "Cross", "-", "validation", "with", "given", "paramaters", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/python-package/xgboost/training.py#L294-L354
train
apple/turicreate
src/unity/python/turicreate/toolkits/image_classifier/image_classifier.py
create
def create(dataset, target, feature=None, model = 'resnet-50', l2_penalty=0.01, l1_penalty=0.0, solver='auto', feature_rescaling=True, convergence_threshold = _DEFAULT_SOLVER_OPTIONS['convergence_threshold'], step_size = _DEFAULT_SOLVER_OPTIONS['step_size'], lbfgs_memory_level = _DEFAULT_SOLVER_OPTIONS['lbfgs_memory_level'], max_iterations = _DEFAULT_SOLVER_OPTIONS['max_iterations'], class_weights = None, validation_set = 'auto', verbose=True, seed=None, batch_size=64): """ Create a :class:`ImageClassifier` model. Parameters ---------- dataset : SFrame Input data. The column named by the 'feature' parameter will be extracted for modeling. target : string, or int Name of the column containing the target variable. The values in this column must be of string or integer type. String target variables are automatically mapped to integers in the order in which they are provided. For example, a target variable with 'cat' and 'dog' as possible values is mapped to 0 and 1 respectively with 0 being the base class and 1 being the reference class. Use `model.classes` to retrieve the order in which the classes are mapped. feature : string, optional indicates that the SFrame has only column of Image type and that will Name of the column containing the input images. 'None' (the default) indicates the only image column in `dataset` should be used as the feature. l2_penalty : float, optional Weight on l2 regularization of the model. The larger this weight, the more the model coefficients shrink toward 0. This introduces bias into the model but decreases variance, potentially leading to better predictions. The default value is 0.01; setting this parameter to 0 corresponds to unregularized logistic regression. See the ridge regression reference for more detail. l1_penalty : float, optional Weight on l1 regularization of the model. Like the l2 penalty, the higher the l1 penalty, the more the estimated coefficients shrink toward 0. The l1 penalty, however, completely zeros out sufficiently small coefficients, automatically indicating features that are not useful for the model. The default weight of 0 prevents any features from being discarded. See the LASSO regression reference for more detail. solver : string, optional Name of the solver to be used to solve the regression. See the references for more detail on each solver. Available solvers are: - *auto (default)*: automatically chooses the best solver for the data and model parameters. - *newton*: Newton-Raphson - *lbfgs*: limited memory BFGS - *fista*: accelerated gradient descent For this model, the Newton-Raphson method is equivalent to the iteratively re-weighted least squares algorithm. If the l1_penalty is greater than 0, use the 'fista' solver. The model is trained using a carefully engineered collection of methods that are automatically picked based on the input data. The ``newton`` method works best for datasets with plenty of examples and few features (long datasets). Limited memory BFGS (``lbfgs``) is a robust solver for wide datasets (i.e datasets with many coefficients). ``fista`` is the default solver for l1-regularized linear regression. The solvers are all automatically tuned and the default options should function well. See the solver options guide for setting additional parameters for each of the solvers. See the user guide for additional details on how the solver is chosen. (see `here <https://apple.github.io/turicreate/docs/userguide/supervised-learning/linear-regression.html>`_) feature_rescaling : boolean, optional Feature rescaling is an important pre-processing step that ensures that all features are on the same scale. An l2-norm rescaling is performed to make sure that all features are of the same norm. Categorical features are also rescaled by rescaling the dummy variables that are used to represent them. The coefficients are returned in original scale of the problem. This process is particularly useful when features vary widely in their ranges. convergence_threshold : float, optional Convergence is tested using variation in the training objective. The variation in the training objective is calculated using the difference between the objective values between two steps. Consider reducing this below the default value (0.01) for a more accurately trained model. Beware of overfitting (i.e a model that works well only on the training data) if this parameter is set to a very low value. lbfgs_memory_level : float, optional The L-BFGS algorithm keeps track of gradient information from the previous ``lbfgs_memory_level`` iterations. The storage requirement for each of these gradients is the ``num_coefficients`` in the problem. Increasing the ``lbfgs_memory_level ``can help improve the quality of the model trained. Setting this to more than ``max_iterations`` has the same effect as setting it to ``max_iterations``. model : string optional Uses a pretrained model to bootstrap an image classifier: - "resnet-50" : Uses a pretrained resnet model. Exported Core ML model will be ~90M. - "squeezenet_v1.1" : Uses a pretrained squeezenet model. Exported Core ML model will be ~4.7M. - "VisionFeaturePrint_Scene": Uses an OS internal feature extractor. Only on available on iOS 12.0+, macOS 10.14+ and tvOS 12.0+. Exported Core ML model will be ~41K. Models are downloaded from the internet if not available locally. Once downloaded, the models are cached for future use. step_size : float, optional The starting step size to use for the ``fista`` solver. The default is set to 1.0, this is an aggressive setting. If the first iteration takes a considerable amount of time, reducing this parameter may speed up model training. class_weights : {dict, `auto`}, optional Weights the examples in the training data according to the given class weights. If set to `None`, all classes are supposed to have weight one. The `auto` mode set the class weight to be inversely proportional to number of examples in the training data with the given class. validation_set : SFrame, optional A dataset for monitoring the model's generalization performance. The format of this SFrame must be the same as the training set. By default this argument is set to 'auto' and a validation set is automatically sampled and used for progress printing. If validation_set is set to None, then no additional metrics are computed. The default value is 'auto'. max_iterations : int, optional The maximum number of allowed passes through the data. More passes over the data can result in a more accurately trained model. Consider increasing this (the default value is 10) if the training accuracy is low and the *Grad-Norm* in the display is large. verbose : bool, optional If True, prints progress updates and model details. seed : int, optional Seed for random number generation. Set this value to ensure that the same model is created every time. batch_size : int, optional If you are getting memory errors, try decreasing this value. If you have a powerful computer, increasing this value may improve performance. Returns ------- out : ImageClassifier A trained :class:`ImageClassifier` model. Examples -------- .. sourcecode:: python >>> model = turicreate.image_classifier.create(data, target='is_expensive') # Make predictions (in various forms) >>> predictions = model.predict(data) # predictions >>> predictions = model.classify(data) # predictions with confidence >>> predictions = model.predict_topk(data) # Top-5 predictions (multiclass) # Evaluate the model with ground truth data >>> results = model.evaluate(data) See Also -------- ImageClassifier """ start_time = _time.time() # Check model parameter allowed_models = list(_pre_trained_models.MODELS.keys()) if _mac_ver() >= (10,14): allowed_models.append('VisionFeaturePrint_Scene') # Also, to make sure existing code doesn't break, replace incorrect name # with the correct name version if model == "VisionFeaturePrint_Screen": print("WARNING: Correct spelling of model name is VisionFeaturePrint_Scene; VisionFeaturePrint_Screen will be removed in subsequent versions.") model = "VisionFeaturePrint_Scene" _tkutl._check_categorical_option_type('model', model, allowed_models) # Check dataset parameter if len(dataset) == 0: raise _ToolkitError('Unable to train on empty dataset') if (feature is not None) and (feature not in dataset.column_names()): raise _ToolkitError("Image feature column '%s' does not exist" % feature) if target not in dataset.column_names(): raise _ToolkitError("Target column '%s' does not exist" % target) if(batch_size < 1): raise ValueError("'batch_size' must be greater than or equal to 1") if not (isinstance(validation_set, _tc.SFrame) or validation_set == 'auto' or validation_set is None): raise TypeError("Unrecognized value for 'validation_set'.") if feature is None: feature = _tkutl._find_only_image_column(dataset) feature_extractor = _image_feature_extractor._create_feature_extractor(model) # Extract features extracted_features = _tc.SFrame({ target: dataset[target], '__image_features__': feature_extractor.extract_features(dataset, feature, verbose=verbose, batch_size=batch_size), }) if isinstance(validation_set, _tc.SFrame): extracted_features_validation = _tc.SFrame({ target: validation_set[target], '__image_features__': feature_extractor.extract_features(validation_set, feature, verbose=verbose, batch_size=batch_size), }) else: extracted_features_validation = validation_set # Train a classifier using the extracted features extracted_features[target] = dataset[target] lr_model = _tc.logistic_classifier.create(extracted_features, features=['__image_features__'], target=target, max_iterations=max_iterations, validation_set=extracted_features_validation, seed=seed, verbose=verbose, l2_penalty=l2_penalty, l1_penalty=l1_penalty, solver=solver, feature_rescaling=feature_rescaling, convergence_threshold=convergence_threshold, step_size=step_size, lbfgs_memory_level=lbfgs_memory_level, class_weights=class_weights) # set input image shape if model in _pre_trained_models.MODELS: input_image_shape = _pre_trained_models.MODELS[model].input_image_shape else: # model == VisionFeaturePrint_Scene input_image_shape = (3, 299, 299) # Save the model state = { 'classifier': lr_model, 'model': model, 'max_iterations': max_iterations, 'feature_extractor': feature_extractor, 'input_image_shape': input_image_shape, 'target': target, 'feature': feature, 'num_features': 1, 'num_classes': lr_model.num_classes, 'classes': lr_model.classes, 'num_examples': lr_model.num_examples, 'training_time': _time.time() - start_time, 'training_loss': lr_model.training_loss, } return ImageClassifier(state)
python
def create(dataset, target, feature=None, model = 'resnet-50', l2_penalty=0.01, l1_penalty=0.0, solver='auto', feature_rescaling=True, convergence_threshold = _DEFAULT_SOLVER_OPTIONS['convergence_threshold'], step_size = _DEFAULT_SOLVER_OPTIONS['step_size'], lbfgs_memory_level = _DEFAULT_SOLVER_OPTIONS['lbfgs_memory_level'], max_iterations = _DEFAULT_SOLVER_OPTIONS['max_iterations'], class_weights = None, validation_set = 'auto', verbose=True, seed=None, batch_size=64): """ Create a :class:`ImageClassifier` model. Parameters ---------- dataset : SFrame Input data. The column named by the 'feature' parameter will be extracted for modeling. target : string, or int Name of the column containing the target variable. The values in this column must be of string or integer type. String target variables are automatically mapped to integers in the order in which they are provided. For example, a target variable with 'cat' and 'dog' as possible values is mapped to 0 and 1 respectively with 0 being the base class and 1 being the reference class. Use `model.classes` to retrieve the order in which the classes are mapped. feature : string, optional indicates that the SFrame has only column of Image type and that will Name of the column containing the input images. 'None' (the default) indicates the only image column in `dataset` should be used as the feature. l2_penalty : float, optional Weight on l2 regularization of the model. The larger this weight, the more the model coefficients shrink toward 0. This introduces bias into the model but decreases variance, potentially leading to better predictions. The default value is 0.01; setting this parameter to 0 corresponds to unregularized logistic regression. See the ridge regression reference for more detail. l1_penalty : float, optional Weight on l1 regularization of the model. Like the l2 penalty, the higher the l1 penalty, the more the estimated coefficients shrink toward 0. The l1 penalty, however, completely zeros out sufficiently small coefficients, automatically indicating features that are not useful for the model. The default weight of 0 prevents any features from being discarded. See the LASSO regression reference for more detail. solver : string, optional Name of the solver to be used to solve the regression. See the references for more detail on each solver. Available solvers are: - *auto (default)*: automatically chooses the best solver for the data and model parameters. - *newton*: Newton-Raphson - *lbfgs*: limited memory BFGS - *fista*: accelerated gradient descent For this model, the Newton-Raphson method is equivalent to the iteratively re-weighted least squares algorithm. If the l1_penalty is greater than 0, use the 'fista' solver. The model is trained using a carefully engineered collection of methods that are automatically picked based on the input data. The ``newton`` method works best for datasets with plenty of examples and few features (long datasets). Limited memory BFGS (``lbfgs``) is a robust solver for wide datasets (i.e datasets with many coefficients). ``fista`` is the default solver for l1-regularized linear regression. The solvers are all automatically tuned and the default options should function well. See the solver options guide for setting additional parameters for each of the solvers. See the user guide for additional details on how the solver is chosen. (see `here <https://apple.github.io/turicreate/docs/userguide/supervised-learning/linear-regression.html>`_) feature_rescaling : boolean, optional Feature rescaling is an important pre-processing step that ensures that all features are on the same scale. An l2-norm rescaling is performed to make sure that all features are of the same norm. Categorical features are also rescaled by rescaling the dummy variables that are used to represent them. The coefficients are returned in original scale of the problem. This process is particularly useful when features vary widely in their ranges. convergence_threshold : float, optional Convergence is tested using variation in the training objective. The variation in the training objective is calculated using the difference between the objective values between two steps. Consider reducing this below the default value (0.01) for a more accurately trained model. Beware of overfitting (i.e a model that works well only on the training data) if this parameter is set to a very low value. lbfgs_memory_level : float, optional The L-BFGS algorithm keeps track of gradient information from the previous ``lbfgs_memory_level`` iterations. The storage requirement for each of these gradients is the ``num_coefficients`` in the problem. Increasing the ``lbfgs_memory_level ``can help improve the quality of the model trained. Setting this to more than ``max_iterations`` has the same effect as setting it to ``max_iterations``. model : string optional Uses a pretrained model to bootstrap an image classifier: - "resnet-50" : Uses a pretrained resnet model. Exported Core ML model will be ~90M. - "squeezenet_v1.1" : Uses a pretrained squeezenet model. Exported Core ML model will be ~4.7M. - "VisionFeaturePrint_Scene": Uses an OS internal feature extractor. Only on available on iOS 12.0+, macOS 10.14+ and tvOS 12.0+. Exported Core ML model will be ~41K. Models are downloaded from the internet if not available locally. Once downloaded, the models are cached for future use. step_size : float, optional The starting step size to use for the ``fista`` solver. The default is set to 1.0, this is an aggressive setting. If the first iteration takes a considerable amount of time, reducing this parameter may speed up model training. class_weights : {dict, `auto`}, optional Weights the examples in the training data according to the given class weights. If set to `None`, all classes are supposed to have weight one. The `auto` mode set the class weight to be inversely proportional to number of examples in the training data with the given class. validation_set : SFrame, optional A dataset for monitoring the model's generalization performance. The format of this SFrame must be the same as the training set. By default this argument is set to 'auto' and a validation set is automatically sampled and used for progress printing. If validation_set is set to None, then no additional metrics are computed. The default value is 'auto'. max_iterations : int, optional The maximum number of allowed passes through the data. More passes over the data can result in a more accurately trained model. Consider increasing this (the default value is 10) if the training accuracy is low and the *Grad-Norm* in the display is large. verbose : bool, optional If True, prints progress updates and model details. seed : int, optional Seed for random number generation. Set this value to ensure that the same model is created every time. batch_size : int, optional If you are getting memory errors, try decreasing this value. If you have a powerful computer, increasing this value may improve performance. Returns ------- out : ImageClassifier A trained :class:`ImageClassifier` model. Examples -------- .. sourcecode:: python >>> model = turicreate.image_classifier.create(data, target='is_expensive') # Make predictions (in various forms) >>> predictions = model.predict(data) # predictions >>> predictions = model.classify(data) # predictions with confidence >>> predictions = model.predict_topk(data) # Top-5 predictions (multiclass) # Evaluate the model with ground truth data >>> results = model.evaluate(data) See Also -------- ImageClassifier """ start_time = _time.time() # Check model parameter allowed_models = list(_pre_trained_models.MODELS.keys()) if _mac_ver() >= (10,14): allowed_models.append('VisionFeaturePrint_Scene') # Also, to make sure existing code doesn't break, replace incorrect name # with the correct name version if model == "VisionFeaturePrint_Screen": print("WARNING: Correct spelling of model name is VisionFeaturePrint_Scene; VisionFeaturePrint_Screen will be removed in subsequent versions.") model = "VisionFeaturePrint_Scene" _tkutl._check_categorical_option_type('model', model, allowed_models) # Check dataset parameter if len(dataset) == 0: raise _ToolkitError('Unable to train on empty dataset') if (feature is not None) and (feature not in dataset.column_names()): raise _ToolkitError("Image feature column '%s' does not exist" % feature) if target not in dataset.column_names(): raise _ToolkitError("Target column '%s' does not exist" % target) if(batch_size < 1): raise ValueError("'batch_size' must be greater than or equal to 1") if not (isinstance(validation_set, _tc.SFrame) or validation_set == 'auto' or validation_set is None): raise TypeError("Unrecognized value for 'validation_set'.") if feature is None: feature = _tkutl._find_only_image_column(dataset) feature_extractor = _image_feature_extractor._create_feature_extractor(model) # Extract features extracted_features = _tc.SFrame({ target: dataset[target], '__image_features__': feature_extractor.extract_features(dataset, feature, verbose=verbose, batch_size=batch_size), }) if isinstance(validation_set, _tc.SFrame): extracted_features_validation = _tc.SFrame({ target: validation_set[target], '__image_features__': feature_extractor.extract_features(validation_set, feature, verbose=verbose, batch_size=batch_size), }) else: extracted_features_validation = validation_set # Train a classifier using the extracted features extracted_features[target] = dataset[target] lr_model = _tc.logistic_classifier.create(extracted_features, features=['__image_features__'], target=target, max_iterations=max_iterations, validation_set=extracted_features_validation, seed=seed, verbose=verbose, l2_penalty=l2_penalty, l1_penalty=l1_penalty, solver=solver, feature_rescaling=feature_rescaling, convergence_threshold=convergence_threshold, step_size=step_size, lbfgs_memory_level=lbfgs_memory_level, class_weights=class_weights) # set input image shape if model in _pre_trained_models.MODELS: input_image_shape = _pre_trained_models.MODELS[model].input_image_shape else: # model == VisionFeaturePrint_Scene input_image_shape = (3, 299, 299) # Save the model state = { 'classifier': lr_model, 'model': model, 'max_iterations': max_iterations, 'feature_extractor': feature_extractor, 'input_image_shape': input_image_shape, 'target': target, 'feature': feature, 'num_features': 1, 'num_classes': lr_model.num_classes, 'classes': lr_model.classes, 'num_examples': lr_model.num_examples, 'training_time': _time.time() - start_time, 'training_loss': lr_model.training_loss, } return ImageClassifier(state)
[ "def", "create", "(", "dataset", ",", "target", ",", "feature", "=", "None", ",", "model", "=", "'resnet-50'", ",", "l2_penalty", "=", "0.01", ",", "l1_penalty", "=", "0.0", ",", "solver", "=", "'auto'", ",", "feature_rescaling", "=", "True", ",", "convergence_threshold", "=", "_DEFAULT_SOLVER_OPTIONS", "[", "'convergence_threshold'", "]", ",", "step_size", "=", "_DEFAULT_SOLVER_OPTIONS", "[", "'step_size'", "]", ",", "lbfgs_memory_level", "=", "_DEFAULT_SOLVER_OPTIONS", "[", "'lbfgs_memory_level'", "]", ",", "max_iterations", "=", "_DEFAULT_SOLVER_OPTIONS", "[", "'max_iterations'", "]", ",", "class_weights", "=", "None", ",", "validation_set", "=", "'auto'", ",", "verbose", "=", "True", ",", "seed", "=", "None", ",", "batch_size", "=", "64", ")", ":", "start_time", "=", "_time", ".", "time", "(", ")", "# Check model parameter", "allowed_models", "=", "list", "(", "_pre_trained_models", ".", "MODELS", ".", "keys", "(", ")", ")", "if", "_mac_ver", "(", ")", ">=", "(", "10", ",", "14", ")", ":", "allowed_models", ".", "append", "(", "'VisionFeaturePrint_Scene'", ")", "# Also, to make sure existing code doesn't break, replace incorrect name", "# with the correct name version", "if", "model", "==", "\"VisionFeaturePrint_Screen\"", ":", "print", "(", "\"WARNING: Correct spelling of model name is VisionFeaturePrint_Scene; VisionFeaturePrint_Screen will be removed in subsequent versions.\"", ")", "model", "=", "\"VisionFeaturePrint_Scene\"", "_tkutl", ".", "_check_categorical_option_type", "(", "'model'", ",", "model", ",", "allowed_models", ")", "# Check dataset parameter", "if", "len", "(", "dataset", ")", "==", "0", ":", "raise", "_ToolkitError", "(", "'Unable to train on empty dataset'", ")", "if", "(", "feature", "is", "not", "None", ")", "and", "(", "feature", "not", "in", "dataset", ".", "column_names", "(", ")", ")", ":", "raise", "_ToolkitError", "(", "\"Image feature column '%s' does not exist\"", "%", "feature", ")", "if", "target", "not", "in", "dataset", ".", "column_names", "(", ")", ":", "raise", "_ToolkitError", "(", "\"Target column '%s' does not exist\"", "%", "target", ")", "if", "(", "batch_size", "<", "1", ")", ":", "raise", "ValueError", "(", "\"'batch_size' must be greater than or equal to 1\"", ")", "if", "not", "(", "isinstance", "(", "validation_set", ",", "_tc", ".", "SFrame", ")", "or", "validation_set", "==", "'auto'", "or", "validation_set", "is", "None", ")", ":", "raise", "TypeError", "(", "\"Unrecognized value for 'validation_set'.\"", ")", "if", "feature", "is", "None", ":", "feature", "=", "_tkutl", ".", "_find_only_image_column", "(", "dataset", ")", "feature_extractor", "=", "_image_feature_extractor", ".", "_create_feature_extractor", "(", "model", ")", "# Extract features", "extracted_features", "=", "_tc", ".", "SFrame", "(", "{", "target", ":", "dataset", "[", "target", "]", ",", "'__image_features__'", ":", "feature_extractor", ".", "extract_features", "(", "dataset", ",", "feature", ",", "verbose", "=", "verbose", ",", "batch_size", "=", "batch_size", ")", ",", "}", ")", "if", "isinstance", "(", "validation_set", ",", "_tc", ".", "SFrame", ")", ":", "extracted_features_validation", "=", "_tc", ".", "SFrame", "(", "{", "target", ":", "validation_set", "[", "target", "]", ",", "'__image_features__'", ":", "feature_extractor", ".", "extract_features", "(", "validation_set", ",", "feature", ",", "verbose", "=", "verbose", ",", "batch_size", "=", "batch_size", ")", ",", "}", ")", "else", ":", "extracted_features_validation", "=", "validation_set", "# Train a classifier using the extracted features", "extracted_features", "[", "target", "]", "=", "dataset", "[", "target", "]", "lr_model", "=", "_tc", ".", "logistic_classifier", ".", "create", "(", "extracted_features", ",", "features", "=", "[", "'__image_features__'", "]", ",", "target", "=", "target", ",", "max_iterations", "=", "max_iterations", ",", "validation_set", "=", "extracted_features_validation", ",", "seed", "=", "seed", ",", "verbose", "=", "verbose", ",", "l2_penalty", "=", "l2_penalty", ",", "l1_penalty", "=", "l1_penalty", ",", "solver", "=", "solver", ",", "feature_rescaling", "=", "feature_rescaling", ",", "convergence_threshold", "=", "convergence_threshold", ",", "step_size", "=", "step_size", ",", "lbfgs_memory_level", "=", "lbfgs_memory_level", ",", "class_weights", "=", "class_weights", ")", "# set input image shape", "if", "model", "in", "_pre_trained_models", ".", "MODELS", ":", "input_image_shape", "=", "_pre_trained_models", ".", "MODELS", "[", "model", "]", ".", "input_image_shape", "else", ":", "# model == VisionFeaturePrint_Scene", "input_image_shape", "=", "(", "3", ",", "299", ",", "299", ")", "# Save the model", "state", "=", "{", "'classifier'", ":", "lr_model", ",", "'model'", ":", "model", ",", "'max_iterations'", ":", "max_iterations", ",", "'feature_extractor'", ":", "feature_extractor", ",", "'input_image_shape'", ":", "input_image_shape", ",", "'target'", ":", "target", ",", "'feature'", ":", "feature", ",", "'num_features'", ":", "1", ",", "'num_classes'", ":", "lr_model", ".", "num_classes", ",", "'classes'", ":", "lr_model", ".", "classes", ",", "'num_examples'", ":", "lr_model", ".", "num_examples", ",", "'training_time'", ":", "_time", ".", "time", "(", ")", "-", "start_time", ",", "'training_loss'", ":", "lr_model", ".", "training_loss", ",", "}", "return", "ImageClassifier", "(", "state", ")" ]
Create a :class:`ImageClassifier` model. Parameters ---------- dataset : SFrame Input data. The column named by the 'feature' parameter will be extracted for modeling. target : string, or int Name of the column containing the target variable. The values in this column must be of string or integer type. String target variables are automatically mapped to integers in the order in which they are provided. For example, a target variable with 'cat' and 'dog' as possible values is mapped to 0 and 1 respectively with 0 being the base class and 1 being the reference class. Use `model.classes` to retrieve the order in which the classes are mapped. feature : string, optional indicates that the SFrame has only column of Image type and that will Name of the column containing the input images. 'None' (the default) indicates the only image column in `dataset` should be used as the feature. l2_penalty : float, optional Weight on l2 regularization of the model. The larger this weight, the more the model coefficients shrink toward 0. This introduces bias into the model but decreases variance, potentially leading to better predictions. The default value is 0.01; setting this parameter to 0 corresponds to unregularized logistic regression. See the ridge regression reference for more detail. l1_penalty : float, optional Weight on l1 regularization of the model. Like the l2 penalty, the higher the l1 penalty, the more the estimated coefficients shrink toward 0. The l1 penalty, however, completely zeros out sufficiently small coefficients, automatically indicating features that are not useful for the model. The default weight of 0 prevents any features from being discarded. See the LASSO regression reference for more detail. solver : string, optional Name of the solver to be used to solve the regression. See the references for more detail on each solver. Available solvers are: - *auto (default)*: automatically chooses the best solver for the data and model parameters. - *newton*: Newton-Raphson - *lbfgs*: limited memory BFGS - *fista*: accelerated gradient descent For this model, the Newton-Raphson method is equivalent to the iteratively re-weighted least squares algorithm. If the l1_penalty is greater than 0, use the 'fista' solver. The model is trained using a carefully engineered collection of methods that are automatically picked based on the input data. The ``newton`` method works best for datasets with plenty of examples and few features (long datasets). Limited memory BFGS (``lbfgs``) is a robust solver for wide datasets (i.e datasets with many coefficients). ``fista`` is the default solver for l1-regularized linear regression. The solvers are all automatically tuned and the default options should function well. See the solver options guide for setting additional parameters for each of the solvers. See the user guide for additional details on how the solver is chosen. (see `here <https://apple.github.io/turicreate/docs/userguide/supervised-learning/linear-regression.html>`_) feature_rescaling : boolean, optional Feature rescaling is an important pre-processing step that ensures that all features are on the same scale. An l2-norm rescaling is performed to make sure that all features are of the same norm. Categorical features are also rescaled by rescaling the dummy variables that are used to represent them. The coefficients are returned in original scale of the problem. This process is particularly useful when features vary widely in their ranges. convergence_threshold : float, optional Convergence is tested using variation in the training objective. The variation in the training objective is calculated using the difference between the objective values between two steps. Consider reducing this below the default value (0.01) for a more accurately trained model. Beware of overfitting (i.e a model that works well only on the training data) if this parameter is set to a very low value. lbfgs_memory_level : float, optional The L-BFGS algorithm keeps track of gradient information from the previous ``lbfgs_memory_level`` iterations. The storage requirement for each of these gradients is the ``num_coefficients`` in the problem. Increasing the ``lbfgs_memory_level ``can help improve the quality of the model trained. Setting this to more than ``max_iterations`` has the same effect as setting it to ``max_iterations``. model : string optional Uses a pretrained model to bootstrap an image classifier: - "resnet-50" : Uses a pretrained resnet model. Exported Core ML model will be ~90M. - "squeezenet_v1.1" : Uses a pretrained squeezenet model. Exported Core ML model will be ~4.7M. - "VisionFeaturePrint_Scene": Uses an OS internal feature extractor. Only on available on iOS 12.0+, macOS 10.14+ and tvOS 12.0+. Exported Core ML model will be ~41K. Models are downloaded from the internet if not available locally. Once downloaded, the models are cached for future use. step_size : float, optional The starting step size to use for the ``fista`` solver. The default is set to 1.0, this is an aggressive setting. If the first iteration takes a considerable amount of time, reducing this parameter may speed up model training. class_weights : {dict, `auto`}, optional Weights the examples in the training data according to the given class weights. If set to `None`, all classes are supposed to have weight one. The `auto` mode set the class weight to be inversely proportional to number of examples in the training data with the given class. validation_set : SFrame, optional A dataset for monitoring the model's generalization performance. The format of this SFrame must be the same as the training set. By default this argument is set to 'auto' and a validation set is automatically sampled and used for progress printing. If validation_set is set to None, then no additional metrics are computed. The default value is 'auto'. max_iterations : int, optional The maximum number of allowed passes through the data. More passes over the data can result in a more accurately trained model. Consider increasing this (the default value is 10) if the training accuracy is low and the *Grad-Norm* in the display is large. verbose : bool, optional If True, prints progress updates and model details. seed : int, optional Seed for random number generation. Set this value to ensure that the same model is created every time. batch_size : int, optional If you are getting memory errors, try decreasing this value. If you have a powerful computer, increasing this value may improve performance. Returns ------- out : ImageClassifier A trained :class:`ImageClassifier` model. Examples -------- .. sourcecode:: python >>> model = turicreate.image_classifier.create(data, target='is_expensive') # Make predictions (in various forms) >>> predictions = model.predict(data) # predictions >>> predictions = model.classify(data) # predictions with confidence >>> predictions = model.predict_topk(data) # Top-5 predictions (multiclass) # Evaluate the model with ground truth data >>> results = model.evaluate(data) See Also -------- ImageClassifier
[ "Create", "a", ":", "class", ":", "ImageClassifier", "model", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/image_classifier/image_classifier.py#L38-L307
train
apple/turicreate
src/unity/python/turicreate/toolkits/image_classifier/image_classifier.py
ImageClassifier._get_native_state
def _get_native_state(self): """ Save the model as a dictionary, which can be loaded with the :py:func:`~turicreate.load_model` method. """ state = self.__proxy__.get_state() state['classifier'] = state['classifier'].__proxy__ del state['feature_extractor'] del state['classes'] return state
python
def _get_native_state(self): """ Save the model as a dictionary, which can be loaded with the :py:func:`~turicreate.load_model` method. """ state = self.__proxy__.get_state() state['classifier'] = state['classifier'].__proxy__ del state['feature_extractor'] del state['classes'] return state
[ "def", "_get_native_state", "(", "self", ")", ":", "state", "=", "self", ".", "__proxy__", ".", "get_state", "(", ")", "state", "[", "'classifier'", "]", "=", "state", "[", "'classifier'", "]", ".", "__proxy__", "del", "state", "[", "'feature_extractor'", "]", "del", "state", "[", "'classes'", "]", "return", "state" ]
Save the model as a dictionary, which can be loaded with the :py:func:`~turicreate.load_model` method.
[ "Save", "the", "model", "as", "a", "dictionary", "which", "can", "be", "loaded", "with", "the", ":", "py", ":", "func", ":", "~turicreate", ".", "load_model", "method", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/image_classifier/image_classifier.py#L329-L338
train
apple/turicreate
src/unity/python/turicreate/toolkits/image_classifier/image_classifier.py
ImageClassifier._load_version
def _load_version(cls, state, version): """ A function to load a previously saved ImageClassifier instance. """ _tkutl._model_version_check(version, cls._PYTHON_IMAGE_CLASSIFIER_VERSION) from turicreate.toolkits.classifier.logistic_classifier import LogisticClassifier state['classifier'] = LogisticClassifier(state['classifier']) state['classes'] = state['classifier'].classes # Correct models saved with a previous typo if state['model'] == "VisionFeaturePrint_Screen": state['model'] = "VisionFeaturePrint_Scene" # Load pre-trained model & feature extractor model_name = state['model'] if model_name == "VisionFeaturePrint_Scene" and _mac_ver() < (10,14): raise ToolkitError("Can not load model on this operating system. This model uses VisionFeaturePrint_Scene, " "which is only supported on macOS 10.14 and higher.") state['feature_extractor'] = _image_feature_extractor._create_feature_extractor(model_name) state['input_image_shape'] = tuple([int(i) for i in state['input_image_shape']]) return ImageClassifier(state)
python
def _load_version(cls, state, version): """ A function to load a previously saved ImageClassifier instance. """ _tkutl._model_version_check(version, cls._PYTHON_IMAGE_CLASSIFIER_VERSION) from turicreate.toolkits.classifier.logistic_classifier import LogisticClassifier state['classifier'] = LogisticClassifier(state['classifier']) state['classes'] = state['classifier'].classes # Correct models saved with a previous typo if state['model'] == "VisionFeaturePrint_Screen": state['model'] = "VisionFeaturePrint_Scene" # Load pre-trained model & feature extractor model_name = state['model'] if model_name == "VisionFeaturePrint_Scene" and _mac_ver() < (10,14): raise ToolkitError("Can not load model on this operating system. This model uses VisionFeaturePrint_Scene, " "which is only supported on macOS 10.14 and higher.") state['feature_extractor'] = _image_feature_extractor._create_feature_extractor(model_name) state['input_image_shape'] = tuple([int(i) for i in state['input_image_shape']]) return ImageClassifier(state)
[ "def", "_load_version", "(", "cls", ",", "state", ",", "version", ")", ":", "_tkutl", ".", "_model_version_check", "(", "version", ",", "cls", ".", "_PYTHON_IMAGE_CLASSIFIER_VERSION", ")", "from", "turicreate", ".", "toolkits", ".", "classifier", ".", "logistic_classifier", "import", "LogisticClassifier", "state", "[", "'classifier'", "]", "=", "LogisticClassifier", "(", "state", "[", "'classifier'", "]", ")", "state", "[", "'classes'", "]", "=", "state", "[", "'classifier'", "]", ".", "classes", "# Correct models saved with a previous typo", "if", "state", "[", "'model'", "]", "==", "\"VisionFeaturePrint_Screen\"", ":", "state", "[", "'model'", "]", "=", "\"VisionFeaturePrint_Scene\"", "# Load pre-trained model & feature extractor", "model_name", "=", "state", "[", "'model'", "]", "if", "model_name", "==", "\"VisionFeaturePrint_Scene\"", "and", "_mac_ver", "(", ")", "<", "(", "10", ",", "14", ")", ":", "raise", "ToolkitError", "(", "\"Can not load model on this operating system. This model uses VisionFeaturePrint_Scene, \"", "\"which is only supported on macOS 10.14 and higher.\"", ")", "state", "[", "'feature_extractor'", "]", "=", "_image_feature_extractor", ".", "_create_feature_extractor", "(", "model_name", ")", "state", "[", "'input_image_shape'", "]", "=", "tuple", "(", "[", "int", "(", "i", ")", "for", "i", "in", "state", "[", "'input_image_shape'", "]", "]", ")", "return", "ImageClassifier", "(", "state", ")" ]
A function to load a previously saved ImageClassifier instance.
[ "A", "function", "to", "load", "a", "previously", "saved", "ImageClassifier", "instance", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/image_classifier/image_classifier.py#L341-L362
train
apple/turicreate
src/unity/python/turicreate/toolkits/image_classifier/image_classifier.py
ImageClassifier.predict
def predict(self, dataset, output_type='class', batch_size=64): """ Return predictions for ``dataset``, using the trained logistic regression model. Predictions can be generated as class labels, probabilities that the target value is True, or margins (i.e. the distance of the observations from the hyperplane separating the classes). `probability_vector` returns a vector of probabilities by each class. For each new example in ``dataset``, the margin---also known as the linear predictor---is the inner product of the example and the model coefficients. The probability is obtained by passing the margin through the logistic function. Predicted classes are obtained by thresholding the predicted probabilities at 0.5. If you would like to threshold predictions at a different probability level, you can use the Turi Create evaluation toolkit. Parameters ---------- dataset : SFrame | SArray | turicreate.Image The images to be classified. If dataset is an SFrame, it must have columns with the same names as the features used for model training, but does not require a target column. Additional columns are ignored. output_type : {'probability', 'margin', 'class', 'probability_vector'}, optional Form of the predictions which are one of: - 'probability': Prediction probability associated with the True class (not applicable for multi-class classification) - 'probability_vector': Prediction probability associated with each class as a vector. The probability of the first class (sorted alphanumerically by name of the class in the training set) is in position 0 of the vector, the second in position 1 and so on. - 'class': Class prediction. For multi-class classification, this returns the class with maximum probability. batch_size : int, optional If you are getting memory errors, try decreasing this value. If you have a powerful computer, increasing this value may improve performance. Returns ------- out : SArray An SArray with model predictions. If `dataset` is a single image, the return value will be a single prediction. See Also ---------- create, evaluate, classify Examples ---------- >>> probability_predictions = model.predict(data, output_type='probability') >>> margin_predictions = model.predict(data, output_type='margin') >>> class_predictions = model.predict(data, output_type='class') """ if not isinstance(dataset, (_tc.SFrame, _tc.SArray, _tc.Image)): raise TypeError('dataset must be either an SFrame, SArray or turicreate.Image') if(batch_size < 1): raise ValueError("'batch_size' must be greater than or equal to 1") dataset, unpack = self._canonize_input(dataset) extracted_features = self._extract_features(dataset, batch_size=batch_size) return unpack(self.classifier.predict(extracted_features, output_type=output_type))
python
def predict(self, dataset, output_type='class', batch_size=64): """ Return predictions for ``dataset``, using the trained logistic regression model. Predictions can be generated as class labels, probabilities that the target value is True, or margins (i.e. the distance of the observations from the hyperplane separating the classes). `probability_vector` returns a vector of probabilities by each class. For each new example in ``dataset``, the margin---also known as the linear predictor---is the inner product of the example and the model coefficients. The probability is obtained by passing the margin through the logistic function. Predicted classes are obtained by thresholding the predicted probabilities at 0.5. If you would like to threshold predictions at a different probability level, you can use the Turi Create evaluation toolkit. Parameters ---------- dataset : SFrame | SArray | turicreate.Image The images to be classified. If dataset is an SFrame, it must have columns with the same names as the features used for model training, but does not require a target column. Additional columns are ignored. output_type : {'probability', 'margin', 'class', 'probability_vector'}, optional Form of the predictions which are one of: - 'probability': Prediction probability associated with the True class (not applicable for multi-class classification) - 'probability_vector': Prediction probability associated with each class as a vector. The probability of the first class (sorted alphanumerically by name of the class in the training set) is in position 0 of the vector, the second in position 1 and so on. - 'class': Class prediction. For multi-class classification, this returns the class with maximum probability. batch_size : int, optional If you are getting memory errors, try decreasing this value. If you have a powerful computer, increasing this value may improve performance. Returns ------- out : SArray An SArray with model predictions. If `dataset` is a single image, the return value will be a single prediction. See Also ---------- create, evaluate, classify Examples ---------- >>> probability_predictions = model.predict(data, output_type='probability') >>> margin_predictions = model.predict(data, output_type='margin') >>> class_predictions = model.predict(data, output_type='class') """ if not isinstance(dataset, (_tc.SFrame, _tc.SArray, _tc.Image)): raise TypeError('dataset must be either an SFrame, SArray or turicreate.Image') if(batch_size < 1): raise ValueError("'batch_size' must be greater than or equal to 1") dataset, unpack = self._canonize_input(dataset) extracted_features = self._extract_features(dataset, batch_size=batch_size) return unpack(self.classifier.predict(extracted_features, output_type=output_type))
[ "def", "predict", "(", "self", ",", "dataset", ",", "output_type", "=", "'class'", ",", "batch_size", "=", "64", ")", ":", "if", "not", "isinstance", "(", "dataset", ",", "(", "_tc", ".", "SFrame", ",", "_tc", ".", "SArray", ",", "_tc", ".", "Image", ")", ")", ":", "raise", "TypeError", "(", "'dataset must be either an SFrame, SArray or turicreate.Image'", ")", "if", "(", "batch_size", "<", "1", ")", ":", "raise", "ValueError", "(", "\"'batch_size' must be greater than or equal to 1\"", ")", "dataset", ",", "unpack", "=", "self", ".", "_canonize_input", "(", "dataset", ")", "extracted_features", "=", "self", ".", "_extract_features", "(", "dataset", ",", "batch_size", "=", "batch_size", ")", "return", "unpack", "(", "self", ".", "classifier", ".", "predict", "(", "extracted_features", ",", "output_type", "=", "output_type", ")", ")" ]
Return predictions for ``dataset``, using the trained logistic regression model. Predictions can be generated as class labels, probabilities that the target value is True, or margins (i.e. the distance of the observations from the hyperplane separating the classes). `probability_vector` returns a vector of probabilities by each class. For each new example in ``dataset``, the margin---also known as the linear predictor---is the inner product of the example and the model coefficients. The probability is obtained by passing the margin through the logistic function. Predicted classes are obtained by thresholding the predicted probabilities at 0.5. If you would like to threshold predictions at a different probability level, you can use the Turi Create evaluation toolkit. Parameters ---------- dataset : SFrame | SArray | turicreate.Image The images to be classified. If dataset is an SFrame, it must have columns with the same names as the features used for model training, but does not require a target column. Additional columns are ignored. output_type : {'probability', 'margin', 'class', 'probability_vector'}, optional Form of the predictions which are one of: - 'probability': Prediction probability associated with the True class (not applicable for multi-class classification) - 'probability_vector': Prediction probability associated with each class as a vector. The probability of the first class (sorted alphanumerically by name of the class in the training set) is in position 0 of the vector, the second in position 1 and so on. - 'class': Class prediction. For multi-class classification, this returns the class with maximum probability. batch_size : int, optional If you are getting memory errors, try decreasing this value. If you have a powerful computer, increasing this value may improve performance. Returns ------- out : SArray An SArray with model predictions. If `dataset` is a single image, the return value will be a single prediction. See Also ---------- create, evaluate, classify Examples ---------- >>> probability_predictions = model.predict(data, output_type='probability') >>> margin_predictions = model.predict(data, output_type='margin') >>> class_predictions = model.predict(data, output_type='class')
[ "Return", "predictions", "for", "dataset", "using", "the", "trained", "logistic", "regression", "model", ".", "Predictions", "can", "be", "generated", "as", "class", "labels", "probabilities", "that", "the", "target", "value", "is", "True", "or", "margins", "(", "i", ".", "e", ".", "the", "distance", "of", "the", "observations", "from", "the", "hyperplane", "separating", "the", "classes", ")", ".", "probability_vector", "returns", "a", "vector", "of", "probabilities", "by", "each", "class", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/image_classifier/image_classifier.py#L433-L499
train
apple/turicreate
src/unity/python/turicreate/toolkits/image_classifier/image_classifier.py
ImageClassifier.predict_topk
def predict_topk(self, dataset, output_type="probability", k=3, batch_size=64): """ Return top-k predictions for the ``dataset``, using the trained model. Predictions are returned as an SFrame with three columns: `id`, `class`, and `probability`, `margin`, or `rank`, depending on the ``output_type`` parameter. Input dataset size must be the same as for training of the model. Parameters ---------- dataset : SFrame | SArray | turicreate.Image Images to be classified. If dataset is an SFrame, it must include columns with the same names as the features used for model training, but does not require a target column. Additional columns are ignored. output_type : {'probability', 'rank', 'margin'}, optional Choose the return type of the prediction: - `probability`: Probability associated with each label in the prediction. - `rank` : Rank associated with each label in the prediction. - `margin` : Margin associated with each label in the prediction. k : int, optional Number of classes to return for each input example. Returns ------- out : SFrame An SFrame with model predictions. See Also -------- predict, classify, evaluate Examples -------- >>> pred = m.predict_topk(validation_data, k=3) >>> pred +----+-------+-------------------+ | id | class | probability | +----+-------+-------------------+ | 0 | 4 | 0.995623886585 | | 0 | 9 | 0.0038311756216 | | 0 | 7 | 0.000301006948575 | | 1 | 1 | 0.928708016872 | | 1 | 3 | 0.0440889261663 | | 1 | 2 | 0.0176190119237 | | 2 | 3 | 0.996967732906 | | 2 | 2 | 0.00151345680933 | | 2 | 7 | 0.000637513934635 | | 3 | 1 | 0.998070061207 | | .. | ... | ... | +----+-------+-------------------+ [35688 rows x 3 columns] """ if not isinstance(dataset, (_tc.SFrame, _tc.SArray, _tc.Image)): raise TypeError('dataset must be either an SFrame, SArray or turicreate.Image') if(batch_size < 1): raise ValueError("'batch_size' must be greater than or equal to 1") dataset, _ = self._canonize_input(dataset) extracted_features = self._extract_features(dataset) return self.classifier.predict_topk(extracted_features, output_type = output_type, k = k)
python
def predict_topk(self, dataset, output_type="probability", k=3, batch_size=64): """ Return top-k predictions for the ``dataset``, using the trained model. Predictions are returned as an SFrame with three columns: `id`, `class`, and `probability`, `margin`, or `rank`, depending on the ``output_type`` parameter. Input dataset size must be the same as for training of the model. Parameters ---------- dataset : SFrame | SArray | turicreate.Image Images to be classified. If dataset is an SFrame, it must include columns with the same names as the features used for model training, but does not require a target column. Additional columns are ignored. output_type : {'probability', 'rank', 'margin'}, optional Choose the return type of the prediction: - `probability`: Probability associated with each label in the prediction. - `rank` : Rank associated with each label in the prediction. - `margin` : Margin associated with each label in the prediction. k : int, optional Number of classes to return for each input example. Returns ------- out : SFrame An SFrame with model predictions. See Also -------- predict, classify, evaluate Examples -------- >>> pred = m.predict_topk(validation_data, k=3) >>> pred +----+-------+-------------------+ | id | class | probability | +----+-------+-------------------+ | 0 | 4 | 0.995623886585 | | 0 | 9 | 0.0038311756216 | | 0 | 7 | 0.000301006948575 | | 1 | 1 | 0.928708016872 | | 1 | 3 | 0.0440889261663 | | 1 | 2 | 0.0176190119237 | | 2 | 3 | 0.996967732906 | | 2 | 2 | 0.00151345680933 | | 2 | 7 | 0.000637513934635 | | 3 | 1 | 0.998070061207 | | .. | ... | ... | +----+-------+-------------------+ [35688 rows x 3 columns] """ if not isinstance(dataset, (_tc.SFrame, _tc.SArray, _tc.Image)): raise TypeError('dataset must be either an SFrame, SArray or turicreate.Image') if(batch_size < 1): raise ValueError("'batch_size' must be greater than or equal to 1") dataset, _ = self._canonize_input(dataset) extracted_features = self._extract_features(dataset) return self.classifier.predict_topk(extracted_features, output_type = output_type, k = k)
[ "def", "predict_topk", "(", "self", ",", "dataset", ",", "output_type", "=", "\"probability\"", ",", "k", "=", "3", ",", "batch_size", "=", "64", ")", ":", "if", "not", "isinstance", "(", "dataset", ",", "(", "_tc", ".", "SFrame", ",", "_tc", ".", "SArray", ",", "_tc", ".", "Image", ")", ")", ":", "raise", "TypeError", "(", "'dataset must be either an SFrame, SArray or turicreate.Image'", ")", "if", "(", "batch_size", "<", "1", ")", ":", "raise", "ValueError", "(", "\"'batch_size' must be greater than or equal to 1\"", ")", "dataset", ",", "_", "=", "self", ".", "_canonize_input", "(", "dataset", ")", "extracted_features", "=", "self", ".", "_extract_features", "(", "dataset", ")", "return", "self", ".", "classifier", ".", "predict_topk", "(", "extracted_features", ",", "output_type", "=", "output_type", ",", "k", "=", "k", ")" ]
Return top-k predictions for the ``dataset``, using the trained model. Predictions are returned as an SFrame with three columns: `id`, `class`, and `probability`, `margin`, or `rank`, depending on the ``output_type`` parameter. Input dataset size must be the same as for training of the model. Parameters ---------- dataset : SFrame | SArray | turicreate.Image Images to be classified. If dataset is an SFrame, it must include columns with the same names as the features used for model training, but does not require a target column. Additional columns are ignored. output_type : {'probability', 'rank', 'margin'}, optional Choose the return type of the prediction: - `probability`: Probability associated with each label in the prediction. - `rank` : Rank associated with each label in the prediction. - `margin` : Margin associated with each label in the prediction. k : int, optional Number of classes to return for each input example. Returns ------- out : SFrame An SFrame with model predictions. See Also -------- predict, classify, evaluate Examples -------- >>> pred = m.predict_topk(validation_data, k=3) >>> pred +----+-------+-------------------+ | id | class | probability | +----+-------+-------------------+ | 0 | 4 | 0.995623886585 | | 0 | 9 | 0.0038311756216 | | 0 | 7 | 0.000301006948575 | | 1 | 1 | 0.928708016872 | | 1 | 3 | 0.0440889261663 | | 1 | 2 | 0.0176190119237 | | 2 | 3 | 0.996967732906 | | 2 | 2 | 0.00151345680933 | | 2 | 7 | 0.000637513934635 | | 3 | 1 | 0.998070061207 | | .. | ... | ... | +----+-------+-------------------+ [35688 rows x 3 columns]
[ "Return", "top", "-", "k", "predictions", "for", "the", "dataset", "using", "the", "trained", "model", ".", "Predictions", "are", "returned", "as", "an", "SFrame", "with", "three", "columns", ":", "id", "class", "and", "probability", "margin", "or", "rank", "depending", "on", "the", "output_type", "parameter", ".", "Input", "dataset", "size", "must", "be", "the", "same", "as", "for", "training", "of", "the", "model", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/image_classifier/image_classifier.py#L546-L609
train
apple/turicreate
src/unity/python/turicreate/toolkits/image_classifier/image_classifier.py
ImageClassifier.evaluate
def evaluate(self, dataset, metric='auto', verbose=True, batch_size=64): """ Evaluate the model by making predictions of target values and comparing these to actual values. Parameters ---------- dataset : SFrame Dataset of new observations. Must include columns with the same names as the target and features used for model training. Additional columns are ignored. metric : str, optional Name of the evaluation metric. Possible values are: - 'auto' : Returns all available metrics. - 'accuracy' : Classification accuracy (micro average). - 'auc' : Area under the ROC curve (macro average) - 'precision' : Precision score (macro average) - 'recall' : Recall score (macro average) - 'f1_score' : F1 score (macro average) - 'log_loss' : Log loss - 'confusion_matrix' : An SFrame with counts of possible prediction/true label combinations. - 'roc_curve' : An SFrame containing information needed for an ROC curve For more flexibility in calculating evaluation metrics, use the :class:`~turicreate.evaluation` module. verbose : bool, optional If True, prints progress updates and model details. batch_size : int, optional If you are getting memory errors, try decreasing this value. If you have a powerful computer, increasing this value may improve performance. Returns ------- out : dict Dictionary of evaluation results where the key is the name of the evaluation metric (e.g. `accuracy`) and the value is the evaluation score. See Also ---------- create, predict, classify Examples ---------- .. sourcecode:: python >>> results = model.evaluate(data) >>> print results['accuracy'] """ import os, json, math if(batch_size < 1): raise ValueError("'batch_size' must be greater than or equal to 1") extracted_features = self._extract_features(dataset, verbose=verbose, batch_size=batch_size) extracted_features[self.target] = dataset[self.target] metrics = self.classifier.evaluate(extracted_features, metric=metric, with_predictions=True) predictions = metrics["predictions"]["probs"] state = self.__proxy__.get_state() labels = state["classes"] def entropy(probs): return _reduce(lambda x, y: x + (y*math.log(1/y, 2) if y > 0 else 0) , probs, 0) / math.log(len(probs),2) def confidence(probs): return max(probs) def relative_confidence(probs): lp = len(probs) return probs[lp-1] - probs[lp-2] def get_confusion_matrix(extended_test, labels): #Init a matrix sf_confusion_matrix = {'label':[], 'predicted_label':[], 'prob_default':[]} for target_l in labels: for predicted_l in labels: sf_confusion_matrix['label'].append(target_l) sf_confusion_matrix['predicted_label'].append(predicted_l) sf_confusion_matrix['prob_default'].append(0) sf_confusion_matrix = _tc.SFrame(sf_confusion_matrix) sf_confusion_matrix = sf_confusion_matrix.join(extended_test.groupby(['label', 'predicted_label'], {'count' :_tc.aggregate.COUNT}), how='left', on=['label','predicted_label']) sf_confusion_matrix = sf_confusion_matrix.fillna('count', 0) label_column = _tc.SFrame({'label': extended_test['label']}) predictions = extended_test['probs'] for i in range(0, len(labels)): new_test_data = label_column.add_columns([predictions.apply(lambda probs: probs[i]), predictions.apply(lambda probs: labels[i])], ['prob','predicted_label']) if (i==0): test_longer_form = new_test_data else: test_longer_form = test_longer_form.append(new_test_data) if len(extended_test) is 0: sf_confusion_matrix = sf_confusion_matrix.rename({'prob_default': 'prob', 'label': 'target_label'}) else: sf_confusion_matrix = sf_confusion_matrix.join(test_longer_form.groupby(['label', 'predicted_label'], {'prob': _tc.aggregate.SUM('prob')}), how='left', on=['label', 'predicted_label']) sf_confusion_matrix = sf_confusion_matrix.rename({'label': 'target_label'}).fillna('prob', 0) def wo_divide_by_zero(a,b): if b==0: return None else: return a*1.0/b sf_confusion_matrix['norm_prob'] = sf_confusion_matrix.join(sf_confusion_matrix.groupby('target_label', {'sum_prob': _tc.aggregate.SUM('prob')}),how='left').apply(lambda x: wo_divide_by_zero(x['prob'], x['sum_prob'])) return sf_confusion_matrix.fillna('norm_prob', 0) def hclusterSort(vectors, dist_fn): distances = [] vecs = list(vectors)[:] for i in range(0, len(vecs)): for j in range(i+1, len(vecs)): distances.append({'from': vecs[i], 'to': vecs[j], 'dist': dist_fn(vecs[i], vecs[j])}) distances = sorted(distances, key=lambda d: d['dist']) excluding_names = [] while(len(distances) > 0): min_dist = distances[0] new_vec = {'name': str(min_dist['from']['name']) + '|'+ str(min_dist['to']['name']), 'members': min_dist['from'].get('members', [min_dist['from']]) + min_dist['to'].get('members',[min_dist['to']])} excluding_names = [min_dist['from']['name'], min_dist['to']['name']] vecs = filter(lambda v: v['name'] not in excluding_names, vecs) distances = filter(lambda dist: (dist['from']['name'] not in excluding_names) and (dist['to']['name'] not in excluding_names), distances) for v in vecs: total = 0 for vi in v.get('members', [v]): for vj in new_vec['members']: total += dist_fn(vi, vj) distances.append({'from': v, 'to': new_vec, 'dist': total/len(v.get('members', [v]))/len(new_vec['members'])}) vecs.append(new_vec) distances = sorted(distances, key=lambda d: d['dist']) return vecs def l2Dist(v1, v2): dist = 0 for i in range(0, len(v1['pos'])): dist += math.pow(v1['pos'][i] - v2['pos'][i], 2) return math.pow(dist, 0.5) evaluation_result = {k: metrics[k] for k in ['accuracy', 'f1_score', 'log_loss', 'precision', 'recall', 'auc']} evaluation_result['num_test_examples'] = len(dataset) for k in ['num_classes', 'num_features', 'input_image_shape', 'num_examples', 'training_loss', 'training_time', 'model', 'max_iterations']: evaluation_result[k] = getattr(self, k) # Extend the given test data extended_test = dataset.add_column(predictions, 'probs') extended_test['label'] = dataset[self.target] extended_test = extended_test.add_columns( [extended_test.apply(lambda d: labels[d['probs'].index(confidence(d['probs']))]), extended_test.apply(lambda d: entropy(d['probs'])), extended_test.apply(lambda d: confidence(d['probs'])), extended_test.apply(lambda d: relative_confidence(d['probs']))], ['predicted_label', 'entropy', 'confidence', 'relative_confidence']) extended_test = extended_test.add_column(extended_test.apply(lambda d: d['label'] == d['predicted_label']), 'correct') # Calculate the confusion matrix sf_conf_mat = get_confusion_matrix(extended_test, labels) confidence_threshold = 0.5 hesitant_threshold = 0.2 evaluation_result['confidence_threshold'] = confidence_threshold evaluation_result['hesitant_threshold'] = hesitant_threshold evaluation_result['confidence_metric_for_threshold'] = 'relative_confidence' sf_hesitant_conf_mat = get_confusion_matrix(extended_test[extended_test[evaluation_result['confidence_metric_for_threshold']] < hesitant_threshold], labels) sf_confidently_wrong_conf_mat = get_confusion_matrix(extended_test[(extended_test[evaluation_result['confidence_metric_for_threshold']] > confidence_threshold) & (extended_test['correct']==True)], labels) evaluation_result['conf_mat'] = list(sf_conf_mat) evaluation_result['hesitant_conf_mat'] = list(sf_hesitant_conf_mat) evaluation_result['confidently_wrong_conf_mat'] = list(sf_confidently_wrong_conf_mat) # Get sorted labels (sorted by hCluster) vectors = map(lambda l: {'name': l, 'pos':list(sf_conf_mat[sf_conf_mat['target_label']==l].sort('predicted_label')['norm_prob'])}, labels) evaluation_result['sorted_labels'] = hclusterSort(vectors, l2Dist)[0]['name'].split("|") # Get recall and precision per label per_l = extended_test.groupby(['label'], {'count': _tc.aggregate.COUNT, 'correct_count': _tc.aggregate.SUM('correct') }) per_l['recall'] = per_l.apply(lambda l: l['correct_count']*1.0 / l['count']) per_pl = extended_test.groupby(['predicted_label'], {'predicted_count': _tc.aggregate.COUNT, 'correct_count': _tc.aggregate.SUM('correct') }) per_pl['precision'] = per_pl.apply(lambda l: l['correct_count']*1.0 / l['predicted_count']) per_pl = per_pl.rename({'predicted_label': 'label'}) evaluation_result['label_metrics'] = list(per_l.join(per_pl, on='label', how='outer').select_columns(['label', 'count', 'correct_count', 'predicted_count', 'recall', 'precision'])) evaluation_result['labels'] = labels extended_test = extended_test.add_row_number('__idx').rename({'label': 'target_label'}) evaluation_result['test_data'] = extended_test evaluation_result['feature'] = self.feature return _Evaluation(evaluation_result)
python
def evaluate(self, dataset, metric='auto', verbose=True, batch_size=64): """ Evaluate the model by making predictions of target values and comparing these to actual values. Parameters ---------- dataset : SFrame Dataset of new observations. Must include columns with the same names as the target and features used for model training. Additional columns are ignored. metric : str, optional Name of the evaluation metric. Possible values are: - 'auto' : Returns all available metrics. - 'accuracy' : Classification accuracy (micro average). - 'auc' : Area under the ROC curve (macro average) - 'precision' : Precision score (macro average) - 'recall' : Recall score (macro average) - 'f1_score' : F1 score (macro average) - 'log_loss' : Log loss - 'confusion_matrix' : An SFrame with counts of possible prediction/true label combinations. - 'roc_curve' : An SFrame containing information needed for an ROC curve For more flexibility in calculating evaluation metrics, use the :class:`~turicreate.evaluation` module. verbose : bool, optional If True, prints progress updates and model details. batch_size : int, optional If you are getting memory errors, try decreasing this value. If you have a powerful computer, increasing this value may improve performance. Returns ------- out : dict Dictionary of evaluation results where the key is the name of the evaluation metric (e.g. `accuracy`) and the value is the evaluation score. See Also ---------- create, predict, classify Examples ---------- .. sourcecode:: python >>> results = model.evaluate(data) >>> print results['accuracy'] """ import os, json, math if(batch_size < 1): raise ValueError("'batch_size' must be greater than or equal to 1") extracted_features = self._extract_features(dataset, verbose=verbose, batch_size=batch_size) extracted_features[self.target] = dataset[self.target] metrics = self.classifier.evaluate(extracted_features, metric=metric, with_predictions=True) predictions = metrics["predictions"]["probs"] state = self.__proxy__.get_state() labels = state["classes"] def entropy(probs): return _reduce(lambda x, y: x + (y*math.log(1/y, 2) if y > 0 else 0) , probs, 0) / math.log(len(probs),2) def confidence(probs): return max(probs) def relative_confidence(probs): lp = len(probs) return probs[lp-1] - probs[lp-2] def get_confusion_matrix(extended_test, labels): #Init a matrix sf_confusion_matrix = {'label':[], 'predicted_label':[], 'prob_default':[]} for target_l in labels: for predicted_l in labels: sf_confusion_matrix['label'].append(target_l) sf_confusion_matrix['predicted_label'].append(predicted_l) sf_confusion_matrix['prob_default'].append(0) sf_confusion_matrix = _tc.SFrame(sf_confusion_matrix) sf_confusion_matrix = sf_confusion_matrix.join(extended_test.groupby(['label', 'predicted_label'], {'count' :_tc.aggregate.COUNT}), how='left', on=['label','predicted_label']) sf_confusion_matrix = sf_confusion_matrix.fillna('count', 0) label_column = _tc.SFrame({'label': extended_test['label']}) predictions = extended_test['probs'] for i in range(0, len(labels)): new_test_data = label_column.add_columns([predictions.apply(lambda probs: probs[i]), predictions.apply(lambda probs: labels[i])], ['prob','predicted_label']) if (i==0): test_longer_form = new_test_data else: test_longer_form = test_longer_form.append(new_test_data) if len(extended_test) is 0: sf_confusion_matrix = sf_confusion_matrix.rename({'prob_default': 'prob', 'label': 'target_label'}) else: sf_confusion_matrix = sf_confusion_matrix.join(test_longer_form.groupby(['label', 'predicted_label'], {'prob': _tc.aggregate.SUM('prob')}), how='left', on=['label', 'predicted_label']) sf_confusion_matrix = sf_confusion_matrix.rename({'label': 'target_label'}).fillna('prob', 0) def wo_divide_by_zero(a,b): if b==0: return None else: return a*1.0/b sf_confusion_matrix['norm_prob'] = sf_confusion_matrix.join(sf_confusion_matrix.groupby('target_label', {'sum_prob': _tc.aggregate.SUM('prob')}),how='left').apply(lambda x: wo_divide_by_zero(x['prob'], x['sum_prob'])) return sf_confusion_matrix.fillna('norm_prob', 0) def hclusterSort(vectors, dist_fn): distances = [] vecs = list(vectors)[:] for i in range(0, len(vecs)): for j in range(i+1, len(vecs)): distances.append({'from': vecs[i], 'to': vecs[j], 'dist': dist_fn(vecs[i], vecs[j])}) distances = sorted(distances, key=lambda d: d['dist']) excluding_names = [] while(len(distances) > 0): min_dist = distances[0] new_vec = {'name': str(min_dist['from']['name']) + '|'+ str(min_dist['to']['name']), 'members': min_dist['from'].get('members', [min_dist['from']]) + min_dist['to'].get('members',[min_dist['to']])} excluding_names = [min_dist['from']['name'], min_dist['to']['name']] vecs = filter(lambda v: v['name'] not in excluding_names, vecs) distances = filter(lambda dist: (dist['from']['name'] not in excluding_names) and (dist['to']['name'] not in excluding_names), distances) for v in vecs: total = 0 for vi in v.get('members', [v]): for vj in new_vec['members']: total += dist_fn(vi, vj) distances.append({'from': v, 'to': new_vec, 'dist': total/len(v.get('members', [v]))/len(new_vec['members'])}) vecs.append(new_vec) distances = sorted(distances, key=lambda d: d['dist']) return vecs def l2Dist(v1, v2): dist = 0 for i in range(0, len(v1['pos'])): dist += math.pow(v1['pos'][i] - v2['pos'][i], 2) return math.pow(dist, 0.5) evaluation_result = {k: metrics[k] for k in ['accuracy', 'f1_score', 'log_loss', 'precision', 'recall', 'auc']} evaluation_result['num_test_examples'] = len(dataset) for k in ['num_classes', 'num_features', 'input_image_shape', 'num_examples', 'training_loss', 'training_time', 'model', 'max_iterations']: evaluation_result[k] = getattr(self, k) # Extend the given test data extended_test = dataset.add_column(predictions, 'probs') extended_test['label'] = dataset[self.target] extended_test = extended_test.add_columns( [extended_test.apply(lambda d: labels[d['probs'].index(confidence(d['probs']))]), extended_test.apply(lambda d: entropy(d['probs'])), extended_test.apply(lambda d: confidence(d['probs'])), extended_test.apply(lambda d: relative_confidence(d['probs']))], ['predicted_label', 'entropy', 'confidence', 'relative_confidence']) extended_test = extended_test.add_column(extended_test.apply(lambda d: d['label'] == d['predicted_label']), 'correct') # Calculate the confusion matrix sf_conf_mat = get_confusion_matrix(extended_test, labels) confidence_threshold = 0.5 hesitant_threshold = 0.2 evaluation_result['confidence_threshold'] = confidence_threshold evaluation_result['hesitant_threshold'] = hesitant_threshold evaluation_result['confidence_metric_for_threshold'] = 'relative_confidence' sf_hesitant_conf_mat = get_confusion_matrix(extended_test[extended_test[evaluation_result['confidence_metric_for_threshold']] < hesitant_threshold], labels) sf_confidently_wrong_conf_mat = get_confusion_matrix(extended_test[(extended_test[evaluation_result['confidence_metric_for_threshold']] > confidence_threshold) & (extended_test['correct']==True)], labels) evaluation_result['conf_mat'] = list(sf_conf_mat) evaluation_result['hesitant_conf_mat'] = list(sf_hesitant_conf_mat) evaluation_result['confidently_wrong_conf_mat'] = list(sf_confidently_wrong_conf_mat) # Get sorted labels (sorted by hCluster) vectors = map(lambda l: {'name': l, 'pos':list(sf_conf_mat[sf_conf_mat['target_label']==l].sort('predicted_label')['norm_prob'])}, labels) evaluation_result['sorted_labels'] = hclusterSort(vectors, l2Dist)[0]['name'].split("|") # Get recall and precision per label per_l = extended_test.groupby(['label'], {'count': _tc.aggregate.COUNT, 'correct_count': _tc.aggregate.SUM('correct') }) per_l['recall'] = per_l.apply(lambda l: l['correct_count']*1.0 / l['count']) per_pl = extended_test.groupby(['predicted_label'], {'predicted_count': _tc.aggregate.COUNT, 'correct_count': _tc.aggregate.SUM('correct') }) per_pl['precision'] = per_pl.apply(lambda l: l['correct_count']*1.0 / l['predicted_count']) per_pl = per_pl.rename({'predicted_label': 'label'}) evaluation_result['label_metrics'] = list(per_l.join(per_pl, on='label', how='outer').select_columns(['label', 'count', 'correct_count', 'predicted_count', 'recall', 'precision'])) evaluation_result['labels'] = labels extended_test = extended_test.add_row_number('__idx').rename({'label': 'target_label'}) evaluation_result['test_data'] = extended_test evaluation_result['feature'] = self.feature return _Evaluation(evaluation_result)
[ "def", "evaluate", "(", "self", ",", "dataset", ",", "metric", "=", "'auto'", ",", "verbose", "=", "True", ",", "batch_size", "=", "64", ")", ":", "import", "os", ",", "json", ",", "math", "if", "(", "batch_size", "<", "1", ")", ":", "raise", "ValueError", "(", "\"'batch_size' must be greater than or equal to 1\"", ")", "extracted_features", "=", "self", ".", "_extract_features", "(", "dataset", ",", "verbose", "=", "verbose", ",", "batch_size", "=", "batch_size", ")", "extracted_features", "[", "self", ".", "target", "]", "=", "dataset", "[", "self", ".", "target", "]", "metrics", "=", "self", ".", "classifier", ".", "evaluate", "(", "extracted_features", ",", "metric", "=", "metric", ",", "with_predictions", "=", "True", ")", "predictions", "=", "metrics", "[", "\"predictions\"", "]", "[", "\"probs\"", "]", "state", "=", "self", ".", "__proxy__", ".", "get_state", "(", ")", "labels", "=", "state", "[", "\"classes\"", "]", "def", "entropy", "(", "probs", ")", ":", "return", "_reduce", "(", "lambda", "x", ",", "y", ":", "x", "+", "(", "y", "*", "math", ".", "log", "(", "1", "/", "y", ",", "2", ")", "if", "y", ">", "0", "else", "0", ")", ",", "probs", ",", "0", ")", "/", "math", ".", "log", "(", "len", "(", "probs", ")", ",", "2", ")", "def", "confidence", "(", "probs", ")", ":", "return", "max", "(", "probs", ")", "def", "relative_confidence", "(", "probs", ")", ":", "lp", "=", "len", "(", "probs", ")", "return", "probs", "[", "lp", "-", "1", "]", "-", "probs", "[", "lp", "-", "2", "]", "def", "get_confusion_matrix", "(", "extended_test", ",", "labels", ")", ":", "#Init a matrix", "sf_confusion_matrix", "=", "{", "'label'", ":", "[", "]", ",", "'predicted_label'", ":", "[", "]", ",", "'prob_default'", ":", "[", "]", "}", "for", "target_l", "in", "labels", ":", "for", "predicted_l", "in", "labels", ":", "sf_confusion_matrix", "[", "'label'", "]", ".", "append", "(", "target_l", ")", "sf_confusion_matrix", "[", "'predicted_label'", "]", ".", "append", "(", "predicted_l", ")", "sf_confusion_matrix", "[", "'prob_default'", "]", ".", "append", "(", "0", ")", "sf_confusion_matrix", "=", "_tc", ".", "SFrame", "(", "sf_confusion_matrix", ")", "sf_confusion_matrix", "=", "sf_confusion_matrix", ".", "join", "(", "extended_test", ".", "groupby", "(", "[", "'label'", ",", "'predicted_label'", "]", ",", "{", "'count'", ":", "_tc", ".", "aggregate", ".", "COUNT", "}", ")", ",", "how", "=", "'left'", ",", "on", "=", "[", "'label'", ",", "'predicted_label'", "]", ")", "sf_confusion_matrix", "=", "sf_confusion_matrix", ".", "fillna", "(", "'count'", ",", "0", ")", "label_column", "=", "_tc", ".", "SFrame", "(", "{", "'label'", ":", "extended_test", "[", "'label'", "]", "}", ")", "predictions", "=", "extended_test", "[", "'probs'", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "labels", ")", ")", ":", "new_test_data", "=", "label_column", ".", "add_columns", "(", "[", "predictions", ".", "apply", "(", "lambda", "probs", ":", "probs", "[", "i", "]", ")", ",", "predictions", ".", "apply", "(", "lambda", "probs", ":", "labels", "[", "i", "]", ")", "]", ",", "[", "'prob'", ",", "'predicted_label'", "]", ")", "if", "(", "i", "==", "0", ")", ":", "test_longer_form", "=", "new_test_data", "else", ":", "test_longer_form", "=", "test_longer_form", ".", "append", "(", "new_test_data", ")", "if", "len", "(", "extended_test", ")", "is", "0", ":", "sf_confusion_matrix", "=", "sf_confusion_matrix", ".", "rename", "(", "{", "'prob_default'", ":", "'prob'", ",", "'label'", ":", "'target_label'", "}", ")", "else", ":", "sf_confusion_matrix", "=", "sf_confusion_matrix", ".", "join", "(", "test_longer_form", ".", "groupby", "(", "[", "'label'", ",", "'predicted_label'", "]", ",", "{", "'prob'", ":", "_tc", ".", "aggregate", ".", "SUM", "(", "'prob'", ")", "}", ")", ",", "how", "=", "'left'", ",", "on", "=", "[", "'label'", ",", "'predicted_label'", "]", ")", "sf_confusion_matrix", "=", "sf_confusion_matrix", ".", "rename", "(", "{", "'label'", ":", "'target_label'", "}", ")", ".", "fillna", "(", "'prob'", ",", "0", ")", "def", "wo_divide_by_zero", "(", "a", ",", "b", ")", ":", "if", "b", "==", "0", ":", "return", "None", "else", ":", "return", "a", "*", "1.0", "/", "b", "sf_confusion_matrix", "[", "'norm_prob'", "]", "=", "sf_confusion_matrix", ".", "join", "(", "sf_confusion_matrix", ".", "groupby", "(", "'target_label'", ",", "{", "'sum_prob'", ":", "_tc", ".", "aggregate", ".", "SUM", "(", "'prob'", ")", "}", ")", ",", "how", "=", "'left'", ")", ".", "apply", "(", "lambda", "x", ":", "wo_divide_by_zero", "(", "x", "[", "'prob'", "]", ",", "x", "[", "'sum_prob'", "]", ")", ")", "return", "sf_confusion_matrix", ".", "fillna", "(", "'norm_prob'", ",", "0", ")", "def", "hclusterSort", "(", "vectors", ",", "dist_fn", ")", ":", "distances", "=", "[", "]", "vecs", "=", "list", "(", "vectors", ")", "[", ":", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "vecs", ")", ")", ":", "for", "j", "in", "range", "(", "i", "+", "1", ",", "len", "(", "vecs", ")", ")", ":", "distances", ".", "append", "(", "{", "'from'", ":", "vecs", "[", "i", "]", ",", "'to'", ":", "vecs", "[", "j", "]", ",", "'dist'", ":", "dist_fn", "(", "vecs", "[", "i", "]", ",", "vecs", "[", "j", "]", ")", "}", ")", "distances", "=", "sorted", "(", "distances", ",", "key", "=", "lambda", "d", ":", "d", "[", "'dist'", "]", ")", "excluding_names", "=", "[", "]", "while", "(", "len", "(", "distances", ")", ">", "0", ")", ":", "min_dist", "=", "distances", "[", "0", "]", "new_vec", "=", "{", "'name'", ":", "str", "(", "min_dist", "[", "'from'", "]", "[", "'name'", "]", ")", "+", "'|'", "+", "str", "(", "min_dist", "[", "'to'", "]", "[", "'name'", "]", ")", ",", "'members'", ":", "min_dist", "[", "'from'", "]", ".", "get", "(", "'members'", ",", "[", "min_dist", "[", "'from'", "]", "]", ")", "+", "min_dist", "[", "'to'", "]", ".", "get", "(", "'members'", ",", "[", "min_dist", "[", "'to'", "]", "]", ")", "}", "excluding_names", "=", "[", "min_dist", "[", "'from'", "]", "[", "'name'", "]", ",", "min_dist", "[", "'to'", "]", "[", "'name'", "]", "]", "vecs", "=", "filter", "(", "lambda", "v", ":", "v", "[", "'name'", "]", "not", "in", "excluding_names", ",", "vecs", ")", "distances", "=", "filter", "(", "lambda", "dist", ":", "(", "dist", "[", "'from'", "]", "[", "'name'", "]", "not", "in", "excluding_names", ")", "and", "(", "dist", "[", "'to'", "]", "[", "'name'", "]", "not", "in", "excluding_names", ")", ",", "distances", ")", "for", "v", "in", "vecs", ":", "total", "=", "0", "for", "vi", "in", "v", ".", "get", "(", "'members'", ",", "[", "v", "]", ")", ":", "for", "vj", "in", "new_vec", "[", "'members'", "]", ":", "total", "+=", "dist_fn", "(", "vi", ",", "vj", ")", "distances", ".", "append", "(", "{", "'from'", ":", "v", ",", "'to'", ":", "new_vec", ",", "'dist'", ":", "total", "/", "len", "(", "v", ".", "get", "(", "'members'", ",", "[", "v", "]", ")", ")", "/", "len", "(", "new_vec", "[", "'members'", "]", ")", "}", ")", "vecs", ".", "append", "(", "new_vec", ")", "distances", "=", "sorted", "(", "distances", ",", "key", "=", "lambda", "d", ":", "d", "[", "'dist'", "]", ")", "return", "vecs", "def", "l2Dist", "(", "v1", ",", "v2", ")", ":", "dist", "=", "0", "for", "i", "in", "range", "(", "0", ",", "len", "(", "v1", "[", "'pos'", "]", ")", ")", ":", "dist", "+=", "math", ".", "pow", "(", "v1", "[", "'pos'", "]", "[", "i", "]", "-", "v2", "[", "'pos'", "]", "[", "i", "]", ",", "2", ")", "return", "math", ".", "pow", "(", "dist", ",", "0.5", ")", "evaluation_result", "=", "{", "k", ":", "metrics", "[", "k", "]", "for", "k", "in", "[", "'accuracy'", ",", "'f1_score'", ",", "'log_loss'", ",", "'precision'", ",", "'recall'", ",", "'auc'", "]", "}", "evaluation_result", "[", "'num_test_examples'", "]", "=", "len", "(", "dataset", ")", "for", "k", "in", "[", "'num_classes'", ",", "'num_features'", ",", "'input_image_shape'", ",", "'num_examples'", ",", "'training_loss'", ",", "'training_time'", ",", "'model'", ",", "'max_iterations'", "]", ":", "evaluation_result", "[", "k", "]", "=", "getattr", "(", "self", ",", "k", ")", "# Extend the given test data", "extended_test", "=", "dataset", ".", "add_column", "(", "predictions", ",", "'probs'", ")", "extended_test", "[", "'label'", "]", "=", "dataset", "[", "self", ".", "target", "]", "extended_test", "=", "extended_test", ".", "add_columns", "(", "[", "extended_test", ".", "apply", "(", "lambda", "d", ":", "labels", "[", "d", "[", "'probs'", "]", ".", "index", "(", "confidence", "(", "d", "[", "'probs'", "]", ")", ")", "]", ")", ",", "extended_test", ".", "apply", "(", "lambda", "d", ":", "entropy", "(", "d", "[", "'probs'", "]", ")", ")", ",", "extended_test", ".", "apply", "(", "lambda", "d", ":", "confidence", "(", "d", "[", "'probs'", "]", ")", ")", ",", "extended_test", ".", "apply", "(", "lambda", "d", ":", "relative_confidence", "(", "d", "[", "'probs'", "]", ")", ")", "]", ",", "[", "'predicted_label'", ",", "'entropy'", ",", "'confidence'", ",", "'relative_confidence'", "]", ")", "extended_test", "=", "extended_test", ".", "add_column", "(", "extended_test", ".", "apply", "(", "lambda", "d", ":", "d", "[", "'label'", "]", "==", "d", "[", "'predicted_label'", "]", ")", ",", "'correct'", ")", "# Calculate the confusion matrix", "sf_conf_mat", "=", "get_confusion_matrix", "(", "extended_test", ",", "labels", ")", "confidence_threshold", "=", "0.5", "hesitant_threshold", "=", "0.2", "evaluation_result", "[", "'confidence_threshold'", "]", "=", "confidence_threshold", "evaluation_result", "[", "'hesitant_threshold'", "]", "=", "hesitant_threshold", "evaluation_result", "[", "'confidence_metric_for_threshold'", "]", "=", "'relative_confidence'", "sf_hesitant_conf_mat", "=", "get_confusion_matrix", "(", "extended_test", "[", "extended_test", "[", "evaluation_result", "[", "'confidence_metric_for_threshold'", "]", "]", "<", "hesitant_threshold", "]", ",", "labels", ")", "sf_confidently_wrong_conf_mat", "=", "get_confusion_matrix", "(", "extended_test", "[", "(", "extended_test", "[", "evaluation_result", "[", "'confidence_metric_for_threshold'", "]", "]", ">", "confidence_threshold", ")", "&", "(", "extended_test", "[", "'correct'", "]", "==", "True", ")", "]", ",", "labels", ")", "evaluation_result", "[", "'conf_mat'", "]", "=", "list", "(", "sf_conf_mat", ")", "evaluation_result", "[", "'hesitant_conf_mat'", "]", "=", "list", "(", "sf_hesitant_conf_mat", ")", "evaluation_result", "[", "'confidently_wrong_conf_mat'", "]", "=", "list", "(", "sf_confidently_wrong_conf_mat", ")", "# Get sorted labels (sorted by hCluster)", "vectors", "=", "map", "(", "lambda", "l", ":", "{", "'name'", ":", "l", ",", "'pos'", ":", "list", "(", "sf_conf_mat", "[", "sf_conf_mat", "[", "'target_label'", "]", "==", "l", "]", ".", "sort", "(", "'predicted_label'", ")", "[", "'norm_prob'", "]", ")", "}", ",", "labels", ")", "evaluation_result", "[", "'sorted_labels'", "]", "=", "hclusterSort", "(", "vectors", ",", "l2Dist", ")", "[", "0", "]", "[", "'name'", "]", ".", "split", "(", "\"|\"", ")", "# Get recall and precision per label", "per_l", "=", "extended_test", ".", "groupby", "(", "[", "'label'", "]", ",", "{", "'count'", ":", "_tc", ".", "aggregate", ".", "COUNT", ",", "'correct_count'", ":", "_tc", ".", "aggregate", ".", "SUM", "(", "'correct'", ")", "}", ")", "per_l", "[", "'recall'", "]", "=", "per_l", ".", "apply", "(", "lambda", "l", ":", "l", "[", "'correct_count'", "]", "*", "1.0", "/", "l", "[", "'count'", "]", ")", "per_pl", "=", "extended_test", ".", "groupby", "(", "[", "'predicted_label'", "]", ",", "{", "'predicted_count'", ":", "_tc", ".", "aggregate", ".", "COUNT", ",", "'correct_count'", ":", "_tc", ".", "aggregate", ".", "SUM", "(", "'correct'", ")", "}", ")", "per_pl", "[", "'precision'", "]", "=", "per_pl", ".", "apply", "(", "lambda", "l", ":", "l", "[", "'correct_count'", "]", "*", "1.0", "/", "l", "[", "'predicted_count'", "]", ")", "per_pl", "=", "per_pl", ".", "rename", "(", "{", "'predicted_label'", ":", "'label'", "}", ")", "evaluation_result", "[", "'label_metrics'", "]", "=", "list", "(", "per_l", ".", "join", "(", "per_pl", ",", "on", "=", "'label'", ",", "how", "=", "'outer'", ")", ".", "select_columns", "(", "[", "'label'", ",", "'count'", ",", "'correct_count'", ",", "'predicted_count'", ",", "'recall'", ",", "'precision'", "]", ")", ")", "evaluation_result", "[", "'labels'", "]", "=", "labels", "extended_test", "=", "extended_test", ".", "add_row_number", "(", "'__idx'", ")", ".", "rename", "(", "{", "'label'", ":", "'target_label'", "}", ")", "evaluation_result", "[", "'test_data'", "]", "=", "extended_test", "evaluation_result", "[", "'feature'", "]", "=", "self", ".", "feature", "return", "_Evaluation", "(", "evaluation_result", ")" ]
Evaluate the model by making predictions of target values and comparing these to actual values. Parameters ---------- dataset : SFrame Dataset of new observations. Must include columns with the same names as the target and features used for model training. Additional columns are ignored. metric : str, optional Name of the evaluation metric. Possible values are: - 'auto' : Returns all available metrics. - 'accuracy' : Classification accuracy (micro average). - 'auc' : Area under the ROC curve (macro average) - 'precision' : Precision score (macro average) - 'recall' : Recall score (macro average) - 'f1_score' : F1 score (macro average) - 'log_loss' : Log loss - 'confusion_matrix' : An SFrame with counts of possible prediction/true label combinations. - 'roc_curve' : An SFrame containing information needed for an ROC curve For more flexibility in calculating evaluation metrics, use the :class:`~turicreate.evaluation` module. verbose : bool, optional If True, prints progress updates and model details. batch_size : int, optional If you are getting memory errors, try decreasing this value. If you have a powerful computer, increasing this value may improve performance. Returns ------- out : dict Dictionary of evaluation results where the key is the name of the evaluation metric (e.g. `accuracy`) and the value is the evaluation score. See Also ---------- create, predict, classify Examples ---------- .. sourcecode:: python >>> results = model.evaluate(data) >>> print results['accuracy']
[ "Evaluate", "the", "model", "by", "making", "predictions", "of", "target", "values", "and", "comparing", "these", "to", "actual", "values", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/image_classifier/image_classifier.py#L611-L816
train
apple/turicreate
src/unity/python/turicreate/toolkits/image_classifier/image_classifier.py
ImageClassifier.export_coreml
def export_coreml(self, filename): """ Save the model in Core ML format. See Also -------- save Examples -------- >>> model.export_coreml('myModel.mlmodel') """ import coremltools # First define three internal helper functions # Internal helper function def _create_vision_feature_print_scene(): prob_name = self.target + 'Probability' # # Setup the top level (pipeline classifier) spec # top_spec = coremltools.proto.Model_pb2.Model() top_spec.specificationVersion = 3 desc = top_spec.description desc.output.add().name = prob_name desc.output.add().name = self.target desc.predictedFeatureName = self.target desc.predictedProbabilitiesName = prob_name input = desc.input.add() input.name = self.feature input.type.imageType.width = 299 input.type.imageType.height = 299 BGR_VALUE = coremltools.proto.FeatureTypes_pb2.ImageFeatureType.ColorSpace.Value('BGR') input.type.imageType.colorSpace = BGR_VALUE # # VisionFeaturePrint extractor # pipelineClassifier = top_spec.pipelineClassifier scene_print = pipelineClassifier.pipeline.models.add() scene_print.specificationVersion = 3 scene_print.visionFeaturePrint.scene.version = 1 input = scene_print.description.input.add() input.name = self.feature input.type.imageType.width = 299 input.type.imageType.height = 299 input.type.imageType.colorSpace = BGR_VALUE output = scene_print.description.output.add() output.name = "output_name" DOUBLE_ARRAY_VALUE = coremltools.proto.FeatureTypes_pb2.ArrayFeatureType.ArrayDataType.Value('DOUBLE') output.type.multiArrayType.dataType = DOUBLE_ARRAY_VALUE output.type.multiArrayType.shape.append(2048) # # Neural Network Classifier, which is just logistic regression, in order to use GPUs # temp = top_spec.pipelineClassifier.pipeline.models.add() temp.specificationVersion = 3 # Empty inner product layer nn_spec = temp.neuralNetworkClassifier feature_layer = nn_spec.layers.add() feature_layer.name = "feature_layer" feature_layer.input.append("output_name") feature_layer.output.append("softmax_input") fc_layer_params = feature_layer.innerProduct fc_layer_params.inputChannels = 2048 # Softmax layer softmax = nn_spec.layers.add() softmax.name = "softmax" softmax.softmax.MergeFromString(b'') softmax.input.append("softmax_input") softmax.output.append(prob_name) input = temp.description.input.add() input.name = "output_name" input.type.multiArrayType.dataType = DOUBLE_ARRAY_VALUE input.type.multiArrayType.shape.append(2048) # Set outputs desc = temp.description prob_output = desc.output.add() prob_output.name = prob_name label_output = desc.output.add() label_output.name = self.target if type(self.classifier.classes[0]) == int: prob_output.type.dictionaryType.int64KeyType.MergeFromString(b'') label_output.type.int64Type.MergeFromString(b'') else: prob_output.type.dictionaryType.stringKeyType.MergeFromString(b'') label_output.type.stringType.MergeFromString(b'') temp.description.predictedFeatureName = self.target temp.description.predictedProbabilitiesName = prob_name return top_spec # Internal helper function def _update_last_two_layers(nn_spec): # Replace the softmax layer with new coeffients num_classes = self.num_classes fc_layer = nn_spec.layers[-2] fc_layer_params = fc_layer.innerProduct fc_layer_params.outputChannels = self.classifier.num_classes inputChannels = fc_layer_params.inputChannels fc_layer_params.hasBias = True coefs = self.classifier.coefficients weights = fc_layer_params.weights bias = fc_layer_params.bias del weights.floatValue[:] del bias.floatValue[:] import numpy as np W = np.array(coefs[coefs['index'] != None]['value'], ndmin = 2).reshape( inputChannels, num_classes - 1, order = 'F') b = coefs[coefs['index'] == None]['value'] Wa = np.hstack((np.zeros((inputChannels, 1)), W)) weights.floatValue.extend(Wa.flatten(order = 'F')) bias.floatValue.extend([0.0] + list(b)) # Internal helper function def _set_inputs_outputs_and_metadata(spec, nn_spec): # Replace the classifier with the new classes class_labels = self.classifier.classes probOutput = spec.description.output[0] classLabel = spec.description.output[1] probOutput.type.dictionaryType.MergeFromString(b'') if type(class_labels[0]) == int: nn_spec.ClearField('int64ClassLabels') probOutput.type.dictionaryType.int64KeyType.MergeFromString(b'') classLabel.type.int64Type.MergeFromString(b'') del nn_spec.int64ClassLabels.vector[:] for c in class_labels: nn_spec.int64ClassLabels.vector.append(c) else: nn_spec.ClearField('stringClassLabels') probOutput.type.dictionaryType.stringKeyType.MergeFromString(b'') classLabel.type.stringType.MergeFromString(b'') del nn_spec.stringClassLabels.vector[:] for c in class_labels: nn_spec.stringClassLabels.vector.append(c) prob_name = self.target + 'Probability' label_name = self.target old_output_name = nn_spec.layers[-1].name coremltools.models.utils.rename_feature(spec, 'classLabel', label_name) coremltools.models.utils.rename_feature(spec, old_output_name, prob_name) if nn_spec.layers[-1].name == old_output_name: nn_spec.layers[-1].name = prob_name if nn_spec.labelProbabilityLayerName == old_output_name: nn_spec.labelProbabilityLayerName = prob_name coremltools.models.utils.rename_feature(spec, 'data', self.feature) if len(nn_spec.preprocessing) > 0: nn_spec.preprocessing[0].featureName = self.feature mlmodel = coremltools.models.MLModel(spec) model_type = 'image classifier (%s)' % self.model mlmodel.short_description = _coreml_utils._mlmodel_short_description(model_type) mlmodel.input_description[self.feature] = u'Input image' mlmodel.output_description[prob_name] = 'Prediction probabilities' mlmodel.output_description[label_name] = 'Class label of top prediction' _coreml_utils._set_model_metadata(mlmodel, self.__class__.__name__, { 'model': self.model, 'target': self.target, 'features': self.feature, 'max_iterations': str(self.max_iterations), }, version=ImageClassifier._PYTHON_IMAGE_CLASSIFIER_VERSION) return mlmodel # main part of the export_coreml function if self.model in _pre_trained_models.MODELS: ptModel = _pre_trained_models.MODELS[self.model]() feature_extractor = _image_feature_extractor.MXFeatureExtractor(ptModel) coreml_model = feature_extractor.get_coreml_model() spec = coreml_model.get_spec() nn_spec = spec.neuralNetworkClassifier else: # model == VisionFeaturePrint_Scene spec = _create_vision_feature_print_scene() nn_spec = spec.pipelineClassifier.pipeline.models[1].neuralNetworkClassifier _update_last_two_layers(nn_spec) mlmodel = _set_inputs_outputs_and_metadata(spec, nn_spec) mlmodel.save(filename)
python
def export_coreml(self, filename): """ Save the model in Core ML format. See Also -------- save Examples -------- >>> model.export_coreml('myModel.mlmodel') """ import coremltools # First define three internal helper functions # Internal helper function def _create_vision_feature_print_scene(): prob_name = self.target + 'Probability' # # Setup the top level (pipeline classifier) spec # top_spec = coremltools.proto.Model_pb2.Model() top_spec.specificationVersion = 3 desc = top_spec.description desc.output.add().name = prob_name desc.output.add().name = self.target desc.predictedFeatureName = self.target desc.predictedProbabilitiesName = prob_name input = desc.input.add() input.name = self.feature input.type.imageType.width = 299 input.type.imageType.height = 299 BGR_VALUE = coremltools.proto.FeatureTypes_pb2.ImageFeatureType.ColorSpace.Value('BGR') input.type.imageType.colorSpace = BGR_VALUE # # VisionFeaturePrint extractor # pipelineClassifier = top_spec.pipelineClassifier scene_print = pipelineClassifier.pipeline.models.add() scene_print.specificationVersion = 3 scene_print.visionFeaturePrint.scene.version = 1 input = scene_print.description.input.add() input.name = self.feature input.type.imageType.width = 299 input.type.imageType.height = 299 input.type.imageType.colorSpace = BGR_VALUE output = scene_print.description.output.add() output.name = "output_name" DOUBLE_ARRAY_VALUE = coremltools.proto.FeatureTypes_pb2.ArrayFeatureType.ArrayDataType.Value('DOUBLE') output.type.multiArrayType.dataType = DOUBLE_ARRAY_VALUE output.type.multiArrayType.shape.append(2048) # # Neural Network Classifier, which is just logistic regression, in order to use GPUs # temp = top_spec.pipelineClassifier.pipeline.models.add() temp.specificationVersion = 3 # Empty inner product layer nn_spec = temp.neuralNetworkClassifier feature_layer = nn_spec.layers.add() feature_layer.name = "feature_layer" feature_layer.input.append("output_name") feature_layer.output.append("softmax_input") fc_layer_params = feature_layer.innerProduct fc_layer_params.inputChannels = 2048 # Softmax layer softmax = nn_spec.layers.add() softmax.name = "softmax" softmax.softmax.MergeFromString(b'') softmax.input.append("softmax_input") softmax.output.append(prob_name) input = temp.description.input.add() input.name = "output_name" input.type.multiArrayType.dataType = DOUBLE_ARRAY_VALUE input.type.multiArrayType.shape.append(2048) # Set outputs desc = temp.description prob_output = desc.output.add() prob_output.name = prob_name label_output = desc.output.add() label_output.name = self.target if type(self.classifier.classes[0]) == int: prob_output.type.dictionaryType.int64KeyType.MergeFromString(b'') label_output.type.int64Type.MergeFromString(b'') else: prob_output.type.dictionaryType.stringKeyType.MergeFromString(b'') label_output.type.stringType.MergeFromString(b'') temp.description.predictedFeatureName = self.target temp.description.predictedProbabilitiesName = prob_name return top_spec # Internal helper function def _update_last_two_layers(nn_spec): # Replace the softmax layer with new coeffients num_classes = self.num_classes fc_layer = nn_spec.layers[-2] fc_layer_params = fc_layer.innerProduct fc_layer_params.outputChannels = self.classifier.num_classes inputChannels = fc_layer_params.inputChannels fc_layer_params.hasBias = True coefs = self.classifier.coefficients weights = fc_layer_params.weights bias = fc_layer_params.bias del weights.floatValue[:] del bias.floatValue[:] import numpy as np W = np.array(coefs[coefs['index'] != None]['value'], ndmin = 2).reshape( inputChannels, num_classes - 1, order = 'F') b = coefs[coefs['index'] == None]['value'] Wa = np.hstack((np.zeros((inputChannels, 1)), W)) weights.floatValue.extend(Wa.flatten(order = 'F')) bias.floatValue.extend([0.0] + list(b)) # Internal helper function def _set_inputs_outputs_and_metadata(spec, nn_spec): # Replace the classifier with the new classes class_labels = self.classifier.classes probOutput = spec.description.output[0] classLabel = spec.description.output[1] probOutput.type.dictionaryType.MergeFromString(b'') if type(class_labels[0]) == int: nn_spec.ClearField('int64ClassLabels') probOutput.type.dictionaryType.int64KeyType.MergeFromString(b'') classLabel.type.int64Type.MergeFromString(b'') del nn_spec.int64ClassLabels.vector[:] for c in class_labels: nn_spec.int64ClassLabels.vector.append(c) else: nn_spec.ClearField('stringClassLabels') probOutput.type.dictionaryType.stringKeyType.MergeFromString(b'') classLabel.type.stringType.MergeFromString(b'') del nn_spec.stringClassLabels.vector[:] for c in class_labels: nn_spec.stringClassLabels.vector.append(c) prob_name = self.target + 'Probability' label_name = self.target old_output_name = nn_spec.layers[-1].name coremltools.models.utils.rename_feature(spec, 'classLabel', label_name) coremltools.models.utils.rename_feature(spec, old_output_name, prob_name) if nn_spec.layers[-1].name == old_output_name: nn_spec.layers[-1].name = prob_name if nn_spec.labelProbabilityLayerName == old_output_name: nn_spec.labelProbabilityLayerName = prob_name coremltools.models.utils.rename_feature(spec, 'data', self.feature) if len(nn_spec.preprocessing) > 0: nn_spec.preprocessing[0].featureName = self.feature mlmodel = coremltools.models.MLModel(spec) model_type = 'image classifier (%s)' % self.model mlmodel.short_description = _coreml_utils._mlmodel_short_description(model_type) mlmodel.input_description[self.feature] = u'Input image' mlmodel.output_description[prob_name] = 'Prediction probabilities' mlmodel.output_description[label_name] = 'Class label of top prediction' _coreml_utils._set_model_metadata(mlmodel, self.__class__.__name__, { 'model': self.model, 'target': self.target, 'features': self.feature, 'max_iterations': str(self.max_iterations), }, version=ImageClassifier._PYTHON_IMAGE_CLASSIFIER_VERSION) return mlmodel # main part of the export_coreml function if self.model in _pre_trained_models.MODELS: ptModel = _pre_trained_models.MODELS[self.model]() feature_extractor = _image_feature_extractor.MXFeatureExtractor(ptModel) coreml_model = feature_extractor.get_coreml_model() spec = coreml_model.get_spec() nn_spec = spec.neuralNetworkClassifier else: # model == VisionFeaturePrint_Scene spec = _create_vision_feature_print_scene() nn_spec = spec.pipelineClassifier.pipeline.models[1].neuralNetworkClassifier _update_last_two_layers(nn_spec) mlmodel = _set_inputs_outputs_and_metadata(spec, nn_spec) mlmodel.save(filename)
[ "def", "export_coreml", "(", "self", ",", "filename", ")", ":", "import", "coremltools", "# First define three internal helper functions", "# Internal helper function", "def", "_create_vision_feature_print_scene", "(", ")", ":", "prob_name", "=", "self", ".", "target", "+", "'Probability'", "#", "# Setup the top level (pipeline classifier) spec", "#", "top_spec", "=", "coremltools", ".", "proto", ".", "Model_pb2", ".", "Model", "(", ")", "top_spec", ".", "specificationVersion", "=", "3", "desc", "=", "top_spec", ".", "description", "desc", ".", "output", ".", "add", "(", ")", ".", "name", "=", "prob_name", "desc", ".", "output", ".", "add", "(", ")", ".", "name", "=", "self", ".", "target", "desc", ".", "predictedFeatureName", "=", "self", ".", "target", "desc", ".", "predictedProbabilitiesName", "=", "prob_name", "input", "=", "desc", ".", "input", ".", "add", "(", ")", "input", ".", "name", "=", "self", ".", "feature", "input", ".", "type", ".", "imageType", ".", "width", "=", "299", "input", ".", "type", ".", "imageType", ".", "height", "=", "299", "BGR_VALUE", "=", "coremltools", ".", "proto", ".", "FeatureTypes_pb2", ".", "ImageFeatureType", ".", "ColorSpace", ".", "Value", "(", "'BGR'", ")", "input", ".", "type", ".", "imageType", ".", "colorSpace", "=", "BGR_VALUE", "#", "# VisionFeaturePrint extractor", "#", "pipelineClassifier", "=", "top_spec", ".", "pipelineClassifier", "scene_print", "=", "pipelineClassifier", ".", "pipeline", ".", "models", ".", "add", "(", ")", "scene_print", ".", "specificationVersion", "=", "3", "scene_print", ".", "visionFeaturePrint", ".", "scene", ".", "version", "=", "1", "input", "=", "scene_print", ".", "description", ".", "input", ".", "add", "(", ")", "input", ".", "name", "=", "self", ".", "feature", "input", ".", "type", ".", "imageType", ".", "width", "=", "299", "input", ".", "type", ".", "imageType", ".", "height", "=", "299", "input", ".", "type", ".", "imageType", ".", "colorSpace", "=", "BGR_VALUE", "output", "=", "scene_print", ".", "description", ".", "output", ".", "add", "(", ")", "output", ".", "name", "=", "\"output_name\"", "DOUBLE_ARRAY_VALUE", "=", "coremltools", ".", "proto", ".", "FeatureTypes_pb2", ".", "ArrayFeatureType", ".", "ArrayDataType", ".", "Value", "(", "'DOUBLE'", ")", "output", ".", "type", ".", "multiArrayType", ".", "dataType", "=", "DOUBLE_ARRAY_VALUE", "output", ".", "type", ".", "multiArrayType", ".", "shape", ".", "append", "(", "2048", ")", "#", "# Neural Network Classifier, which is just logistic regression, in order to use GPUs", "#", "temp", "=", "top_spec", ".", "pipelineClassifier", ".", "pipeline", ".", "models", ".", "add", "(", ")", "temp", ".", "specificationVersion", "=", "3", "# Empty inner product layer", "nn_spec", "=", "temp", ".", "neuralNetworkClassifier", "feature_layer", "=", "nn_spec", ".", "layers", ".", "add", "(", ")", "feature_layer", ".", "name", "=", "\"feature_layer\"", "feature_layer", ".", "input", ".", "append", "(", "\"output_name\"", ")", "feature_layer", ".", "output", ".", "append", "(", "\"softmax_input\"", ")", "fc_layer_params", "=", "feature_layer", ".", "innerProduct", "fc_layer_params", ".", "inputChannels", "=", "2048", "# Softmax layer", "softmax", "=", "nn_spec", ".", "layers", ".", "add", "(", ")", "softmax", ".", "name", "=", "\"softmax\"", "softmax", ".", "softmax", ".", "MergeFromString", "(", "b''", ")", "softmax", ".", "input", ".", "append", "(", "\"softmax_input\"", ")", "softmax", ".", "output", ".", "append", "(", "prob_name", ")", "input", "=", "temp", ".", "description", ".", "input", ".", "add", "(", ")", "input", ".", "name", "=", "\"output_name\"", "input", ".", "type", ".", "multiArrayType", ".", "dataType", "=", "DOUBLE_ARRAY_VALUE", "input", ".", "type", ".", "multiArrayType", ".", "shape", ".", "append", "(", "2048", ")", "# Set outputs", "desc", "=", "temp", ".", "description", "prob_output", "=", "desc", ".", "output", ".", "add", "(", ")", "prob_output", ".", "name", "=", "prob_name", "label_output", "=", "desc", ".", "output", ".", "add", "(", ")", "label_output", ".", "name", "=", "self", ".", "target", "if", "type", "(", "self", ".", "classifier", ".", "classes", "[", "0", "]", ")", "==", "int", ":", "prob_output", ".", "type", ".", "dictionaryType", ".", "int64KeyType", ".", "MergeFromString", "(", "b''", ")", "label_output", ".", "type", ".", "int64Type", ".", "MergeFromString", "(", "b''", ")", "else", ":", "prob_output", ".", "type", ".", "dictionaryType", ".", "stringKeyType", ".", "MergeFromString", "(", "b''", ")", "label_output", ".", "type", ".", "stringType", ".", "MergeFromString", "(", "b''", ")", "temp", ".", "description", ".", "predictedFeatureName", "=", "self", ".", "target", "temp", ".", "description", ".", "predictedProbabilitiesName", "=", "prob_name", "return", "top_spec", "# Internal helper function", "def", "_update_last_two_layers", "(", "nn_spec", ")", ":", "# Replace the softmax layer with new coeffients", "num_classes", "=", "self", ".", "num_classes", "fc_layer", "=", "nn_spec", ".", "layers", "[", "-", "2", "]", "fc_layer_params", "=", "fc_layer", ".", "innerProduct", "fc_layer_params", ".", "outputChannels", "=", "self", ".", "classifier", ".", "num_classes", "inputChannels", "=", "fc_layer_params", ".", "inputChannels", "fc_layer_params", ".", "hasBias", "=", "True", "coefs", "=", "self", ".", "classifier", ".", "coefficients", "weights", "=", "fc_layer_params", ".", "weights", "bias", "=", "fc_layer_params", ".", "bias", "del", "weights", ".", "floatValue", "[", ":", "]", "del", "bias", ".", "floatValue", "[", ":", "]", "import", "numpy", "as", "np", "W", "=", "np", ".", "array", "(", "coefs", "[", "coefs", "[", "'index'", "]", "!=", "None", "]", "[", "'value'", "]", ",", "ndmin", "=", "2", ")", ".", "reshape", "(", "inputChannels", ",", "num_classes", "-", "1", ",", "order", "=", "'F'", ")", "b", "=", "coefs", "[", "coefs", "[", "'index'", "]", "==", "None", "]", "[", "'value'", "]", "Wa", "=", "np", ".", "hstack", "(", "(", "np", ".", "zeros", "(", "(", "inputChannels", ",", "1", ")", ")", ",", "W", ")", ")", "weights", ".", "floatValue", ".", "extend", "(", "Wa", ".", "flatten", "(", "order", "=", "'F'", ")", ")", "bias", ".", "floatValue", ".", "extend", "(", "[", "0.0", "]", "+", "list", "(", "b", ")", ")", "# Internal helper function", "def", "_set_inputs_outputs_and_metadata", "(", "spec", ",", "nn_spec", ")", ":", "# Replace the classifier with the new classes", "class_labels", "=", "self", ".", "classifier", ".", "classes", "probOutput", "=", "spec", ".", "description", ".", "output", "[", "0", "]", "classLabel", "=", "spec", ".", "description", ".", "output", "[", "1", "]", "probOutput", ".", "type", ".", "dictionaryType", ".", "MergeFromString", "(", "b''", ")", "if", "type", "(", "class_labels", "[", "0", "]", ")", "==", "int", ":", "nn_spec", ".", "ClearField", "(", "'int64ClassLabels'", ")", "probOutput", ".", "type", ".", "dictionaryType", ".", "int64KeyType", ".", "MergeFromString", "(", "b''", ")", "classLabel", ".", "type", ".", "int64Type", ".", "MergeFromString", "(", "b''", ")", "del", "nn_spec", ".", "int64ClassLabels", ".", "vector", "[", ":", "]", "for", "c", "in", "class_labels", ":", "nn_spec", ".", "int64ClassLabels", ".", "vector", ".", "append", "(", "c", ")", "else", ":", "nn_spec", ".", "ClearField", "(", "'stringClassLabels'", ")", "probOutput", ".", "type", ".", "dictionaryType", ".", "stringKeyType", ".", "MergeFromString", "(", "b''", ")", "classLabel", ".", "type", ".", "stringType", ".", "MergeFromString", "(", "b''", ")", "del", "nn_spec", ".", "stringClassLabels", ".", "vector", "[", ":", "]", "for", "c", "in", "class_labels", ":", "nn_spec", ".", "stringClassLabels", ".", "vector", ".", "append", "(", "c", ")", "prob_name", "=", "self", ".", "target", "+", "'Probability'", "label_name", "=", "self", ".", "target", "old_output_name", "=", "nn_spec", ".", "layers", "[", "-", "1", "]", ".", "name", "coremltools", ".", "models", ".", "utils", ".", "rename_feature", "(", "spec", ",", "'classLabel'", ",", "label_name", ")", "coremltools", ".", "models", ".", "utils", ".", "rename_feature", "(", "spec", ",", "old_output_name", ",", "prob_name", ")", "if", "nn_spec", ".", "layers", "[", "-", "1", "]", ".", "name", "==", "old_output_name", ":", "nn_spec", ".", "layers", "[", "-", "1", "]", ".", "name", "=", "prob_name", "if", "nn_spec", ".", "labelProbabilityLayerName", "==", "old_output_name", ":", "nn_spec", ".", "labelProbabilityLayerName", "=", "prob_name", "coremltools", ".", "models", ".", "utils", ".", "rename_feature", "(", "spec", ",", "'data'", ",", "self", ".", "feature", ")", "if", "len", "(", "nn_spec", ".", "preprocessing", ")", ">", "0", ":", "nn_spec", ".", "preprocessing", "[", "0", "]", ".", "featureName", "=", "self", ".", "feature", "mlmodel", "=", "coremltools", ".", "models", ".", "MLModel", "(", "spec", ")", "model_type", "=", "'image classifier (%s)'", "%", "self", ".", "model", "mlmodel", ".", "short_description", "=", "_coreml_utils", ".", "_mlmodel_short_description", "(", "model_type", ")", "mlmodel", ".", "input_description", "[", "self", ".", "feature", "]", "=", "u'Input image'", "mlmodel", ".", "output_description", "[", "prob_name", "]", "=", "'Prediction probabilities'", "mlmodel", ".", "output_description", "[", "label_name", "]", "=", "'Class label of top prediction'", "_coreml_utils", ".", "_set_model_metadata", "(", "mlmodel", ",", "self", ".", "__class__", ".", "__name__", ",", "{", "'model'", ":", "self", ".", "model", ",", "'target'", ":", "self", ".", "target", ",", "'features'", ":", "self", ".", "feature", ",", "'max_iterations'", ":", "str", "(", "self", ".", "max_iterations", ")", ",", "}", ",", "version", "=", "ImageClassifier", ".", "_PYTHON_IMAGE_CLASSIFIER_VERSION", ")", "return", "mlmodel", "# main part of the export_coreml function", "if", "self", ".", "model", "in", "_pre_trained_models", ".", "MODELS", ":", "ptModel", "=", "_pre_trained_models", ".", "MODELS", "[", "self", ".", "model", "]", "(", ")", "feature_extractor", "=", "_image_feature_extractor", ".", "MXFeatureExtractor", "(", "ptModel", ")", "coreml_model", "=", "feature_extractor", ".", "get_coreml_model", "(", ")", "spec", "=", "coreml_model", ".", "get_spec", "(", ")", "nn_spec", "=", "spec", ".", "neuralNetworkClassifier", "else", ":", "# model == VisionFeaturePrint_Scene", "spec", "=", "_create_vision_feature_print_scene", "(", ")", "nn_spec", "=", "spec", ".", "pipelineClassifier", ".", "pipeline", ".", "models", "[", "1", "]", ".", "neuralNetworkClassifier", "_update_last_two_layers", "(", "nn_spec", ")", "mlmodel", "=", "_set_inputs_outputs_and_metadata", "(", "spec", ",", "nn_spec", ")", "mlmodel", ".", "save", "(", "filename", ")" ]
Save the model in Core ML format. See Also -------- save Examples -------- >>> model.export_coreml('myModel.mlmodel')
[ "Save", "the", "model", "in", "Core", "ML", "format", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/image_classifier/image_classifier.py#L824-L1021
train
apple/turicreate
src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_topology2.py
NetGraph.make_input_layers
def make_input_layers(self): """ Extract the ordering of the input layers. """ self.input_layers = [] in_nodes = self.model._inbound_nodes if hasattr( self.model,'_inbound_nodes') else self.model.inbound_nodes if hasattr(self.model, 'input_layers'): input_keras_layers = self.model.input_layers[:] self.input_layers = [None] * len(input_keras_layers) for layer in self.layer_list: keras_layer = self.keras_layer_map[layer] if isinstance(keras_layer, InputLayer): if keras_layer in input_keras_layers: idx = input_keras_layers.index(keras_layer) self.input_layers[idx] = layer elif hasattr(self.model, 'inputs'): for ts in _to_list(self.model.inputs): # search for the InputLayer that matches this ts for l in self.layer_list: kl = self.keras_layer_map[l] if isinstance(kl, InputLayer) and kl.input == ts: self.input_layers.append(l) elif len(in_nodes) <= 1: for ts in _to_list(self.model.input): # search for the InputLayer that matches this ts for l in self.layer_list: kl = self.keras_layer_map[l] if isinstance(kl, InputLayer) and kl.input == ts: self.input_layers.append(l) else: raise ValueError("Input values cannot be identified.")
python
def make_input_layers(self): """ Extract the ordering of the input layers. """ self.input_layers = [] in_nodes = self.model._inbound_nodes if hasattr( self.model,'_inbound_nodes') else self.model.inbound_nodes if hasattr(self.model, 'input_layers'): input_keras_layers = self.model.input_layers[:] self.input_layers = [None] * len(input_keras_layers) for layer in self.layer_list: keras_layer = self.keras_layer_map[layer] if isinstance(keras_layer, InputLayer): if keras_layer in input_keras_layers: idx = input_keras_layers.index(keras_layer) self.input_layers[idx] = layer elif hasattr(self.model, 'inputs'): for ts in _to_list(self.model.inputs): # search for the InputLayer that matches this ts for l in self.layer_list: kl = self.keras_layer_map[l] if isinstance(kl, InputLayer) and kl.input == ts: self.input_layers.append(l) elif len(in_nodes) <= 1: for ts in _to_list(self.model.input): # search for the InputLayer that matches this ts for l in self.layer_list: kl = self.keras_layer_map[l] if isinstance(kl, InputLayer) and kl.input == ts: self.input_layers.append(l) else: raise ValueError("Input values cannot be identified.")
[ "def", "make_input_layers", "(", "self", ")", ":", "self", ".", "input_layers", "=", "[", "]", "in_nodes", "=", "self", ".", "model", ".", "_inbound_nodes", "if", "hasattr", "(", "self", ".", "model", ",", "'_inbound_nodes'", ")", "else", "self", ".", "model", ".", "inbound_nodes", "if", "hasattr", "(", "self", ".", "model", ",", "'input_layers'", ")", ":", "input_keras_layers", "=", "self", ".", "model", ".", "input_layers", "[", ":", "]", "self", ".", "input_layers", "=", "[", "None", "]", "*", "len", "(", "input_keras_layers", ")", "for", "layer", "in", "self", ".", "layer_list", ":", "keras_layer", "=", "self", ".", "keras_layer_map", "[", "layer", "]", "if", "isinstance", "(", "keras_layer", ",", "InputLayer", ")", ":", "if", "keras_layer", "in", "input_keras_layers", ":", "idx", "=", "input_keras_layers", ".", "index", "(", "keras_layer", ")", "self", ".", "input_layers", "[", "idx", "]", "=", "layer", "elif", "hasattr", "(", "self", ".", "model", ",", "'inputs'", ")", ":", "for", "ts", "in", "_to_list", "(", "self", ".", "model", ".", "inputs", ")", ":", "# search for the InputLayer that matches this ts", "for", "l", "in", "self", ".", "layer_list", ":", "kl", "=", "self", ".", "keras_layer_map", "[", "l", "]", "if", "isinstance", "(", "kl", ",", "InputLayer", ")", "and", "kl", ".", "input", "==", "ts", ":", "self", ".", "input_layers", ".", "append", "(", "l", ")", "elif", "len", "(", "in_nodes", ")", "<=", "1", ":", "for", "ts", "in", "_to_list", "(", "self", ".", "model", ".", "input", ")", ":", "# search for the InputLayer that matches this ts", "for", "l", "in", "self", ".", "layer_list", ":", "kl", "=", "self", ".", "keras_layer_map", "[", "l", "]", "if", "isinstance", "(", "kl", ",", "InputLayer", ")", "and", "kl", ".", "input", "==", "ts", ":", "self", ".", "input_layers", ".", "append", "(", "l", ")", "else", ":", "raise", "ValueError", "(", "\"Input values cannot be identified.\"", ")" ]
Extract the ordering of the input layers.
[ "Extract", "the", "ordering", "of", "the", "input", "layers", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_topology2.py#L148-L179
train
apple/turicreate
src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_topology2.py
NetGraph.make_output_layers
def make_output_layers(self): """ Extract the ordering of output layers. """ self.output_layers = [] # import pytest; pytest.set_trace() if hasattr(self.model, 'output_layers'): # find corresponding output layers in CoreML model # assume output layers are not shared # Helper function to recursively extract output layers # even if the model has a layer which is a nested model def extract_output_layers(keras_model): output_layers = [] for layer in keras_model.output_layers: if hasattr(layer,'output_layers'): output_layers.extend(extract_output_layers(layer)) else: output_layers.append(layer) return output_layers for kl in extract_output_layers(self.model): coreml_layers = self.get_coreml_layers(kl) if len(coreml_layers) > 0: for cl in coreml_layers: self.output_layers.append(cl) elif len(self.model.outputs) > 0: for model_output in self.model.outputs: for l in self.layer_list: k_layer = self.keras_layer_map[l] in_nodes = k_layer._inbound_nodes if hasattr(k_layer, '_inbound_nodes') else k_layer.inbound_nodes for idx in range(len(in_nodes)): out_tensor = k_layer.get_output_at(idx) if out_tensor == model_output or (out_tensor.name in model_output.name): self.output_layers.append(l) if len(self.output_layers) == 0: raise ValueError("No outputs can be identified")
python
def make_output_layers(self): """ Extract the ordering of output layers. """ self.output_layers = [] # import pytest; pytest.set_trace() if hasattr(self.model, 'output_layers'): # find corresponding output layers in CoreML model # assume output layers are not shared # Helper function to recursively extract output layers # even if the model has a layer which is a nested model def extract_output_layers(keras_model): output_layers = [] for layer in keras_model.output_layers: if hasattr(layer,'output_layers'): output_layers.extend(extract_output_layers(layer)) else: output_layers.append(layer) return output_layers for kl in extract_output_layers(self.model): coreml_layers = self.get_coreml_layers(kl) if len(coreml_layers) > 0: for cl in coreml_layers: self.output_layers.append(cl) elif len(self.model.outputs) > 0: for model_output in self.model.outputs: for l in self.layer_list: k_layer = self.keras_layer_map[l] in_nodes = k_layer._inbound_nodes if hasattr(k_layer, '_inbound_nodes') else k_layer.inbound_nodes for idx in range(len(in_nodes)): out_tensor = k_layer.get_output_at(idx) if out_tensor == model_output or (out_tensor.name in model_output.name): self.output_layers.append(l) if len(self.output_layers) == 0: raise ValueError("No outputs can be identified")
[ "def", "make_output_layers", "(", "self", ")", ":", "self", ".", "output_layers", "=", "[", "]", "# import pytest; pytest.set_trace()", "if", "hasattr", "(", "self", ".", "model", ",", "'output_layers'", ")", ":", "# find corresponding output layers in CoreML model", "# assume output layers are not shared", "# Helper function to recursively extract output layers", "# even if the model has a layer which is a nested model", "def", "extract_output_layers", "(", "keras_model", ")", ":", "output_layers", "=", "[", "]", "for", "layer", "in", "keras_model", ".", "output_layers", ":", "if", "hasattr", "(", "layer", ",", "'output_layers'", ")", ":", "output_layers", ".", "extend", "(", "extract_output_layers", "(", "layer", ")", ")", "else", ":", "output_layers", ".", "append", "(", "layer", ")", "return", "output_layers", "for", "kl", "in", "extract_output_layers", "(", "self", ".", "model", ")", ":", "coreml_layers", "=", "self", ".", "get_coreml_layers", "(", "kl", ")", "if", "len", "(", "coreml_layers", ")", ">", "0", ":", "for", "cl", "in", "coreml_layers", ":", "self", ".", "output_layers", ".", "append", "(", "cl", ")", "elif", "len", "(", "self", ".", "model", ".", "outputs", ")", ">", "0", ":", "for", "model_output", "in", "self", ".", "model", ".", "outputs", ":", "for", "l", "in", "self", ".", "layer_list", ":", "k_layer", "=", "self", ".", "keras_layer_map", "[", "l", "]", "in_nodes", "=", "k_layer", ".", "_inbound_nodes", "if", "hasattr", "(", "k_layer", ",", "'_inbound_nodes'", ")", "else", "k_layer", ".", "inbound_nodes", "for", "idx", "in", "range", "(", "len", "(", "in_nodes", ")", ")", ":", "out_tensor", "=", "k_layer", ".", "get_output_at", "(", "idx", ")", "if", "out_tensor", "==", "model_output", "or", "(", "out_tensor", ".", "name", "in", "model_output", ".", "name", ")", ":", "self", ".", "output_layers", ".", "append", "(", "l", ")", "if", "len", "(", "self", ".", "output_layers", ")", "==", "0", ":", "raise", "ValueError", "(", "\"No outputs can be identified\"", ")" ]
Extract the ordering of output layers.
[ "Extract", "the", "ordering", "of", "output", "layers", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_topology2.py#L181-L216
train
apple/turicreate
src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_topology2.py
NetGraph._remove_layer_and_reconnect
def _remove_layer_and_reconnect(self, layer): """ Remove the layer, and reconnect each of its predecessor to each of its successor """ successors = self.get_successors(layer) predecessors = self.get_predecessors(layer) # remove layer's edges for succ in successors: self._remove_edge(layer, succ) for pred in predecessors: self._remove_edge(pred, layer) # connect predecessors and successors for pred in predecessors: for succ in successors: self._add_edge(pred, succ) # remove layer in the data structures self.layer_list.remove(layer) self.keras_layer_map.pop(layer) # re-assign input and output layers if layer happens to be an # input / output layer if layer in self.input_layers: idx = self.input_layers.index(layer) self.input_layers.pop(idx) for pred in predecessors: self.input_layers.insert(idx, pred) idx += 1 if layer in self.output_layers: idx = self.output_layers.index(layer) self.output_layers.pop(idx) for succ in successors: self.output_layers.insert(idx, succ) idx += 1
python
def _remove_layer_and_reconnect(self, layer): """ Remove the layer, and reconnect each of its predecessor to each of its successor """ successors = self.get_successors(layer) predecessors = self.get_predecessors(layer) # remove layer's edges for succ in successors: self._remove_edge(layer, succ) for pred in predecessors: self._remove_edge(pred, layer) # connect predecessors and successors for pred in predecessors: for succ in successors: self._add_edge(pred, succ) # remove layer in the data structures self.layer_list.remove(layer) self.keras_layer_map.pop(layer) # re-assign input and output layers if layer happens to be an # input / output layer if layer in self.input_layers: idx = self.input_layers.index(layer) self.input_layers.pop(idx) for pred in predecessors: self.input_layers.insert(idx, pred) idx += 1 if layer in self.output_layers: idx = self.output_layers.index(layer) self.output_layers.pop(idx) for succ in successors: self.output_layers.insert(idx, succ) idx += 1
[ "def", "_remove_layer_and_reconnect", "(", "self", ",", "layer", ")", ":", "successors", "=", "self", ".", "get_successors", "(", "layer", ")", "predecessors", "=", "self", ".", "get_predecessors", "(", "layer", ")", "# remove layer's edges", "for", "succ", "in", "successors", ":", "self", ".", "_remove_edge", "(", "layer", ",", "succ", ")", "for", "pred", "in", "predecessors", ":", "self", ".", "_remove_edge", "(", "pred", ",", "layer", ")", "# connect predecessors and successors", "for", "pred", "in", "predecessors", ":", "for", "succ", "in", "successors", ":", "self", ".", "_add_edge", "(", "pred", ",", "succ", ")", "# remove layer in the data structures", "self", ".", "layer_list", ".", "remove", "(", "layer", ")", "self", ".", "keras_layer_map", ".", "pop", "(", "layer", ")", "# re-assign input and output layers if layer happens to be an", "# input / output layer", "if", "layer", "in", "self", ".", "input_layers", ":", "idx", "=", "self", ".", "input_layers", ".", "index", "(", "layer", ")", "self", ".", "input_layers", ".", "pop", "(", "idx", ")", "for", "pred", "in", "predecessors", ":", "self", ".", "input_layers", ".", "insert", "(", "idx", ",", "pred", ")", "idx", "+=", "1", "if", "layer", "in", "self", ".", "output_layers", ":", "idx", "=", "self", ".", "output_layers", ".", "index", "(", "layer", ")", "self", ".", "output_layers", ".", "pop", "(", "idx", ")", "for", "succ", "in", "successors", ":", "self", ".", "output_layers", ".", "insert", "(", "idx", ",", "succ", ")", "idx", "+=", "1" ]
Remove the layer, and reconnect each of its predecessor to each of its successor
[ "Remove", "the", "layer", "and", "reconnect", "each", "of", "its", "predecessor", "to", "each", "of", "its", "successor" ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_topology2.py#L387-L421
train
apple/turicreate
src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_topology2.py
NetGraph.defuse_activation
def defuse_activation(self): """ Defuse the fused activation layers in the network. """ idx, nb_layers = 0, len(self.layer_list) while idx < nb_layers: layer = self.layer_list[idx] k_layer = self.keras_layer_map[layer] if (isinstance(k_layer, _keras.layers.TimeDistributed)): k_layer = k_layer.layer if (isinstance(k_layer, _keras.layers.Conv2D) or isinstance(k_layer, _keras.layers.Conv1D) or isinstance(k_layer, _keras.layers.SeparableConv2D) or isinstance(k_layer, _keras.layers.SeparableConv1D) or isinstance(k_layer, _keras.layers.Dense)): func_name = k_layer.activation.func_name if six.PY2 else \ k_layer.activation.__name__ if func_name != 'linear': # Create new layer new_layer = layer + '__activation__' new_keras_layer = _keras.layers.core.Activation(func_name) # insert new layer after it self._insert_layer_after(idx, new_layer, new_keras_layer) idx += 1 nb_layers += 1 idx += 1
python
def defuse_activation(self): """ Defuse the fused activation layers in the network. """ idx, nb_layers = 0, len(self.layer_list) while idx < nb_layers: layer = self.layer_list[idx] k_layer = self.keras_layer_map[layer] if (isinstance(k_layer, _keras.layers.TimeDistributed)): k_layer = k_layer.layer if (isinstance(k_layer, _keras.layers.Conv2D) or isinstance(k_layer, _keras.layers.Conv1D) or isinstance(k_layer, _keras.layers.SeparableConv2D) or isinstance(k_layer, _keras.layers.SeparableConv1D) or isinstance(k_layer, _keras.layers.Dense)): func_name = k_layer.activation.func_name if six.PY2 else \ k_layer.activation.__name__ if func_name != 'linear': # Create new layer new_layer = layer + '__activation__' new_keras_layer = _keras.layers.core.Activation(func_name) # insert new layer after it self._insert_layer_after(idx, new_layer, new_keras_layer) idx += 1 nb_layers += 1 idx += 1
[ "def", "defuse_activation", "(", "self", ")", ":", "idx", ",", "nb_layers", "=", "0", ",", "len", "(", "self", ".", "layer_list", ")", "while", "idx", "<", "nb_layers", ":", "layer", "=", "self", ".", "layer_list", "[", "idx", "]", "k_layer", "=", "self", ".", "keras_layer_map", "[", "layer", "]", "if", "(", "isinstance", "(", "k_layer", ",", "_keras", ".", "layers", ".", "TimeDistributed", ")", ")", ":", "k_layer", "=", "k_layer", ".", "layer", "if", "(", "isinstance", "(", "k_layer", ",", "_keras", ".", "layers", ".", "Conv2D", ")", "or", "isinstance", "(", "k_layer", ",", "_keras", ".", "layers", ".", "Conv1D", ")", "or", "isinstance", "(", "k_layer", ",", "_keras", ".", "layers", ".", "SeparableConv2D", ")", "or", "isinstance", "(", "k_layer", ",", "_keras", ".", "layers", ".", "SeparableConv1D", ")", "or", "isinstance", "(", "k_layer", ",", "_keras", ".", "layers", ".", "Dense", ")", ")", ":", "func_name", "=", "k_layer", ".", "activation", ".", "func_name", "if", "six", ".", "PY2", "else", "k_layer", ".", "activation", ".", "__name__", "if", "func_name", "!=", "'linear'", ":", "# Create new layer", "new_layer", "=", "layer", "+", "'__activation__'", "new_keras_layer", "=", "_keras", ".", "layers", ".", "core", ".", "Activation", "(", "func_name", ")", "# insert new layer after it", "self", ".", "_insert_layer_after", "(", "idx", ",", "new_layer", ",", "new_keras_layer", ")", "idx", "+=", "1", "nb_layers", "+=", "1", "idx", "+=", "1" ]
Defuse the fused activation layers in the network.
[ "Defuse", "the", "fused", "activation", "layers", "in", "the", "network", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_topology2.py#L498-L524
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray.date_range
def date_range(cls,start_time,end_time,freq): ''' Returns a new SArray that represents a fixed frequency datetime index. Parameters ---------- start_time : datetime.datetime Left bound for generating dates. end_time : datetime.datetime Right bound for generating dates. freq : datetime.timedelta Fixed frequency between two consecutive data points. Returns ------- out : SArray Examples -------- >>> import datetime as dt >>> start = dt.datetime(2013, 5, 7, 10, 4, 10) >>> end = dt.datetime(2013, 5, 10, 10, 4, 10) >>> sa = tc.SArray.date_range(start,end,dt.timedelta(1)) >>> print sa dtype: datetime Rows: 4 [datetime.datetime(2013, 5, 7, 10, 4, 10), datetime.datetime(2013, 5, 8, 10, 4, 10), datetime.datetime(2013, 5, 9, 10, 4, 10), datetime.datetime(2013, 5, 10, 10, 4, 10)] ''' if not isinstance(start_time,datetime.datetime): raise TypeError("The ``start_time`` argument must be from type datetime.datetime.") if not isinstance(end_time,datetime.datetime): raise TypeError("The ``end_time`` argument must be from type datetime.datetime.") if not isinstance(freq,datetime.timedelta): raise TypeError("The ``freq`` argument must be from type datetime.timedelta.") from .. import extensions return extensions.date_range(start_time,end_time,freq.total_seconds())
python
def date_range(cls,start_time,end_time,freq): ''' Returns a new SArray that represents a fixed frequency datetime index. Parameters ---------- start_time : datetime.datetime Left bound for generating dates. end_time : datetime.datetime Right bound for generating dates. freq : datetime.timedelta Fixed frequency between two consecutive data points. Returns ------- out : SArray Examples -------- >>> import datetime as dt >>> start = dt.datetime(2013, 5, 7, 10, 4, 10) >>> end = dt.datetime(2013, 5, 10, 10, 4, 10) >>> sa = tc.SArray.date_range(start,end,dt.timedelta(1)) >>> print sa dtype: datetime Rows: 4 [datetime.datetime(2013, 5, 7, 10, 4, 10), datetime.datetime(2013, 5, 8, 10, 4, 10), datetime.datetime(2013, 5, 9, 10, 4, 10), datetime.datetime(2013, 5, 10, 10, 4, 10)] ''' if not isinstance(start_time,datetime.datetime): raise TypeError("The ``start_time`` argument must be from type datetime.datetime.") if not isinstance(end_time,datetime.datetime): raise TypeError("The ``end_time`` argument must be from type datetime.datetime.") if not isinstance(freq,datetime.timedelta): raise TypeError("The ``freq`` argument must be from type datetime.timedelta.") from .. import extensions return extensions.date_range(start_time,end_time,freq.total_seconds())
[ "def", "date_range", "(", "cls", ",", "start_time", ",", "end_time", ",", "freq", ")", ":", "if", "not", "isinstance", "(", "start_time", ",", "datetime", ".", "datetime", ")", ":", "raise", "TypeError", "(", "\"The ``start_time`` argument must be from type datetime.datetime.\"", ")", "if", "not", "isinstance", "(", "end_time", ",", "datetime", ".", "datetime", ")", ":", "raise", "TypeError", "(", "\"The ``end_time`` argument must be from type datetime.datetime.\"", ")", "if", "not", "isinstance", "(", "freq", ",", "datetime", ".", "timedelta", ")", ":", "raise", "TypeError", "(", "\"The ``freq`` argument must be from type datetime.timedelta.\"", ")", "from", ".", ".", "import", "extensions", "return", "extensions", ".", "date_range", "(", "start_time", ",", "end_time", ",", "freq", ".", "total_seconds", "(", ")", ")" ]
Returns a new SArray that represents a fixed frequency datetime index. Parameters ---------- start_time : datetime.datetime Left bound for generating dates. end_time : datetime.datetime Right bound for generating dates. freq : datetime.timedelta Fixed frequency between two consecutive data points. Returns ------- out : SArray Examples -------- >>> import datetime as dt >>> start = dt.datetime(2013, 5, 7, 10, 4, 10) >>> end = dt.datetime(2013, 5, 10, 10, 4, 10) >>> sa = tc.SArray.date_range(start,end,dt.timedelta(1)) >>> print sa dtype: datetime Rows: 4 [datetime.datetime(2013, 5, 7, 10, 4, 10), datetime.datetime(2013, 5, 8, 10, 4, 10), datetime.datetime(2013, 5, 9, 10, 4, 10), datetime.datetime(2013, 5, 10, 10, 4, 10)]
[ "Returns", "a", "new", "SArray", "that", "represents", "a", "fixed", "frequency", "datetime", "index", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L431-L475
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray.from_const
def from_const(cls, value, size, dtype=type(None)): """ Constructs an SArray of size with a const value. Parameters ---------- value : [int | float | str | array.array | list | dict | datetime] The value to fill the SArray size : int The size of the SArray dtype : type The type of the SArray. If not specified, is automatically detected from the value. This should be specified if value=None since the actual type of the SArray can be anything. Examples -------- Construct an SArray consisting of 10 zeroes: >>> turicreate.SArray.from_const(0, 10) Construct an SArray consisting of 10 missing string values: >>> turicreate.SArray.from_const(None, 10, str) """ assert isinstance(size, (int, long)) and size >= 0, "size must be a positive int" if not isinstance(value, (type(None), int, float, str, array.array, list, dict, datetime.datetime)): raise TypeError('Cannot create sarray of value type %s' % str(type(value))) proxy = UnitySArrayProxy() proxy.load_from_const(value, size, dtype) return cls(_proxy=proxy)
python
def from_const(cls, value, size, dtype=type(None)): """ Constructs an SArray of size with a const value. Parameters ---------- value : [int | float | str | array.array | list | dict | datetime] The value to fill the SArray size : int The size of the SArray dtype : type The type of the SArray. If not specified, is automatically detected from the value. This should be specified if value=None since the actual type of the SArray can be anything. Examples -------- Construct an SArray consisting of 10 zeroes: >>> turicreate.SArray.from_const(0, 10) Construct an SArray consisting of 10 missing string values: >>> turicreate.SArray.from_const(None, 10, str) """ assert isinstance(size, (int, long)) and size >= 0, "size must be a positive int" if not isinstance(value, (type(None), int, float, str, array.array, list, dict, datetime.datetime)): raise TypeError('Cannot create sarray of value type %s' % str(type(value))) proxy = UnitySArrayProxy() proxy.load_from_const(value, size, dtype) return cls(_proxy=proxy)
[ "def", "from_const", "(", "cls", ",", "value", ",", "size", ",", "dtype", "=", "type", "(", "None", ")", ")", ":", "assert", "isinstance", "(", "size", ",", "(", "int", ",", "long", ")", ")", "and", "size", ">=", "0", ",", "\"size must be a positive int\"", "if", "not", "isinstance", "(", "value", ",", "(", "type", "(", "None", ")", ",", "int", ",", "float", ",", "str", ",", "array", ".", "array", ",", "list", ",", "dict", ",", "datetime", ".", "datetime", ")", ")", ":", "raise", "TypeError", "(", "'Cannot create sarray of value type %s'", "%", "str", "(", "type", "(", "value", ")", ")", ")", "proxy", "=", "UnitySArrayProxy", "(", ")", "proxy", ".", "load_from_const", "(", "value", ",", "size", ",", "dtype", ")", "return", "cls", "(", "_proxy", "=", "proxy", ")" ]
Constructs an SArray of size with a const value. Parameters ---------- value : [int | float | str | array.array | list | dict | datetime] The value to fill the SArray size : int The size of the SArray dtype : type The type of the SArray. If not specified, is automatically detected from the value. This should be specified if value=None since the actual type of the SArray can be anything. Examples -------- Construct an SArray consisting of 10 zeroes: >>> turicreate.SArray.from_const(0, 10) Construct an SArray consisting of 10 missing string values: >>> turicreate.SArray.from_const(None, 10, str)
[ "Constructs", "an", "SArray", "of", "size", "with", "a", "const", "value", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L478-L508
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray.from_sequence
def from_sequence(cls, *args): """ from_sequence(start=0, stop) Create an SArray from sequence .. sourcecode:: python Construct an SArray of integer values from 0 to 999 >>> tc.SArray.from_sequence(1000) This is equivalent, but more efficient than: >>> tc.SArray(range(1000)) Construct an SArray of integer values from 10 to 999 >>> tc.SArray.from_sequence(10, 1000) This is equivalent, but more efficient than: >>> tc.SArray(range(10, 1000)) Parameters ---------- start : int, optional The start of the sequence. The sequence will contain this value. stop : int The end of the sequence. The sequence will not contain this value. """ start = None stop = None # fill with args. This checks for from_sequence(100), from_sequence(10,100) if len(args) == 1: stop = args[0] elif len(args) == 2: start = args[0] stop = args[1] if stop is None and start is None: raise TypeError("from_sequence expects at least 1 argument. got 0") elif start is None: return _create_sequential_sarray(stop) else: size = stop - start # this matches the behavior of range # i.e. range(100,10) just returns an empty array if (size < 0): size = 0 return _create_sequential_sarray(size, start)
python
def from_sequence(cls, *args): """ from_sequence(start=0, stop) Create an SArray from sequence .. sourcecode:: python Construct an SArray of integer values from 0 to 999 >>> tc.SArray.from_sequence(1000) This is equivalent, but more efficient than: >>> tc.SArray(range(1000)) Construct an SArray of integer values from 10 to 999 >>> tc.SArray.from_sequence(10, 1000) This is equivalent, but more efficient than: >>> tc.SArray(range(10, 1000)) Parameters ---------- start : int, optional The start of the sequence. The sequence will contain this value. stop : int The end of the sequence. The sequence will not contain this value. """ start = None stop = None # fill with args. This checks for from_sequence(100), from_sequence(10,100) if len(args) == 1: stop = args[0] elif len(args) == 2: start = args[0] stop = args[1] if stop is None and start is None: raise TypeError("from_sequence expects at least 1 argument. got 0") elif start is None: return _create_sequential_sarray(stop) else: size = stop - start # this matches the behavior of range # i.e. range(100,10) just returns an empty array if (size < 0): size = 0 return _create_sequential_sarray(size, start)
[ "def", "from_sequence", "(", "cls", ",", "*", "args", ")", ":", "start", "=", "None", "stop", "=", "None", "# fill with args. This checks for from_sequence(100), from_sequence(10,100)", "if", "len", "(", "args", ")", "==", "1", ":", "stop", "=", "args", "[", "0", "]", "elif", "len", "(", "args", ")", "==", "2", ":", "start", "=", "args", "[", "0", "]", "stop", "=", "args", "[", "1", "]", "if", "stop", "is", "None", "and", "start", "is", "None", ":", "raise", "TypeError", "(", "\"from_sequence expects at least 1 argument. got 0\"", ")", "elif", "start", "is", "None", ":", "return", "_create_sequential_sarray", "(", "stop", ")", "else", ":", "size", "=", "stop", "-", "start", "# this matches the behavior of range", "# i.e. range(100,10) just returns an empty array", "if", "(", "size", "<", "0", ")", ":", "size", "=", "0", "return", "_create_sequential_sarray", "(", "size", ",", "start", ")" ]
from_sequence(start=0, stop) Create an SArray from sequence .. sourcecode:: python Construct an SArray of integer values from 0 to 999 >>> tc.SArray.from_sequence(1000) This is equivalent, but more efficient than: >>> tc.SArray(range(1000)) Construct an SArray of integer values from 10 to 999 >>> tc.SArray.from_sequence(10, 1000) This is equivalent, but more efficient than: >>> tc.SArray(range(10, 1000)) Parameters ---------- start : int, optional The start of the sequence. The sequence will contain this value. stop : int The end of the sequence. The sequence will not contain this value.
[ "from_sequence", "(", "start", "=", "0", "stop", ")" ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L511-L563
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray.read_json
def read_json(cls, filename): """ Construct an SArray from a json file or glob of json files. The json file must contain a list of dictionaries. The returned SArray type will be of dict type Parameters ---------- filename : str The filename or glob to load into an SArray. Examples -------- Construct an SArray from a local JSON file named 'data.json': >>> turicreate.SArray.read_json('/data/data.json') Construct an SArray from all JSON files /data/data*.json >>> turicreate.SArray.read_json('/data/data*.json') """ proxy = UnitySArrayProxy() proxy.load_from_json_record_files(_make_internal_url(filename)) return cls(_proxy = proxy)
python
def read_json(cls, filename): """ Construct an SArray from a json file or glob of json files. The json file must contain a list of dictionaries. The returned SArray type will be of dict type Parameters ---------- filename : str The filename or glob to load into an SArray. Examples -------- Construct an SArray from a local JSON file named 'data.json': >>> turicreate.SArray.read_json('/data/data.json') Construct an SArray from all JSON files /data/data*.json >>> turicreate.SArray.read_json('/data/data*.json') """ proxy = UnitySArrayProxy() proxy.load_from_json_record_files(_make_internal_url(filename)) return cls(_proxy = proxy)
[ "def", "read_json", "(", "cls", ",", "filename", ")", ":", "proxy", "=", "UnitySArrayProxy", "(", ")", "proxy", ".", "load_from_json_record_files", "(", "_make_internal_url", "(", "filename", ")", ")", "return", "cls", "(", "_proxy", "=", "proxy", ")" ]
Construct an SArray from a json file or glob of json files. The json file must contain a list of dictionaries. The returned SArray type will be of dict type Parameters ---------- filename : str The filename or glob to load into an SArray. Examples -------- Construct an SArray from a local JSON file named 'data.json': >>> turicreate.SArray.read_json('/data/data.json') Construct an SArray from all JSON files /data/data*.json >>> turicreate.SArray.read_json('/data/data*.json')
[ "Construct", "an", "SArray", "from", "a", "json", "file", "or", "glob", "of", "json", "files", ".", "The", "json", "file", "must", "contain", "a", "list", "of", "dictionaries", ".", "The", "returned", "SArray", "type", "will", "be", "of", "dict", "type" ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L566-L590
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray.where
def where(cls, condition, istrue, isfalse, dtype=None): """ Selects elements from either istrue or isfalse depending on the value of the condition SArray. Parameters ---------- condition : SArray An SArray of values such that for each value, if non-zero, yields a value from istrue, otherwise from isfalse. istrue : SArray or constant The elements selected if condition is true. If istrue is an SArray, this must be of the same length as condition. isfalse : SArray or constant The elements selected if condition is false. If istrue is an SArray, this must be of the same length as condition. dtype : type The type of result SArray. This is required if both istrue and isfalse are constants of ambiguous types. Examples -------- Returns an SArray with the same values as g with values above 10 clipped to 10 >>> g = SArray([6,7,8,9,10,11,12,13]) >>> SArray.where(g > 10, 10, g) dtype: int Rows: 8 [6, 7, 8, 9, 10, 10, 10, 10] Returns an SArray with the same values as g with values below 10 clipped to 10 >>> SArray.where(g > 10, g, 10) dtype: int Rows: 8 [10, 10, 10, 10, 10, 11, 12, 13] Returns an SArray with the same values of g with all values == 1 replaced by None >>> g = SArray([1,2,3,4,1,2,3,4]) >>> SArray.where(g == 1, None, g) dtype: int Rows: 8 [None, 2, 3, 4, None, 2, 3, 4] Returns an SArray with the same values of g, but with each missing value replaced by its corresponding element in replace_none >>> g = SArray([1,2,None,None]) >>> replace_none = SArray([3,3,2,2]) >>> SArray.where(g != None, g, replace_none) dtype: int Rows: 4 [1, 2, 2, 2] """ true_is_sarray = isinstance(istrue, SArray) false_is_sarray = isinstance(isfalse, SArray) if not true_is_sarray and false_is_sarray: istrue = cls(_proxy=condition.__proxy__.to_const(istrue, isfalse.dtype)) if true_is_sarray and not false_is_sarray: isfalse = cls(_proxy=condition.__proxy__.to_const(isfalse, istrue.dtype)) if not true_is_sarray and not false_is_sarray: if dtype is None: if istrue is None: dtype = type(isfalse) elif isfalse is None: dtype = type(istrue) elif type(istrue) != type(isfalse): raise TypeError("true and false inputs are of different types") elif type(istrue) == type(isfalse): dtype = type(istrue) if dtype is None: raise TypeError("Both true and false are None. Resultant type cannot be inferred.") istrue = cls(_proxy=condition.__proxy__.to_const(istrue, dtype)) isfalse = cls(_proxy=condition.__proxy__.to_const(isfalse, dtype)) return cls(_proxy=condition.__proxy__.ternary_operator(istrue.__proxy__, isfalse.__proxy__))
python
def where(cls, condition, istrue, isfalse, dtype=None): """ Selects elements from either istrue or isfalse depending on the value of the condition SArray. Parameters ---------- condition : SArray An SArray of values such that for each value, if non-zero, yields a value from istrue, otherwise from isfalse. istrue : SArray or constant The elements selected if condition is true. If istrue is an SArray, this must be of the same length as condition. isfalse : SArray or constant The elements selected if condition is false. If istrue is an SArray, this must be of the same length as condition. dtype : type The type of result SArray. This is required if both istrue and isfalse are constants of ambiguous types. Examples -------- Returns an SArray with the same values as g with values above 10 clipped to 10 >>> g = SArray([6,7,8,9,10,11,12,13]) >>> SArray.where(g > 10, 10, g) dtype: int Rows: 8 [6, 7, 8, 9, 10, 10, 10, 10] Returns an SArray with the same values as g with values below 10 clipped to 10 >>> SArray.where(g > 10, g, 10) dtype: int Rows: 8 [10, 10, 10, 10, 10, 11, 12, 13] Returns an SArray with the same values of g with all values == 1 replaced by None >>> g = SArray([1,2,3,4,1,2,3,4]) >>> SArray.where(g == 1, None, g) dtype: int Rows: 8 [None, 2, 3, 4, None, 2, 3, 4] Returns an SArray with the same values of g, but with each missing value replaced by its corresponding element in replace_none >>> g = SArray([1,2,None,None]) >>> replace_none = SArray([3,3,2,2]) >>> SArray.where(g != None, g, replace_none) dtype: int Rows: 4 [1, 2, 2, 2] """ true_is_sarray = isinstance(istrue, SArray) false_is_sarray = isinstance(isfalse, SArray) if not true_is_sarray and false_is_sarray: istrue = cls(_proxy=condition.__proxy__.to_const(istrue, isfalse.dtype)) if true_is_sarray and not false_is_sarray: isfalse = cls(_proxy=condition.__proxy__.to_const(isfalse, istrue.dtype)) if not true_is_sarray and not false_is_sarray: if dtype is None: if istrue is None: dtype = type(isfalse) elif isfalse is None: dtype = type(istrue) elif type(istrue) != type(isfalse): raise TypeError("true and false inputs are of different types") elif type(istrue) == type(isfalse): dtype = type(istrue) if dtype is None: raise TypeError("Both true and false are None. Resultant type cannot be inferred.") istrue = cls(_proxy=condition.__proxy__.to_const(istrue, dtype)) isfalse = cls(_proxy=condition.__proxy__.to_const(isfalse, dtype)) return cls(_proxy=condition.__proxy__.ternary_operator(istrue.__proxy__, isfalse.__proxy__))
[ "def", "where", "(", "cls", ",", "condition", ",", "istrue", ",", "isfalse", ",", "dtype", "=", "None", ")", ":", "true_is_sarray", "=", "isinstance", "(", "istrue", ",", "SArray", ")", "false_is_sarray", "=", "isinstance", "(", "isfalse", ",", "SArray", ")", "if", "not", "true_is_sarray", "and", "false_is_sarray", ":", "istrue", "=", "cls", "(", "_proxy", "=", "condition", ".", "__proxy__", ".", "to_const", "(", "istrue", ",", "isfalse", ".", "dtype", ")", ")", "if", "true_is_sarray", "and", "not", "false_is_sarray", ":", "isfalse", "=", "cls", "(", "_proxy", "=", "condition", ".", "__proxy__", ".", "to_const", "(", "isfalse", ",", "istrue", ".", "dtype", ")", ")", "if", "not", "true_is_sarray", "and", "not", "false_is_sarray", ":", "if", "dtype", "is", "None", ":", "if", "istrue", "is", "None", ":", "dtype", "=", "type", "(", "isfalse", ")", "elif", "isfalse", "is", "None", ":", "dtype", "=", "type", "(", "istrue", ")", "elif", "type", "(", "istrue", ")", "!=", "type", "(", "isfalse", ")", ":", "raise", "TypeError", "(", "\"true and false inputs are of different types\"", ")", "elif", "type", "(", "istrue", ")", "==", "type", "(", "isfalse", ")", ":", "dtype", "=", "type", "(", "istrue", ")", "if", "dtype", "is", "None", ":", "raise", "TypeError", "(", "\"Both true and false are None. Resultant type cannot be inferred.\"", ")", "istrue", "=", "cls", "(", "_proxy", "=", "condition", ".", "__proxy__", ".", "to_const", "(", "istrue", ",", "dtype", ")", ")", "isfalse", "=", "cls", "(", "_proxy", "=", "condition", ".", "__proxy__", ".", "to_const", "(", "isfalse", ",", "dtype", ")", ")", "return", "cls", "(", "_proxy", "=", "condition", ".", "__proxy__", ".", "ternary_operator", "(", "istrue", ".", "__proxy__", ",", "isfalse", ".", "__proxy__", ")", ")" ]
Selects elements from either istrue or isfalse depending on the value of the condition SArray. Parameters ---------- condition : SArray An SArray of values such that for each value, if non-zero, yields a value from istrue, otherwise from isfalse. istrue : SArray or constant The elements selected if condition is true. If istrue is an SArray, this must be of the same length as condition. isfalse : SArray or constant The elements selected if condition is false. If istrue is an SArray, this must be of the same length as condition. dtype : type The type of result SArray. This is required if both istrue and isfalse are constants of ambiguous types. Examples -------- Returns an SArray with the same values as g with values above 10 clipped to 10 >>> g = SArray([6,7,8,9,10,11,12,13]) >>> SArray.where(g > 10, 10, g) dtype: int Rows: 8 [6, 7, 8, 9, 10, 10, 10, 10] Returns an SArray with the same values as g with values below 10 clipped to 10 >>> SArray.where(g > 10, g, 10) dtype: int Rows: 8 [10, 10, 10, 10, 10, 11, 12, 13] Returns an SArray with the same values of g with all values == 1 replaced by None >>> g = SArray([1,2,3,4,1,2,3,4]) >>> SArray.where(g == 1, None, g) dtype: int Rows: 8 [None, 2, 3, 4, None, 2, 3, 4] Returns an SArray with the same values of g, but with each missing value replaced by its corresponding element in replace_none >>> g = SArray([1,2,None,None]) >>> replace_none = SArray([3,3,2,2]) >>> SArray.where(g != None, g, replace_none) dtype: int Rows: 4 [1, 2, 2, 2]
[ "Selects", "elements", "from", "either", "istrue", "or", "isfalse", "depending", "on", "the", "value", "of", "the", "condition", "SArray", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L593-L675
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray.save
def save(self, filename, format=None): """ Saves the SArray to file. The saved SArray will be in a directory named with the `targetfile` parameter. Parameters ---------- filename : string A local path or a remote URL. If format is 'text', it will be saved as a text file. If format is 'binary', a directory will be created at the location which will contain the SArray. format : {'binary', 'text', 'csv'}, optional Format in which to save the SFrame. Binary saved SArrays can be loaded much faster and without any format conversion losses. 'text' and 'csv' are synonymous: Each SArray row will be written as a single line in an output text file. If not given, will try to infer the format from filename given. If file name ends with 'csv', 'txt' or '.csv.gz', then save as 'csv' format, otherwise save as 'binary' format. """ from .sframe import SFrame as _SFrame if format is None: if filename.endswith(('.csv', '.csv.gz', 'txt')): format = 'text' else: format = 'binary' if format == 'binary': with cython_context(): self.__proxy__.save(_make_internal_url(filename)) elif format == 'text' or format == 'csv': sf = _SFrame({'X1':self}) with cython_context(): sf.__proxy__.save_as_csv(_make_internal_url(filename), {'header':False}) else: raise ValueError("Unsupported format: {}".format(format))
python
def save(self, filename, format=None): """ Saves the SArray to file. The saved SArray will be in a directory named with the `targetfile` parameter. Parameters ---------- filename : string A local path or a remote URL. If format is 'text', it will be saved as a text file. If format is 'binary', a directory will be created at the location which will contain the SArray. format : {'binary', 'text', 'csv'}, optional Format in which to save the SFrame. Binary saved SArrays can be loaded much faster and without any format conversion losses. 'text' and 'csv' are synonymous: Each SArray row will be written as a single line in an output text file. If not given, will try to infer the format from filename given. If file name ends with 'csv', 'txt' or '.csv.gz', then save as 'csv' format, otherwise save as 'binary' format. """ from .sframe import SFrame as _SFrame if format is None: if filename.endswith(('.csv', '.csv.gz', 'txt')): format = 'text' else: format = 'binary' if format == 'binary': with cython_context(): self.__proxy__.save(_make_internal_url(filename)) elif format == 'text' or format == 'csv': sf = _SFrame({'X1':self}) with cython_context(): sf.__proxy__.save_as_csv(_make_internal_url(filename), {'header':False}) else: raise ValueError("Unsupported format: {}".format(format))
[ "def", "save", "(", "self", ",", "filename", ",", "format", "=", "None", ")", ":", "from", ".", "sframe", "import", "SFrame", "as", "_SFrame", "if", "format", "is", "None", ":", "if", "filename", ".", "endswith", "(", "(", "'.csv'", ",", "'.csv.gz'", ",", "'txt'", ")", ")", ":", "format", "=", "'text'", "else", ":", "format", "=", "'binary'", "if", "format", "==", "'binary'", ":", "with", "cython_context", "(", ")", ":", "self", ".", "__proxy__", ".", "save", "(", "_make_internal_url", "(", "filename", ")", ")", "elif", "format", "==", "'text'", "or", "format", "==", "'csv'", ":", "sf", "=", "_SFrame", "(", "{", "'X1'", ":", "self", "}", ")", "with", "cython_context", "(", ")", ":", "sf", ".", "__proxy__", ".", "save_as_csv", "(", "_make_internal_url", "(", "filename", ")", ",", "{", "'header'", ":", "False", "}", ")", "else", ":", "raise", "ValueError", "(", "\"Unsupported format: {}\"", ".", "format", "(", "format", ")", ")" ]
Saves the SArray to file. The saved SArray will be in a directory named with the `targetfile` parameter. Parameters ---------- filename : string A local path or a remote URL. If format is 'text', it will be saved as a text file. If format is 'binary', a directory will be created at the location which will contain the SArray. format : {'binary', 'text', 'csv'}, optional Format in which to save the SFrame. Binary saved SArrays can be loaded much faster and without any format conversion losses. 'text' and 'csv' are synonymous: Each SArray row will be written as a single line in an output text file. If not given, will try to infer the format from filename given. If file name ends with 'csv', 'txt' or '.csv.gz', then save as 'csv' format, otherwise save as 'binary' format.
[ "Saves", "the", "SArray", "to", "file", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L705-L743
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray.vector_slice
def vector_slice(self, start, end=None): """ If this SArray contains vectors or lists, this returns a new SArray containing each individual element sliced, between start and end (exclusive). Parameters ---------- start : int The start position of the slice. end : int, optional. The end position of the slice. Note that the end position is NOT included in the slice. Thus a g.vector_slice(1,3) will extract entries in position 1 and 2. If end is not specified, the return array will contain only one element, the element at the start position. Returns ------- out : SArray Each individual vector sliced according to the arguments. Examples -------- If g is a vector of floats: >>> g = SArray([[1,2,3],[2,3,4]]) >>> g dtype: array Rows: 2 [array('d', [1.0, 2.0, 3.0]), array('d', [2.0, 3.0, 4.0])] >>> g.vector_slice(0) # extracts the first element of each vector dtype: float Rows: 2 [1.0, 2.0] >>> g.vector_slice(0, 2) # extracts the first two elements of each vector dtype: array.array Rows: 2 [array('d', [1.0, 2.0]), array('d', [2.0, 3.0])] If a vector cannot be sliced, the result will be None: >>> g = SArray([[1],[1,2],[1,2,3]]) >>> g dtype: array.array Rows: 3 [array('d', [1.0]), array('d', [1.0, 2.0]), array('d', [1.0, 2.0, 3.0])] >>> g.vector_slice(2) dtype: float Rows: 3 [None, None, 3.0] >>> g.vector_slice(0,2) dtype: list Rows: 3 [None, array('d', [1.0, 2.0]), array('d', [1.0, 2.0])] If g is a vector of mixed types (float, int, str, array, list, etc.): >>> g = SArray([['a',1,1.0],['b',2,2.0]]) >>> g dtype: list Rows: 2 [['a', 1, 1.0], ['b', 2, 2.0]] >>> g.vector_slice(0) # extracts the first element of each vector dtype: list Rows: 2 [['a'], ['b']] """ if (self.dtype != array.array) and (self.dtype != list): raise RuntimeError("Only Vector type can be sliced") if end is None: end = start + 1 with cython_context(): return SArray(_proxy=self.__proxy__.vector_slice(start, end))
python
def vector_slice(self, start, end=None): """ If this SArray contains vectors or lists, this returns a new SArray containing each individual element sliced, between start and end (exclusive). Parameters ---------- start : int The start position of the slice. end : int, optional. The end position of the slice. Note that the end position is NOT included in the slice. Thus a g.vector_slice(1,3) will extract entries in position 1 and 2. If end is not specified, the return array will contain only one element, the element at the start position. Returns ------- out : SArray Each individual vector sliced according to the arguments. Examples -------- If g is a vector of floats: >>> g = SArray([[1,2,3],[2,3,4]]) >>> g dtype: array Rows: 2 [array('d', [1.0, 2.0, 3.0]), array('d', [2.0, 3.0, 4.0])] >>> g.vector_slice(0) # extracts the first element of each vector dtype: float Rows: 2 [1.0, 2.0] >>> g.vector_slice(0, 2) # extracts the first two elements of each vector dtype: array.array Rows: 2 [array('d', [1.0, 2.0]), array('d', [2.0, 3.0])] If a vector cannot be sliced, the result will be None: >>> g = SArray([[1],[1,2],[1,2,3]]) >>> g dtype: array.array Rows: 3 [array('d', [1.0]), array('d', [1.0, 2.0]), array('d', [1.0, 2.0, 3.0])] >>> g.vector_slice(2) dtype: float Rows: 3 [None, None, 3.0] >>> g.vector_slice(0,2) dtype: list Rows: 3 [None, array('d', [1.0, 2.0]), array('d', [1.0, 2.0])] If g is a vector of mixed types (float, int, str, array, list, etc.): >>> g = SArray([['a',1,1.0],['b',2,2.0]]) >>> g dtype: list Rows: 2 [['a', 1, 1.0], ['b', 2, 2.0]] >>> g.vector_slice(0) # extracts the first element of each vector dtype: list Rows: 2 [['a'], ['b']] """ if (self.dtype != array.array) and (self.dtype != list): raise RuntimeError("Only Vector type can be sliced") if end is None: end = start + 1 with cython_context(): return SArray(_proxy=self.__proxy__.vector_slice(start, end))
[ "def", "vector_slice", "(", "self", ",", "start", ",", "end", "=", "None", ")", ":", "if", "(", "self", ".", "dtype", "!=", "array", ".", "array", ")", "and", "(", "self", ".", "dtype", "!=", "list", ")", ":", "raise", "RuntimeError", "(", "\"Only Vector type can be sliced\"", ")", "if", "end", "is", "None", ":", "end", "=", "start", "+", "1", "with", "cython_context", "(", ")", ":", "return", "SArray", "(", "_proxy", "=", "self", ".", "__proxy__", ".", "vector_slice", "(", "start", ",", "end", ")", ")" ]
If this SArray contains vectors or lists, this returns a new SArray containing each individual element sliced, between start and end (exclusive). Parameters ---------- start : int The start position of the slice. end : int, optional. The end position of the slice. Note that the end position is NOT included in the slice. Thus a g.vector_slice(1,3) will extract entries in position 1 and 2. If end is not specified, the return array will contain only one element, the element at the start position. Returns ------- out : SArray Each individual vector sliced according to the arguments. Examples -------- If g is a vector of floats: >>> g = SArray([[1,2,3],[2,3,4]]) >>> g dtype: array Rows: 2 [array('d', [1.0, 2.0, 3.0]), array('d', [2.0, 3.0, 4.0])] >>> g.vector_slice(0) # extracts the first element of each vector dtype: float Rows: 2 [1.0, 2.0] >>> g.vector_slice(0, 2) # extracts the first two elements of each vector dtype: array.array Rows: 2 [array('d', [1.0, 2.0]), array('d', [2.0, 3.0])] If a vector cannot be sliced, the result will be None: >>> g = SArray([[1],[1,2],[1,2,3]]) >>> g dtype: array.array Rows: 3 [array('d', [1.0]), array('d', [1.0, 2.0]), array('d', [1.0, 2.0, 3.0])] >>> g.vector_slice(2) dtype: float Rows: 3 [None, None, 3.0] >>> g.vector_slice(0,2) dtype: list Rows: 3 [None, array('d', [1.0, 2.0]), array('d', [1.0, 2.0])] If g is a vector of mixed types (float, int, str, array, list, etc.): >>> g = SArray([['a',1,1.0],['b',2,2.0]]) >>> g dtype: list Rows: 2 [['a', 1, 1.0], ['b', 2, 2.0]] >>> g.vector_slice(0) # extracts the first element of each vector dtype: list Rows: 2 [['a'], ['b']]
[ "If", "this", "SArray", "contains", "vectors", "or", "lists", "this", "returns", "a", "new", "SArray", "containing", "each", "individual", "element", "sliced", "between", "start", "and", "end", "(", "exclusive", ")", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L1370-L1451
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray.element_slice
def element_slice(self, start=None, stop=None, step=None): """ This returns an SArray with each element sliced accordingly to the slice specified. This is conceptually equivalent to: >>> g.apply(lambda x: x[start:step:stop]) The SArray must be of type list, vector, or string. For instance: >>> g = SArray(["abcdef","qwerty"]) >>> g.element_slice(start=0, stop=2) dtype: str Rows: 2 ["ab", "qw"] >>> g.element_slice(3,-1) dtype: str Rows: 2 ["de", "rt"] >>> g.element_slice(3) dtype: str Rows: 2 ["def", "rty"] >>> g = SArray([[1,2,3], [4,5,6]]) >>> g.element_slice(0, 1) dtype: str Rows: 2 [[1], [4]] Parameters ---------- start : int or None (default) The start position of the slice stop: int or None (default) The stop position of the slice step: int or None (default) The step size of the slice Returns ------- out : SArray Each individual vector/string/list sliced according to the arguments. """ if self.dtype not in [str, array.array, list]: raise TypeError("SArray must contain strings, arrays or lists") with cython_context(): return SArray(_proxy=self.__proxy__.subslice(start, step, stop))
python
def element_slice(self, start=None, stop=None, step=None): """ This returns an SArray with each element sliced accordingly to the slice specified. This is conceptually equivalent to: >>> g.apply(lambda x: x[start:step:stop]) The SArray must be of type list, vector, or string. For instance: >>> g = SArray(["abcdef","qwerty"]) >>> g.element_slice(start=0, stop=2) dtype: str Rows: 2 ["ab", "qw"] >>> g.element_slice(3,-1) dtype: str Rows: 2 ["de", "rt"] >>> g.element_slice(3) dtype: str Rows: 2 ["def", "rty"] >>> g = SArray([[1,2,3], [4,5,6]]) >>> g.element_slice(0, 1) dtype: str Rows: 2 [[1], [4]] Parameters ---------- start : int or None (default) The start position of the slice stop: int or None (default) The stop position of the slice step: int or None (default) The step size of the slice Returns ------- out : SArray Each individual vector/string/list sliced according to the arguments. """ if self.dtype not in [str, array.array, list]: raise TypeError("SArray must contain strings, arrays or lists") with cython_context(): return SArray(_proxy=self.__proxy__.subslice(start, step, stop))
[ "def", "element_slice", "(", "self", ",", "start", "=", "None", ",", "stop", "=", "None", ",", "step", "=", "None", ")", ":", "if", "self", ".", "dtype", "not", "in", "[", "str", ",", "array", ".", "array", ",", "list", "]", ":", "raise", "TypeError", "(", "\"SArray must contain strings, arrays or lists\"", ")", "with", "cython_context", "(", ")", ":", "return", "SArray", "(", "_proxy", "=", "self", ".", "__proxy__", ".", "subslice", "(", "start", ",", "step", ",", "stop", ")", ")" ]
This returns an SArray with each element sliced accordingly to the slice specified. This is conceptually equivalent to: >>> g.apply(lambda x: x[start:step:stop]) The SArray must be of type list, vector, or string. For instance: >>> g = SArray(["abcdef","qwerty"]) >>> g.element_slice(start=0, stop=2) dtype: str Rows: 2 ["ab", "qw"] >>> g.element_slice(3,-1) dtype: str Rows: 2 ["de", "rt"] >>> g.element_slice(3) dtype: str Rows: 2 ["def", "rty"] >>> g = SArray([[1,2,3], [4,5,6]]) >>> g.element_slice(0, 1) dtype: str Rows: 2 [[1], [4]] Parameters ---------- start : int or None (default) The start position of the slice stop: int or None (default) The stop position of the slice step: int or None (default) The step size of the slice Returns ------- out : SArray Each individual vector/string/list sliced according to the arguments.
[ "This", "returns", "an", "SArray", "with", "each", "element", "sliced", "accordingly", "to", "the", "slice", "specified", ".", "This", "is", "conceptually", "equivalent", "to", ":" ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L1453-L1504
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray._count_words
def _count_words(self, to_lower=True, delimiters=["\r", "\v", "\n", "\f", "\t", " "]): """ This returns an SArray with, for each input string, a dict from the unique, delimited substrings to their number of occurrences within the original string. The SArray must be of type string. ..WARNING:: This function is deprecated, and will be removed in future versions of Turi Create. Please use the `text_analytics.count_words` function instead. Parameters ---------- to_lower : bool, optional "to_lower" indicates whether to map the input strings to lower case before counts delimiters: list[string], optional "delimiters" is a list of which characters to delimit on to find tokens Returns ------- out : SArray for each input string, a dict from the unique, delimited substrings to their number of occurrences within the original string. Examples -------- >>> sa = turicreate.SArray(["The quick brown fox jumps.", "Word word WORD, word!!!word"]) >>> sa._count_words() dtype: dict Rows: 2 [{'quick': 1, 'brown': 1, 'jumps': 1, 'fox': 1, 'the': 1}, {'word': 2, 'word,': 1, 'word!!!word': 1}] """ if (self.dtype != str): raise TypeError("Only SArray of string type is supported for counting bag of words") if (not all([len(delim) == 1 for delim in delimiters])): raise ValueError("Delimiters must be single-character strings") # construct options, will extend over time options = dict() options["to_lower"] = to_lower == True # defaults to std::isspace whitespace delimiters if no others passed in options["delimiters"] = delimiters with cython_context(): return SArray(_proxy=self.__proxy__.count_bag_of_words(options))
python
def _count_words(self, to_lower=True, delimiters=["\r", "\v", "\n", "\f", "\t", " "]): """ This returns an SArray with, for each input string, a dict from the unique, delimited substrings to their number of occurrences within the original string. The SArray must be of type string. ..WARNING:: This function is deprecated, and will be removed in future versions of Turi Create. Please use the `text_analytics.count_words` function instead. Parameters ---------- to_lower : bool, optional "to_lower" indicates whether to map the input strings to lower case before counts delimiters: list[string], optional "delimiters" is a list of which characters to delimit on to find tokens Returns ------- out : SArray for each input string, a dict from the unique, delimited substrings to their number of occurrences within the original string. Examples -------- >>> sa = turicreate.SArray(["The quick brown fox jumps.", "Word word WORD, word!!!word"]) >>> sa._count_words() dtype: dict Rows: 2 [{'quick': 1, 'brown': 1, 'jumps': 1, 'fox': 1, 'the': 1}, {'word': 2, 'word,': 1, 'word!!!word': 1}] """ if (self.dtype != str): raise TypeError("Only SArray of string type is supported for counting bag of words") if (not all([len(delim) == 1 for delim in delimiters])): raise ValueError("Delimiters must be single-character strings") # construct options, will extend over time options = dict() options["to_lower"] = to_lower == True # defaults to std::isspace whitespace delimiters if no others passed in options["delimiters"] = delimiters with cython_context(): return SArray(_proxy=self.__proxy__.count_bag_of_words(options))
[ "def", "_count_words", "(", "self", ",", "to_lower", "=", "True", ",", "delimiters", "=", "[", "\"\\r\"", ",", "\"\\v\"", ",", "\"\\n\"", ",", "\"\\f\"", ",", "\"\\t\"", ",", "\" \"", "]", ")", ":", "if", "(", "self", ".", "dtype", "!=", "str", ")", ":", "raise", "TypeError", "(", "\"Only SArray of string type is supported for counting bag of words\"", ")", "if", "(", "not", "all", "(", "[", "len", "(", "delim", ")", "==", "1", "for", "delim", "in", "delimiters", "]", ")", ")", ":", "raise", "ValueError", "(", "\"Delimiters must be single-character strings\"", ")", "# construct options, will extend over time", "options", "=", "dict", "(", ")", "options", "[", "\"to_lower\"", "]", "=", "to_lower", "==", "True", "# defaults to std::isspace whitespace delimiters if no others passed in", "options", "[", "\"delimiters\"", "]", "=", "delimiters", "with", "cython_context", "(", ")", ":", "return", "SArray", "(", "_proxy", "=", "self", ".", "__proxy__", ".", "count_bag_of_words", "(", "options", ")", ")" ]
This returns an SArray with, for each input string, a dict from the unique, delimited substrings to their number of occurrences within the original string. The SArray must be of type string. ..WARNING:: This function is deprecated, and will be removed in future versions of Turi Create. Please use the `text_analytics.count_words` function instead. Parameters ---------- to_lower : bool, optional "to_lower" indicates whether to map the input strings to lower case before counts delimiters: list[string], optional "delimiters" is a list of which characters to delimit on to find tokens Returns ------- out : SArray for each input string, a dict from the unique, delimited substrings to their number of occurrences within the original string. Examples -------- >>> sa = turicreate.SArray(["The quick brown fox jumps.", "Word word WORD, word!!!word"]) >>> sa._count_words() dtype: dict Rows: 2 [{'quick': 1, 'brown': 1, 'jumps': 1, 'fox': 1, 'the': 1}, {'word': 2, 'word,': 1, 'word!!!word': 1}]
[ "This", "returns", "an", "SArray", "with", "for", "each", "input", "string", "a", "dict", "from", "the", "unique", "delimited", "substrings", "to", "their", "number", "of", "occurrences", "within", "the", "original", "string", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L1506-L1558
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray._count_ngrams
def _count_ngrams(self, n=2, method="word", to_lower=True, ignore_space=True): """ For documentation, see turicreate.text_analytics.count_ngrams(). ..WARNING:: This function is deprecated, and will be removed in future versions of Turi Create. Please use the `text_analytics.count_words` function instead. """ if (self.dtype != str): raise TypeError("Only SArray of string type is supported for counting n-grams") if (type(n) != int): raise TypeError("Input 'n' must be of type int") if (n < 1): raise ValueError("Input 'n' must be greater than 0") if (n > 5): warnings.warn("It is unusual for n-grams to be of size larger than 5.") # construct options, will extend over time options = dict() options["to_lower"] = to_lower == True options["ignore_space"] = ignore_space == True if method == "word": with cython_context(): return SArray(_proxy=self.__proxy__.count_ngrams(n, options)) elif method == "character" : with cython_context(): return SArray(_proxy=self.__proxy__.count_character_ngrams(n, options)) else: raise ValueError("Invalid 'method' input value. Please input either 'word' or 'character' ")
python
def _count_ngrams(self, n=2, method="word", to_lower=True, ignore_space=True): """ For documentation, see turicreate.text_analytics.count_ngrams(). ..WARNING:: This function is deprecated, and will be removed in future versions of Turi Create. Please use the `text_analytics.count_words` function instead. """ if (self.dtype != str): raise TypeError("Only SArray of string type is supported for counting n-grams") if (type(n) != int): raise TypeError("Input 'n' must be of type int") if (n < 1): raise ValueError("Input 'n' must be greater than 0") if (n > 5): warnings.warn("It is unusual for n-grams to be of size larger than 5.") # construct options, will extend over time options = dict() options["to_lower"] = to_lower == True options["ignore_space"] = ignore_space == True if method == "word": with cython_context(): return SArray(_proxy=self.__proxy__.count_ngrams(n, options)) elif method == "character" : with cython_context(): return SArray(_proxy=self.__proxy__.count_character_ngrams(n, options)) else: raise ValueError("Invalid 'method' input value. Please input either 'word' or 'character' ")
[ "def", "_count_ngrams", "(", "self", ",", "n", "=", "2", ",", "method", "=", "\"word\"", ",", "to_lower", "=", "True", ",", "ignore_space", "=", "True", ")", ":", "if", "(", "self", ".", "dtype", "!=", "str", ")", ":", "raise", "TypeError", "(", "\"Only SArray of string type is supported for counting n-grams\"", ")", "if", "(", "type", "(", "n", ")", "!=", "int", ")", ":", "raise", "TypeError", "(", "\"Input 'n' must be of type int\"", ")", "if", "(", "n", "<", "1", ")", ":", "raise", "ValueError", "(", "\"Input 'n' must be greater than 0\"", ")", "if", "(", "n", ">", "5", ")", ":", "warnings", ".", "warn", "(", "\"It is unusual for n-grams to be of size larger than 5.\"", ")", "# construct options, will extend over time", "options", "=", "dict", "(", ")", "options", "[", "\"to_lower\"", "]", "=", "to_lower", "==", "True", "options", "[", "\"ignore_space\"", "]", "=", "ignore_space", "==", "True", "if", "method", "==", "\"word\"", ":", "with", "cython_context", "(", ")", ":", "return", "SArray", "(", "_proxy", "=", "self", ".", "__proxy__", ".", "count_ngrams", "(", "n", ",", "options", ")", ")", "elif", "method", "==", "\"character\"", ":", "with", "cython_context", "(", ")", ":", "return", "SArray", "(", "_proxy", "=", "self", ".", "__proxy__", ".", "count_character_ngrams", "(", "n", ",", "options", ")", ")", "else", ":", "raise", "ValueError", "(", "\"Invalid 'method' input value. Please input either 'word' or 'character' \"", ")" ]
For documentation, see turicreate.text_analytics.count_ngrams(). ..WARNING:: This function is deprecated, and will be removed in future versions of Turi Create. Please use the `text_analytics.count_words` function instead.
[ "For", "documentation", "see", "turicreate", ".", "text_analytics", ".", "count_ngrams", "()", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L1560-L1594
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray.dict_trim_by_keys
def dict_trim_by_keys(self, keys, exclude=True): """ Filter an SArray of dictionary type by the given keys. By default, all keys that are in the provided list in ``keys`` are *excluded* from the returned SArray. Parameters ---------- keys : list A collection of keys to trim down the elements in the SArray. exclude : bool, optional If True, all keys that are in the input key list are removed. If False, only keys that are in the input key list are retained. Returns ------- out : SArray A SArray of dictionary type, with each dictionary element trimmed according to the input criteria. See Also -------- dict_trim_by_values Examples -------- >>> sa = turicreate.SArray([{"this":1, "is":1, "dog":2}, {"this": 2, "are": 2, "cat": 1}]) >>> sa.dict_trim_by_keys(["this", "is", "and", "are"], exclude=True) dtype: dict Rows: 2 [{'dog': 2}, {'cat': 1}] """ if not _is_non_string_iterable(keys): keys = [keys] with cython_context(): return SArray(_proxy=self.__proxy__.dict_trim_by_keys(keys, exclude))
python
def dict_trim_by_keys(self, keys, exclude=True): """ Filter an SArray of dictionary type by the given keys. By default, all keys that are in the provided list in ``keys`` are *excluded* from the returned SArray. Parameters ---------- keys : list A collection of keys to trim down the elements in the SArray. exclude : bool, optional If True, all keys that are in the input key list are removed. If False, only keys that are in the input key list are retained. Returns ------- out : SArray A SArray of dictionary type, with each dictionary element trimmed according to the input criteria. See Also -------- dict_trim_by_values Examples -------- >>> sa = turicreate.SArray([{"this":1, "is":1, "dog":2}, {"this": 2, "are": 2, "cat": 1}]) >>> sa.dict_trim_by_keys(["this", "is", "and", "are"], exclude=True) dtype: dict Rows: 2 [{'dog': 2}, {'cat': 1}] """ if not _is_non_string_iterable(keys): keys = [keys] with cython_context(): return SArray(_proxy=self.__proxy__.dict_trim_by_keys(keys, exclude))
[ "def", "dict_trim_by_keys", "(", "self", ",", "keys", ",", "exclude", "=", "True", ")", ":", "if", "not", "_is_non_string_iterable", "(", "keys", ")", ":", "keys", "=", "[", "keys", "]", "with", "cython_context", "(", ")", ":", "return", "SArray", "(", "_proxy", "=", "self", ".", "__proxy__", ".", "dict_trim_by_keys", "(", "keys", ",", "exclude", ")", ")" ]
Filter an SArray of dictionary type by the given keys. By default, all keys that are in the provided list in ``keys`` are *excluded* from the returned SArray. Parameters ---------- keys : list A collection of keys to trim down the elements in the SArray. exclude : bool, optional If True, all keys that are in the input key list are removed. If False, only keys that are in the input key list are retained. Returns ------- out : SArray A SArray of dictionary type, with each dictionary element trimmed according to the input criteria. See Also -------- dict_trim_by_values Examples -------- >>> sa = turicreate.SArray([{"this":1, "is":1, "dog":2}, {"this": 2, "are": 2, "cat": 1}]) >>> sa.dict_trim_by_keys(["this", "is", "and", "are"], exclude=True) dtype: dict Rows: 2 [{'dog': 2}, {'cat': 1}]
[ "Filter", "an", "SArray", "of", "dictionary", "type", "by", "the", "given", "keys", ".", "By", "default", "all", "keys", "that", "are", "in", "the", "provided", "list", "in", "keys", "are", "*", "excluded", "*", "from", "the", "returned", "SArray", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L1596-L1635
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray.dict_trim_by_values
def dict_trim_by_values(self, lower=None, upper=None): """ Filter dictionary values to a given range (inclusive). Trimming is only performed on values which can be compared to the bound values. Fails on SArrays whose data type is not ``dict``. Parameters ---------- lower : int or long or float, optional The lowest dictionary value that would be retained in the result. If not given, lower bound is not applied. upper : int or long or float, optional The highest dictionary value that would be retained in the result. If not given, upper bound is not applied. Returns ------- out : SArray An SArray of dictionary type, with each dict element trimmed according to the input criteria. See Also -------- dict_trim_by_keys Examples -------- >>> sa = turicreate.SArray([{"this":1, "is":5, "dog":7}, {"this": 2, "are": 1, "cat": 5}]) >>> sa.dict_trim_by_values(2,5) dtype: dict Rows: 2 [{'is': 5}, {'this': 2, 'cat': 5}] >>> sa.dict_trim_by_values(upper=5) dtype: dict Rows: 2 [{'this': 1, 'is': 5}, {'this': 2, 'are': 1, 'cat': 5}] """ if not (lower is None or isinstance(lower, numbers.Number)): raise TypeError("lower bound has to be a numeric value") if not (upper is None or isinstance(upper, numbers.Number)): raise TypeError("upper bound has to be a numeric value") with cython_context(): return SArray(_proxy=self.__proxy__.dict_trim_by_values(lower, upper))
python
def dict_trim_by_values(self, lower=None, upper=None): """ Filter dictionary values to a given range (inclusive). Trimming is only performed on values which can be compared to the bound values. Fails on SArrays whose data type is not ``dict``. Parameters ---------- lower : int or long or float, optional The lowest dictionary value that would be retained in the result. If not given, lower bound is not applied. upper : int or long or float, optional The highest dictionary value that would be retained in the result. If not given, upper bound is not applied. Returns ------- out : SArray An SArray of dictionary type, with each dict element trimmed according to the input criteria. See Also -------- dict_trim_by_keys Examples -------- >>> sa = turicreate.SArray([{"this":1, "is":5, "dog":7}, {"this": 2, "are": 1, "cat": 5}]) >>> sa.dict_trim_by_values(2,5) dtype: dict Rows: 2 [{'is': 5}, {'this': 2, 'cat': 5}] >>> sa.dict_trim_by_values(upper=5) dtype: dict Rows: 2 [{'this': 1, 'is': 5}, {'this': 2, 'are': 1, 'cat': 5}] """ if not (lower is None or isinstance(lower, numbers.Number)): raise TypeError("lower bound has to be a numeric value") if not (upper is None or isinstance(upper, numbers.Number)): raise TypeError("upper bound has to be a numeric value") with cython_context(): return SArray(_proxy=self.__proxy__.dict_trim_by_values(lower, upper))
[ "def", "dict_trim_by_values", "(", "self", ",", "lower", "=", "None", ",", "upper", "=", "None", ")", ":", "if", "not", "(", "lower", "is", "None", "or", "isinstance", "(", "lower", ",", "numbers", ".", "Number", ")", ")", ":", "raise", "TypeError", "(", "\"lower bound has to be a numeric value\"", ")", "if", "not", "(", "upper", "is", "None", "or", "isinstance", "(", "upper", ",", "numbers", ".", "Number", ")", ")", ":", "raise", "TypeError", "(", "\"upper bound has to be a numeric value\"", ")", "with", "cython_context", "(", ")", ":", "return", "SArray", "(", "_proxy", "=", "self", ".", "__proxy__", ".", "dict_trim_by_values", "(", "lower", ",", "upper", ")", ")" ]
Filter dictionary values to a given range (inclusive). Trimming is only performed on values which can be compared to the bound values. Fails on SArrays whose data type is not ``dict``. Parameters ---------- lower : int or long or float, optional The lowest dictionary value that would be retained in the result. If not given, lower bound is not applied. upper : int or long or float, optional The highest dictionary value that would be retained in the result. If not given, upper bound is not applied. Returns ------- out : SArray An SArray of dictionary type, with each dict element trimmed according to the input criteria. See Also -------- dict_trim_by_keys Examples -------- >>> sa = turicreate.SArray([{"this":1, "is":5, "dog":7}, {"this": 2, "are": 1, "cat": 5}]) >>> sa.dict_trim_by_values(2,5) dtype: dict Rows: 2 [{'is': 5}, {'this': 2, 'cat': 5}] >>> sa.dict_trim_by_values(upper=5) dtype: dict Rows: 2 [{'this': 1, 'is': 5}, {'this': 2, 'are': 1, 'cat': 5}]
[ "Filter", "dictionary", "values", "to", "a", "given", "range", "(", "inclusive", ")", ".", "Trimming", "is", "only", "performed", "on", "values", "which", "can", "be", "compared", "to", "the", "bound", "values", ".", "Fails", "on", "SArrays", "whose", "data", "type", "is", "not", "dict", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L1637-L1686
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray.dict_has_any_keys
def dict_has_any_keys(self, keys): """ Create a boolean SArray by checking the keys of an SArray of dictionaries. An element of the output SArray is True if the corresponding input element's dictionary has any of the given keys. Fails on SArrays whose data type is not ``dict``. Parameters ---------- keys : list A list of key values to check each dictionary against. Returns ------- out : SArray A SArray of int type, where each element indicates whether the input SArray element contains any key in the input list. See Also -------- dict_has_all_keys Examples -------- >>> sa = turicreate.SArray([{"this":1, "is":5, "dog":7}, {"animal":1}, {"this": 2, "are": 1, "cat": 5}]) >>> sa.dict_has_any_keys(["is", "this", "are"]) dtype: int Rows: 3 [1, 0, 1] """ if not _is_non_string_iterable(keys): keys = [keys] with cython_context(): return SArray(_proxy=self.__proxy__.dict_has_any_keys(keys))
python
def dict_has_any_keys(self, keys): """ Create a boolean SArray by checking the keys of an SArray of dictionaries. An element of the output SArray is True if the corresponding input element's dictionary has any of the given keys. Fails on SArrays whose data type is not ``dict``. Parameters ---------- keys : list A list of key values to check each dictionary against. Returns ------- out : SArray A SArray of int type, where each element indicates whether the input SArray element contains any key in the input list. See Also -------- dict_has_all_keys Examples -------- >>> sa = turicreate.SArray([{"this":1, "is":5, "dog":7}, {"animal":1}, {"this": 2, "are": 1, "cat": 5}]) >>> sa.dict_has_any_keys(["is", "this", "are"]) dtype: int Rows: 3 [1, 0, 1] """ if not _is_non_string_iterable(keys): keys = [keys] with cython_context(): return SArray(_proxy=self.__proxy__.dict_has_any_keys(keys))
[ "def", "dict_has_any_keys", "(", "self", ",", "keys", ")", ":", "if", "not", "_is_non_string_iterable", "(", "keys", ")", ":", "keys", "=", "[", "keys", "]", "with", "cython_context", "(", ")", ":", "return", "SArray", "(", "_proxy", "=", "self", ".", "__proxy__", ".", "dict_has_any_keys", "(", "keys", ")", ")" ]
Create a boolean SArray by checking the keys of an SArray of dictionaries. An element of the output SArray is True if the corresponding input element's dictionary has any of the given keys. Fails on SArrays whose data type is not ``dict``. Parameters ---------- keys : list A list of key values to check each dictionary against. Returns ------- out : SArray A SArray of int type, where each element indicates whether the input SArray element contains any key in the input list. See Also -------- dict_has_all_keys Examples -------- >>> sa = turicreate.SArray([{"this":1, "is":5, "dog":7}, {"animal":1}, {"this": 2, "are": 1, "cat": 5}]) >>> sa.dict_has_any_keys(["is", "this", "are"]) dtype: int Rows: 3 [1, 0, 1]
[ "Create", "a", "boolean", "SArray", "by", "checking", "the", "keys", "of", "an", "SArray", "of", "dictionaries", ".", "An", "element", "of", "the", "output", "SArray", "is", "True", "if", "the", "corresponding", "input", "element", "s", "dictionary", "has", "any", "of", "the", "given", "keys", ".", "Fails", "on", "SArrays", "whose", "data", "type", "is", "not", "dict", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L1745-L1781
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray.dict_has_all_keys
def dict_has_all_keys(self, keys): """ Create a boolean SArray by checking the keys of an SArray of dictionaries. An element of the output SArray is True if the corresponding input element's dictionary has all of the given keys. Fails on SArrays whose data type is not ``dict``. Parameters ---------- keys : list A list of key values to check each dictionary against. Returns ------- out : SArray A SArray of int type, where each element indicates whether the input SArray element contains all keys in the input list. See Also -------- dict_has_any_keys Examples -------- >>> sa = turicreate.SArray([{"this":1, "is":5, "dog":7}, {"this": 2, "are": 1, "cat": 5}]) >>> sa.dict_has_all_keys(["is", "this"]) dtype: int Rows: 2 [1, 0] """ if not _is_non_string_iterable(keys): keys = [keys] with cython_context(): return SArray(_proxy=self.__proxy__.dict_has_all_keys(keys))
python
def dict_has_all_keys(self, keys): """ Create a boolean SArray by checking the keys of an SArray of dictionaries. An element of the output SArray is True if the corresponding input element's dictionary has all of the given keys. Fails on SArrays whose data type is not ``dict``. Parameters ---------- keys : list A list of key values to check each dictionary against. Returns ------- out : SArray A SArray of int type, where each element indicates whether the input SArray element contains all keys in the input list. See Also -------- dict_has_any_keys Examples -------- >>> sa = turicreate.SArray([{"this":1, "is":5, "dog":7}, {"this": 2, "are": 1, "cat": 5}]) >>> sa.dict_has_all_keys(["is", "this"]) dtype: int Rows: 2 [1, 0] """ if not _is_non_string_iterable(keys): keys = [keys] with cython_context(): return SArray(_proxy=self.__proxy__.dict_has_all_keys(keys))
[ "def", "dict_has_all_keys", "(", "self", ",", "keys", ")", ":", "if", "not", "_is_non_string_iterable", "(", "keys", ")", ":", "keys", "=", "[", "keys", "]", "with", "cython_context", "(", ")", ":", "return", "SArray", "(", "_proxy", "=", "self", ".", "__proxy__", ".", "dict_has_all_keys", "(", "keys", ")", ")" ]
Create a boolean SArray by checking the keys of an SArray of dictionaries. An element of the output SArray is True if the corresponding input element's dictionary has all of the given keys. Fails on SArrays whose data type is not ``dict``. Parameters ---------- keys : list A list of key values to check each dictionary against. Returns ------- out : SArray A SArray of int type, where each element indicates whether the input SArray element contains all keys in the input list. See Also -------- dict_has_any_keys Examples -------- >>> sa = turicreate.SArray([{"this":1, "is":5, "dog":7}, {"this": 2, "are": 1, "cat": 5}]) >>> sa.dict_has_all_keys(["is", "this"]) dtype: int Rows: 2 [1, 0]
[ "Create", "a", "boolean", "SArray", "by", "checking", "the", "keys", "of", "an", "SArray", "of", "dictionaries", ".", "An", "element", "of", "the", "output", "SArray", "is", "True", "if", "the", "corresponding", "input", "element", "s", "dictionary", "has", "all", "of", "the", "given", "keys", ".", "Fails", "on", "SArrays", "whose", "data", "type", "is", "not", "dict", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L1783-L1819
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray.apply
def apply(self, fn, dtype=None, skip_na=True, seed=None): """ apply(fn, dtype=None, skip_na=True, seed=None) Transform each element of the SArray by a given function. The result SArray is of type ``dtype``. ``fn`` should be a function that returns exactly one value which can be cast into the type specified by ``dtype``. If ``dtype`` is not specified, the first 100 elements of the SArray are used to make a guess about the data type. Parameters ---------- fn : function The function to transform each element. Must return exactly one value which can be cast into the type specified by ``dtype``. This can also be a toolkit extension function which is compiled as a native shared library using SDK. dtype : {None, int, float, str, list, array.array, dict, turicreate.Image}, optional The data type of the new SArray. If ``None``, the first 100 elements of the array are used to guess the target data type. skip_na : bool, optional If True, will not apply ``fn`` to any undefined values. seed : int, optional Used as the seed if a random number generator is included in ``fn``. Returns ------- out : SArray The SArray transformed by ``fn``. Each element of the SArray is of type ``dtype``. See Also -------- SFrame.apply Examples -------- >>> sa = turicreate.SArray([1,2,3]) >>> sa.apply(lambda x: x*2) dtype: int Rows: 3 [2, 4, 6] Using native toolkit extension function: .. code-block:: c++ #include <turicreate/sdk/toolkit_function_macros.hpp> #include <cmath> using namespace turi; double logx(const flexible_type& x, double base) { return log((double)(x)) / log(base); } BEGIN_FUNCTION_REGISTRATION REGISTER_FUNCTION(logx, "x", "base"); END_FUNCTION_REGISTRATION compiled into example.so >>> import example >>> sa = turicreate.SArray([1,2,4]) >>> sa.apply(lambda x: example.logx(x, 2)) dtype: float Rows: 3 [0.0, 1.0, 2.0] """ assert callable(fn), "Input function must be callable." dryrun = [fn(i) for i in self.head(100) if i is not None] if dtype is None: dtype = infer_type_of_list(dryrun) if seed is None: seed = abs(hash("%0.20f" % time.time())) % (2 ** 31) # log metric # First phase test if it is a toolkit function nativefn = None try: from .. import extensions nativefn = extensions._build_native_function_call(fn) except: # failure are fine. we just fall out into the next few phases pass if nativefn is not None: # this is a toolkit lambda. We can do something about it nativefn.native_fn_name = nativefn.native_fn_name.encode() with cython_context(): return SArray(_proxy=self.__proxy__.transform_native(nativefn, dtype, skip_na, seed)) with cython_context(): return SArray(_proxy=self.__proxy__.transform(fn, dtype, skip_na, seed))
python
def apply(self, fn, dtype=None, skip_na=True, seed=None): """ apply(fn, dtype=None, skip_na=True, seed=None) Transform each element of the SArray by a given function. The result SArray is of type ``dtype``. ``fn`` should be a function that returns exactly one value which can be cast into the type specified by ``dtype``. If ``dtype`` is not specified, the first 100 elements of the SArray are used to make a guess about the data type. Parameters ---------- fn : function The function to transform each element. Must return exactly one value which can be cast into the type specified by ``dtype``. This can also be a toolkit extension function which is compiled as a native shared library using SDK. dtype : {None, int, float, str, list, array.array, dict, turicreate.Image}, optional The data type of the new SArray. If ``None``, the first 100 elements of the array are used to guess the target data type. skip_na : bool, optional If True, will not apply ``fn`` to any undefined values. seed : int, optional Used as the seed if a random number generator is included in ``fn``. Returns ------- out : SArray The SArray transformed by ``fn``. Each element of the SArray is of type ``dtype``. See Also -------- SFrame.apply Examples -------- >>> sa = turicreate.SArray([1,2,3]) >>> sa.apply(lambda x: x*2) dtype: int Rows: 3 [2, 4, 6] Using native toolkit extension function: .. code-block:: c++ #include <turicreate/sdk/toolkit_function_macros.hpp> #include <cmath> using namespace turi; double logx(const flexible_type& x, double base) { return log((double)(x)) / log(base); } BEGIN_FUNCTION_REGISTRATION REGISTER_FUNCTION(logx, "x", "base"); END_FUNCTION_REGISTRATION compiled into example.so >>> import example >>> sa = turicreate.SArray([1,2,4]) >>> sa.apply(lambda x: example.logx(x, 2)) dtype: float Rows: 3 [0.0, 1.0, 2.0] """ assert callable(fn), "Input function must be callable." dryrun = [fn(i) for i in self.head(100) if i is not None] if dtype is None: dtype = infer_type_of_list(dryrun) if seed is None: seed = abs(hash("%0.20f" % time.time())) % (2 ** 31) # log metric # First phase test if it is a toolkit function nativefn = None try: from .. import extensions nativefn = extensions._build_native_function_call(fn) except: # failure are fine. we just fall out into the next few phases pass if nativefn is not None: # this is a toolkit lambda. We can do something about it nativefn.native_fn_name = nativefn.native_fn_name.encode() with cython_context(): return SArray(_proxy=self.__proxy__.transform_native(nativefn, dtype, skip_na, seed)) with cython_context(): return SArray(_proxy=self.__proxy__.transform(fn, dtype, skip_na, seed))
[ "def", "apply", "(", "self", ",", "fn", ",", "dtype", "=", "None", ",", "skip_na", "=", "True", ",", "seed", "=", "None", ")", ":", "assert", "callable", "(", "fn", ")", ",", "\"Input function must be callable.\"", "dryrun", "=", "[", "fn", "(", "i", ")", "for", "i", "in", "self", ".", "head", "(", "100", ")", "if", "i", "is", "not", "None", "]", "if", "dtype", "is", "None", ":", "dtype", "=", "infer_type_of_list", "(", "dryrun", ")", "if", "seed", "is", "None", ":", "seed", "=", "abs", "(", "hash", "(", "\"%0.20f\"", "%", "time", ".", "time", "(", ")", ")", ")", "%", "(", "2", "**", "31", ")", "# log metric", "# First phase test if it is a toolkit function", "nativefn", "=", "None", "try", ":", "from", ".", ".", "import", "extensions", "nativefn", "=", "extensions", ".", "_build_native_function_call", "(", "fn", ")", "except", ":", "# failure are fine. we just fall out into the next few phases", "pass", "if", "nativefn", "is", "not", "None", ":", "# this is a toolkit lambda. We can do something about it", "nativefn", ".", "native_fn_name", "=", "nativefn", ".", "native_fn_name", ".", "encode", "(", ")", "with", "cython_context", "(", ")", ":", "return", "SArray", "(", "_proxy", "=", "self", ".", "__proxy__", ".", "transform_native", "(", "nativefn", ",", "dtype", ",", "skip_na", ",", "seed", ")", ")", "with", "cython_context", "(", ")", ":", "return", "SArray", "(", "_proxy", "=", "self", ".", "__proxy__", ".", "transform", "(", "fn", ",", "dtype", ",", "skip_na", ",", "seed", ")", ")" ]
apply(fn, dtype=None, skip_na=True, seed=None) Transform each element of the SArray by a given function. The result SArray is of type ``dtype``. ``fn`` should be a function that returns exactly one value which can be cast into the type specified by ``dtype``. If ``dtype`` is not specified, the first 100 elements of the SArray are used to make a guess about the data type. Parameters ---------- fn : function The function to transform each element. Must return exactly one value which can be cast into the type specified by ``dtype``. This can also be a toolkit extension function which is compiled as a native shared library using SDK. dtype : {None, int, float, str, list, array.array, dict, turicreate.Image}, optional The data type of the new SArray. If ``None``, the first 100 elements of the array are used to guess the target data type. skip_na : bool, optional If True, will not apply ``fn`` to any undefined values. seed : int, optional Used as the seed if a random number generator is included in ``fn``. Returns ------- out : SArray The SArray transformed by ``fn``. Each element of the SArray is of type ``dtype``. See Also -------- SFrame.apply Examples -------- >>> sa = turicreate.SArray([1,2,3]) >>> sa.apply(lambda x: x*2) dtype: int Rows: 3 [2, 4, 6] Using native toolkit extension function: .. code-block:: c++ #include <turicreate/sdk/toolkit_function_macros.hpp> #include <cmath> using namespace turi; double logx(const flexible_type& x, double base) { return log((double)(x)) / log(base); } BEGIN_FUNCTION_REGISTRATION REGISTER_FUNCTION(logx, "x", "base"); END_FUNCTION_REGISTRATION compiled into example.so >>> import example >>> sa = turicreate.SArray([1,2,4]) >>> sa.apply(lambda x: example.logx(x, 2)) dtype: float Rows: 3 [0.0, 1.0, 2.0]
[ "apply", "(", "fn", "dtype", "=", "None", "skip_na", "=", "True", "seed", "=", "None", ")" ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L1821-L1920
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray.filter
def filter(self, fn, skip_na=True, seed=None): """ Filter this SArray by a function. Returns a new SArray filtered by this SArray. If `fn` evaluates an element to true, this element is copied to the new SArray. If not, it isn't. Throws an exception if the return type of `fn` is not castable to a boolean value. Parameters ---------- fn : function Function that filters the SArray. Must evaluate to bool or int. skip_na : bool, optional If True, will not apply fn to any undefined values. seed : int, optional Used as the seed if a random number generator is included in fn. Returns ------- out : SArray The SArray filtered by fn. Each element of the SArray is of type int. Examples -------- >>> sa = turicreate.SArray([1,2,3]) >>> sa.filter(lambda x: x < 3) dtype: int Rows: 2 [1, 2] """ assert callable(fn), "Input must be callable" if seed is None: seed = abs(hash("%0.20f" % time.time())) % (2 ** 31) with cython_context(): return SArray(_proxy=self.__proxy__.filter(fn, skip_na, seed))
python
def filter(self, fn, skip_na=True, seed=None): """ Filter this SArray by a function. Returns a new SArray filtered by this SArray. If `fn` evaluates an element to true, this element is copied to the new SArray. If not, it isn't. Throws an exception if the return type of `fn` is not castable to a boolean value. Parameters ---------- fn : function Function that filters the SArray. Must evaluate to bool or int. skip_na : bool, optional If True, will not apply fn to any undefined values. seed : int, optional Used as the seed if a random number generator is included in fn. Returns ------- out : SArray The SArray filtered by fn. Each element of the SArray is of type int. Examples -------- >>> sa = turicreate.SArray([1,2,3]) >>> sa.filter(lambda x: x < 3) dtype: int Rows: 2 [1, 2] """ assert callable(fn), "Input must be callable" if seed is None: seed = abs(hash("%0.20f" % time.time())) % (2 ** 31) with cython_context(): return SArray(_proxy=self.__proxy__.filter(fn, skip_na, seed))
[ "def", "filter", "(", "self", ",", "fn", ",", "skip_na", "=", "True", ",", "seed", "=", "None", ")", ":", "assert", "callable", "(", "fn", ")", ",", "\"Input must be callable\"", "if", "seed", "is", "None", ":", "seed", "=", "abs", "(", "hash", "(", "\"%0.20f\"", "%", "time", ".", "time", "(", ")", ")", ")", "%", "(", "2", "**", "31", ")", "with", "cython_context", "(", ")", ":", "return", "SArray", "(", "_proxy", "=", "self", ".", "__proxy__", ".", "filter", "(", "fn", ",", "skip_na", ",", "seed", ")", ")" ]
Filter this SArray by a function. Returns a new SArray filtered by this SArray. If `fn` evaluates an element to true, this element is copied to the new SArray. If not, it isn't. Throws an exception if the return type of `fn` is not castable to a boolean value. Parameters ---------- fn : function Function that filters the SArray. Must evaluate to bool or int. skip_na : bool, optional If True, will not apply fn to any undefined values. seed : int, optional Used as the seed if a random number generator is included in fn. Returns ------- out : SArray The SArray filtered by fn. Each element of the SArray is of type int. Examples -------- >>> sa = turicreate.SArray([1,2,3]) >>> sa.filter(lambda x: x < 3) dtype: int Rows: 2 [1, 2]
[ "Filter", "this", "SArray", "by", "a", "function", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L1923-L1963
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray.sample
def sample(self, fraction, seed=None, exact=False): """ Create an SArray which contains a subsample of the current SArray. Parameters ---------- fraction : float Fraction of the rows to fetch. Must be between 0 and 1. if exact is False (default), the number of rows returned is approximately the fraction times the number of rows. seed : int, optional The random seed for the random number generator. exact: bool, optional Defaults to False. If exact=True, an exact fraction is returned, but at a performance penalty. Returns ------- out : SArray The new SArray which contains the subsampled rows. Examples -------- >>> sa = turicreate.SArray(range(10)) >>> sa.sample(.3) dtype: int Rows: 3 [2, 6, 9] """ if (fraction > 1 or fraction < 0): raise ValueError('Invalid sampling rate: ' + str(fraction)) if (len(self) == 0): return SArray() if seed is None: seed = abs(hash("%0.20f" % time.time())) % (2 ** 31) with cython_context(): return SArray(_proxy=self.__proxy__.sample(fraction, seed, exact))
python
def sample(self, fraction, seed=None, exact=False): """ Create an SArray which contains a subsample of the current SArray. Parameters ---------- fraction : float Fraction of the rows to fetch. Must be between 0 and 1. if exact is False (default), the number of rows returned is approximately the fraction times the number of rows. seed : int, optional The random seed for the random number generator. exact: bool, optional Defaults to False. If exact=True, an exact fraction is returned, but at a performance penalty. Returns ------- out : SArray The new SArray which contains the subsampled rows. Examples -------- >>> sa = turicreate.SArray(range(10)) >>> sa.sample(.3) dtype: int Rows: 3 [2, 6, 9] """ if (fraction > 1 or fraction < 0): raise ValueError('Invalid sampling rate: ' + str(fraction)) if (len(self) == 0): return SArray() if seed is None: seed = abs(hash("%0.20f" % time.time())) % (2 ** 31) with cython_context(): return SArray(_proxy=self.__proxy__.sample(fraction, seed, exact))
[ "def", "sample", "(", "self", ",", "fraction", ",", "seed", "=", "None", ",", "exact", "=", "False", ")", ":", "if", "(", "fraction", ">", "1", "or", "fraction", "<", "0", ")", ":", "raise", "ValueError", "(", "'Invalid sampling rate: '", "+", "str", "(", "fraction", ")", ")", "if", "(", "len", "(", "self", ")", "==", "0", ")", ":", "return", "SArray", "(", ")", "if", "seed", "is", "None", ":", "seed", "=", "abs", "(", "hash", "(", "\"%0.20f\"", "%", "time", ".", "time", "(", ")", ")", ")", "%", "(", "2", "**", "31", ")", "with", "cython_context", "(", ")", ":", "return", "SArray", "(", "_proxy", "=", "self", ".", "__proxy__", ".", "sample", "(", "fraction", ",", "seed", ",", "exact", ")", ")" ]
Create an SArray which contains a subsample of the current SArray. Parameters ---------- fraction : float Fraction of the rows to fetch. Must be between 0 and 1. if exact is False (default), the number of rows returned is approximately the fraction times the number of rows. seed : int, optional The random seed for the random number generator. exact: bool, optional Defaults to False. If exact=True, an exact fraction is returned, but at a performance penalty. Returns ------- out : SArray The new SArray which contains the subsampled rows. Examples -------- >>> sa = turicreate.SArray(range(10)) >>> sa.sample(.3) dtype: int Rows: 3 [2, 6, 9]
[ "Create", "an", "SArray", "which", "contains", "a", "subsample", "of", "the", "current", "SArray", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L1966-L2006
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray.hash
def hash(self, seed=0): """ Returns an SArray with a hash of each element. seed can be used to change the hash function to allow this method to be used for random number generation. Parameters ---------- seed : int Defaults to 0. Can be changed to different values to get different hash results. Returns ------- out : SArray An integer SArray with a hash value for each element. Identical elements are hashed to the same value """ with cython_context(): return SArray(_proxy=self.__proxy__.hash(seed))
python
def hash(self, seed=0): """ Returns an SArray with a hash of each element. seed can be used to change the hash function to allow this method to be used for random number generation. Parameters ---------- seed : int Defaults to 0. Can be changed to different values to get different hash results. Returns ------- out : SArray An integer SArray with a hash value for each element. Identical elements are hashed to the same value """ with cython_context(): return SArray(_proxy=self.__proxy__.hash(seed))
[ "def", "hash", "(", "self", ",", "seed", "=", "0", ")", ":", "with", "cython_context", "(", ")", ":", "return", "SArray", "(", "_proxy", "=", "self", ".", "__proxy__", ".", "hash", "(", "seed", ")", ")" ]
Returns an SArray with a hash of each element. seed can be used to change the hash function to allow this method to be used for random number generation. Parameters ---------- seed : int Defaults to 0. Can be changed to different values to get different hash results. Returns ------- out : SArray An integer SArray with a hash value for each element. Identical elements are hashed to the same value
[ "Returns", "an", "SArray", "with", "a", "hash", "of", "each", "element", ".", "seed", "can", "be", "used", "to", "change", "the", "hash", "function", "to", "allow", "this", "method", "to", "be", "used", "for", "random", "number", "generation", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L2008-L2027
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray.random_integers
def random_integers(cls, size, seed=None): """ Returns an SArray with random integer values. """ if seed is None: seed = abs(hash("%0.20f" % time.time())) % (2 ** 31) return cls.from_sequence(size).hash(seed)
python
def random_integers(cls, size, seed=None): """ Returns an SArray with random integer values. """ if seed is None: seed = abs(hash("%0.20f" % time.time())) % (2 ** 31) return cls.from_sequence(size).hash(seed)
[ "def", "random_integers", "(", "cls", ",", "size", ",", "seed", "=", "None", ")", ":", "if", "seed", "is", "None", ":", "seed", "=", "abs", "(", "hash", "(", "\"%0.20f\"", "%", "time", ".", "time", "(", ")", ")", ")", "%", "(", "2", "**", "31", ")", "return", "cls", ".", "from_sequence", "(", "size", ")", ".", "hash", "(", "seed", ")" ]
Returns an SArray with random integer values.
[ "Returns", "an", "SArray", "with", "random", "integer", "values", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L2030-L2036
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray.argmin
def argmin(self): """ Get the index of the minimum numeric value in SArray. Returns None on an empty SArray. Raises an exception if called on an SArray with non-numeric type. Returns ------- out : int index of the minimum value of SArray See Also -------- argmax Examples -------- >>> turicreate.SArray([14, 62, 83, 72, 77, 96, 5, 25, 69, 66]).argmin() """ from .sframe import SFrame as _SFrame if len(self) == 0: return None if not any([isinstance(self[0], i) for i in [int,float,long]]): raise TypeError("SArray must be of type 'int', 'long', or 'float'.") sf = _SFrame(self).add_row_number() sf_out = sf.groupby(key_column_names=[],operations={'minimum_x1': _aggregate.ARGMIN('X1','id')}) return sf_out['minimum_x1'][0]
python
def argmin(self): """ Get the index of the minimum numeric value in SArray. Returns None on an empty SArray. Raises an exception if called on an SArray with non-numeric type. Returns ------- out : int index of the minimum value of SArray See Also -------- argmax Examples -------- >>> turicreate.SArray([14, 62, 83, 72, 77, 96, 5, 25, 69, 66]).argmin() """ from .sframe import SFrame as _SFrame if len(self) == 0: return None if not any([isinstance(self[0], i) for i in [int,float,long]]): raise TypeError("SArray must be of type 'int', 'long', or 'float'.") sf = _SFrame(self).add_row_number() sf_out = sf.groupby(key_column_names=[],operations={'minimum_x1': _aggregate.ARGMIN('X1','id')}) return sf_out['minimum_x1'][0]
[ "def", "argmin", "(", "self", ")", ":", "from", ".", "sframe", "import", "SFrame", "as", "_SFrame", "if", "len", "(", "self", ")", "==", "0", ":", "return", "None", "if", "not", "any", "(", "[", "isinstance", "(", "self", "[", "0", "]", ",", "i", ")", "for", "i", "in", "[", "int", ",", "float", ",", "long", "]", "]", ")", ":", "raise", "TypeError", "(", "\"SArray must be of type 'int', 'long', or 'float'.\"", ")", "sf", "=", "_SFrame", "(", "self", ")", ".", "add_row_number", "(", ")", "sf_out", "=", "sf", ".", "groupby", "(", "key_column_names", "=", "[", "]", ",", "operations", "=", "{", "'minimum_x1'", ":", "_aggregate", ".", "ARGMIN", "(", "'X1'", ",", "'id'", ")", "}", ")", "return", "sf_out", "[", "'minimum_x1'", "]", "[", "0", "]" ]
Get the index of the minimum numeric value in SArray. Returns None on an empty SArray. Raises an exception if called on an SArray with non-numeric type. Returns ------- out : int index of the minimum value of SArray See Also -------- argmax Examples -------- >>> turicreate.SArray([14, 62, 83, 72, 77, 96, 5, 25, 69, 66]).argmin()
[ "Get", "the", "index", "of", "the", "minimum", "numeric", "value", "in", "SArray", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L2201-L2231
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray.mean
def mean(self): """ Mean of all the values in the SArray, or mean image. Returns None on an empty SArray. Raises an exception if called on an SArray with non-numeric type or non-Image type. Returns ------- out : float | turicreate.Image Mean of all values in SArray, or image holding per-pixel mean across the input SArray. """ with cython_context(): if self.dtype == _Image: from .. import extensions return extensions.generate_mean(self) else: return self.__proxy__.mean()
python
def mean(self): """ Mean of all the values in the SArray, or mean image. Returns None on an empty SArray. Raises an exception if called on an SArray with non-numeric type or non-Image type. Returns ------- out : float | turicreate.Image Mean of all values in SArray, or image holding per-pixel mean across the input SArray. """ with cython_context(): if self.dtype == _Image: from .. import extensions return extensions.generate_mean(self) else: return self.__proxy__.mean()
[ "def", "mean", "(", "self", ")", ":", "with", "cython_context", "(", ")", ":", "if", "self", ".", "dtype", "==", "_Image", ":", "from", ".", ".", "import", "extensions", "return", "extensions", ".", "generate_mean", "(", "self", ")", "else", ":", "return", "self", ".", "__proxy__", ".", "mean", "(", ")" ]
Mean of all the values in the SArray, or mean image. Returns None on an empty SArray. Raises an exception if called on an SArray with non-numeric type or non-Image type. Returns ------- out : float | turicreate.Image Mean of all values in SArray, or image holding per-pixel mean across the input SArray.
[ "Mean", "of", "all", "the", "values", "in", "the", "SArray", "or", "mean", "image", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L2252-L2270
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray.datetime_to_str
def datetime_to_str(self,format="%Y-%m-%dT%H:%M:%S%ZP"): """ Create a new SArray with all the values cast to str. The string format is specified by the 'format' parameter. Parameters ---------- format : str The format to output the string. Default format is "%Y-%m-%dT%H:%M:%S%ZP". Returns ------- out : SArray[str] The SArray converted to the type 'str'. Examples -------- >>> dt = datetime.datetime(2011, 10, 20, 9, 30, 10, tzinfo=GMT(-5)) >>> sa = turicreate.SArray([dt]) >>> sa.datetime_to_str("%e %b %Y %T %ZP") dtype: str Rows: 1 [20 Oct 2011 09:30:10 GMT-05:00] See Also ---------- str_to_datetime References ---------- [1] Boost date time from string conversion guide (http://www.boost.org/doc/libs/1_48_0/doc/html/date_time/date_time_io.html) """ if(self.dtype != datetime.datetime): raise TypeError("datetime_to_str expects SArray of datetime as input SArray") with cython_context(): return SArray(_proxy=self.__proxy__.datetime_to_str(format))
python
def datetime_to_str(self,format="%Y-%m-%dT%H:%M:%S%ZP"): """ Create a new SArray with all the values cast to str. The string format is specified by the 'format' parameter. Parameters ---------- format : str The format to output the string. Default format is "%Y-%m-%dT%H:%M:%S%ZP". Returns ------- out : SArray[str] The SArray converted to the type 'str'. Examples -------- >>> dt = datetime.datetime(2011, 10, 20, 9, 30, 10, tzinfo=GMT(-5)) >>> sa = turicreate.SArray([dt]) >>> sa.datetime_to_str("%e %b %Y %T %ZP") dtype: str Rows: 1 [20 Oct 2011 09:30:10 GMT-05:00] See Also ---------- str_to_datetime References ---------- [1] Boost date time from string conversion guide (http://www.boost.org/doc/libs/1_48_0/doc/html/date_time/date_time_io.html) """ if(self.dtype != datetime.datetime): raise TypeError("datetime_to_str expects SArray of datetime as input SArray") with cython_context(): return SArray(_proxy=self.__proxy__.datetime_to_str(format))
[ "def", "datetime_to_str", "(", "self", ",", "format", "=", "\"%Y-%m-%dT%H:%M:%S%ZP\"", ")", ":", "if", "(", "self", ".", "dtype", "!=", "datetime", ".", "datetime", ")", ":", "raise", "TypeError", "(", "\"datetime_to_str expects SArray of datetime as input SArray\"", ")", "with", "cython_context", "(", ")", ":", "return", "SArray", "(", "_proxy", "=", "self", ".", "__proxy__", ".", "datetime_to_str", "(", "format", ")", ")" ]
Create a new SArray with all the values cast to str. The string format is specified by the 'format' parameter. Parameters ---------- format : str The format to output the string. Default format is "%Y-%m-%dT%H:%M:%S%ZP". Returns ------- out : SArray[str] The SArray converted to the type 'str'. Examples -------- >>> dt = datetime.datetime(2011, 10, 20, 9, 30, 10, tzinfo=GMT(-5)) >>> sa = turicreate.SArray([dt]) >>> sa.datetime_to_str("%e %b %Y %T %ZP") dtype: str Rows: 1 [20 Oct 2011 09:30:10 GMT-05:00] See Also ---------- str_to_datetime References ---------- [1] Boost date time from string conversion guide (http://www.boost.org/doc/libs/1_48_0/doc/html/date_time/date_time_io.html)
[ "Create", "a", "new", "SArray", "with", "all", "the", "values", "cast", "to", "str", ".", "The", "string", "format", "is", "specified", "by", "the", "format", "parameter", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L2338-L2375
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray.str_to_datetime
def str_to_datetime(self,format="%Y-%m-%dT%H:%M:%S%ZP"): """ Create a new SArray with all the values cast to datetime. The string format is specified by the 'format' parameter. Parameters ---------- format : str The string format of the input SArray. Default format is "%Y-%m-%dT%H:%M:%S%ZP". If format is "ISO", the the format is "%Y%m%dT%H%M%S%F%q" Returns ------- out : SArray[datetime.datetime] The SArray converted to the type 'datetime'. Examples -------- >>> sa = turicreate.SArray(["20-Oct-2011 09:30:10 GMT-05:30"]) >>> sa.str_to_datetime("%d-%b-%Y %H:%M:%S %ZP") dtype: datetime Rows: 1 datetime.datetime(2011, 10, 20, 9, 30, 10, tzinfo=GMT(-5.5)) See Also ---------- datetime_to_str References ---------- [1] boost date time to string conversion guide (http://www.boost.org/doc/libs/1_48_0/doc/html/date_time/date_time_io.html) """ if(self.dtype != str): raise TypeError("str_to_datetime expects SArray of str as input SArray") with cython_context(): return SArray(_proxy=self.__proxy__.str_to_datetime(format))
python
def str_to_datetime(self,format="%Y-%m-%dT%H:%M:%S%ZP"): """ Create a new SArray with all the values cast to datetime. The string format is specified by the 'format' parameter. Parameters ---------- format : str The string format of the input SArray. Default format is "%Y-%m-%dT%H:%M:%S%ZP". If format is "ISO", the the format is "%Y%m%dT%H%M%S%F%q" Returns ------- out : SArray[datetime.datetime] The SArray converted to the type 'datetime'. Examples -------- >>> sa = turicreate.SArray(["20-Oct-2011 09:30:10 GMT-05:30"]) >>> sa.str_to_datetime("%d-%b-%Y %H:%M:%S %ZP") dtype: datetime Rows: 1 datetime.datetime(2011, 10, 20, 9, 30, 10, tzinfo=GMT(-5.5)) See Also ---------- datetime_to_str References ---------- [1] boost date time to string conversion guide (http://www.boost.org/doc/libs/1_48_0/doc/html/date_time/date_time_io.html) """ if(self.dtype != str): raise TypeError("str_to_datetime expects SArray of str as input SArray") with cython_context(): return SArray(_proxy=self.__proxy__.str_to_datetime(format))
[ "def", "str_to_datetime", "(", "self", ",", "format", "=", "\"%Y-%m-%dT%H:%M:%S%ZP\"", ")", ":", "if", "(", "self", ".", "dtype", "!=", "str", ")", ":", "raise", "TypeError", "(", "\"str_to_datetime expects SArray of str as input SArray\"", ")", "with", "cython_context", "(", ")", ":", "return", "SArray", "(", "_proxy", "=", "self", ".", "__proxy__", ".", "str_to_datetime", "(", "format", ")", ")" ]
Create a new SArray with all the values cast to datetime. The string format is specified by the 'format' parameter. Parameters ---------- format : str The string format of the input SArray. Default format is "%Y-%m-%dT%H:%M:%S%ZP". If format is "ISO", the the format is "%Y%m%dT%H%M%S%F%q" Returns ------- out : SArray[datetime.datetime] The SArray converted to the type 'datetime'. Examples -------- >>> sa = turicreate.SArray(["20-Oct-2011 09:30:10 GMT-05:30"]) >>> sa.str_to_datetime("%d-%b-%Y %H:%M:%S %ZP") dtype: datetime Rows: 1 datetime.datetime(2011, 10, 20, 9, 30, 10, tzinfo=GMT(-5.5)) See Also ---------- datetime_to_str References ---------- [1] boost date time to string conversion guide (http://www.boost.org/doc/libs/1_48_0/doc/html/date_time/date_time_io.html)
[ "Create", "a", "new", "SArray", "with", "all", "the", "values", "cast", "to", "datetime", ".", "The", "string", "format", "is", "specified", "by", "the", "format", "parameter", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L2377-L2413
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray.pixel_array_to_image
def pixel_array_to_image(self, width, height, channels, undefined_on_failure=True, allow_rounding=False): """ Create a new SArray with all the values cast to :py:class:`turicreate.image.Image` of uniform size. Parameters ---------- width: int The width of the new images. height: int The height of the new images. channels: int. Number of channels of the new images. undefined_on_failure: bool , optional , default True If True, return None type instead of Image type in failure instances. If False, raises error upon failure. allow_rounding: bool, optional , default False If True, rounds non-integer values when converting to Image type. If False, raises error upon rounding. Returns ------- out : SArray[turicreate.Image] The SArray converted to the type 'turicreate.Image'. See Also -------- astype, str_to_datetime, datetime_to_str Examples -------- The MNIST data is scaled from 0 to 1, but our image type only loads integer pixel values from 0 to 255. If we just convert without scaling, all values below one would be cast to 0. >>> mnist_array = turicreate.SArray('https://static.turi.com/datasets/mnist/mnist_vec_sarray') >>> scaled_mnist_array = mnist_array * 255 >>> mnist_img_sarray = tc.SArray.pixel_array_to_image(scaled_mnist_array, 28, 28, 1, allow_rounding = True) """ if(self.dtype != array.array): raise TypeError("array_to_img expects SArray of arrays as input SArray") num_to_test = 10 num_test = min(len(self), num_to_test) mod_values = [val % 1 for x in range(num_test) for val in self[x]] out_of_range_values = [(val > 255 or val < 0) for x in range(num_test) for val in self[x]] if sum(mod_values) != 0.0 and not allow_rounding: raise ValueError("There are non-integer values in the array data. Images only support integer data values between 0 and 255. To permit rounding, set the 'allow_rounding' parameter to 1.") if sum(out_of_range_values) != 0: raise ValueError("There are values outside the range of 0 to 255. Images only support integer data values between 0 and 255.") from .. import extensions return extensions.vector_sarray_to_image_sarray(self, width, height, channels, undefined_on_failure)
python
def pixel_array_to_image(self, width, height, channels, undefined_on_failure=True, allow_rounding=False): """ Create a new SArray with all the values cast to :py:class:`turicreate.image.Image` of uniform size. Parameters ---------- width: int The width of the new images. height: int The height of the new images. channels: int. Number of channels of the new images. undefined_on_failure: bool , optional , default True If True, return None type instead of Image type in failure instances. If False, raises error upon failure. allow_rounding: bool, optional , default False If True, rounds non-integer values when converting to Image type. If False, raises error upon rounding. Returns ------- out : SArray[turicreate.Image] The SArray converted to the type 'turicreate.Image'. See Also -------- astype, str_to_datetime, datetime_to_str Examples -------- The MNIST data is scaled from 0 to 1, but our image type only loads integer pixel values from 0 to 255. If we just convert without scaling, all values below one would be cast to 0. >>> mnist_array = turicreate.SArray('https://static.turi.com/datasets/mnist/mnist_vec_sarray') >>> scaled_mnist_array = mnist_array * 255 >>> mnist_img_sarray = tc.SArray.pixel_array_to_image(scaled_mnist_array, 28, 28, 1, allow_rounding = True) """ if(self.dtype != array.array): raise TypeError("array_to_img expects SArray of arrays as input SArray") num_to_test = 10 num_test = min(len(self), num_to_test) mod_values = [val % 1 for x in range(num_test) for val in self[x]] out_of_range_values = [(val > 255 or val < 0) for x in range(num_test) for val in self[x]] if sum(mod_values) != 0.0 and not allow_rounding: raise ValueError("There are non-integer values in the array data. Images only support integer data values between 0 and 255. To permit rounding, set the 'allow_rounding' parameter to 1.") if sum(out_of_range_values) != 0: raise ValueError("There are values outside the range of 0 to 255. Images only support integer data values between 0 and 255.") from .. import extensions return extensions.vector_sarray_to_image_sarray(self, width, height, channels, undefined_on_failure)
[ "def", "pixel_array_to_image", "(", "self", ",", "width", ",", "height", ",", "channels", ",", "undefined_on_failure", "=", "True", ",", "allow_rounding", "=", "False", ")", ":", "if", "(", "self", ".", "dtype", "!=", "array", ".", "array", ")", ":", "raise", "TypeError", "(", "\"array_to_img expects SArray of arrays as input SArray\"", ")", "num_to_test", "=", "10", "num_test", "=", "min", "(", "len", "(", "self", ")", ",", "num_to_test", ")", "mod_values", "=", "[", "val", "%", "1", "for", "x", "in", "range", "(", "num_test", ")", "for", "val", "in", "self", "[", "x", "]", "]", "out_of_range_values", "=", "[", "(", "val", ">", "255", "or", "val", "<", "0", ")", "for", "x", "in", "range", "(", "num_test", ")", "for", "val", "in", "self", "[", "x", "]", "]", "if", "sum", "(", "mod_values", ")", "!=", "0.0", "and", "not", "allow_rounding", ":", "raise", "ValueError", "(", "\"There are non-integer values in the array data. Images only support integer data values between 0 and 255. To permit rounding, set the 'allow_rounding' parameter to 1.\"", ")", "if", "sum", "(", "out_of_range_values", ")", "!=", "0", ":", "raise", "ValueError", "(", "\"There are values outside the range of 0 to 255. Images only support integer data values between 0 and 255.\"", ")", "from", ".", ".", "import", "extensions", "return", "extensions", ".", "vector_sarray_to_image_sarray", "(", "self", ",", "width", ",", "height", ",", "channels", ",", "undefined_on_failure", ")" ]
Create a new SArray with all the values cast to :py:class:`turicreate.image.Image` of uniform size. Parameters ---------- width: int The width of the new images. height: int The height of the new images. channels: int. Number of channels of the new images. undefined_on_failure: bool , optional , default True If True, return None type instead of Image type in failure instances. If False, raises error upon failure. allow_rounding: bool, optional , default False If True, rounds non-integer values when converting to Image type. If False, raises error upon rounding. Returns ------- out : SArray[turicreate.Image] The SArray converted to the type 'turicreate.Image'. See Also -------- astype, str_to_datetime, datetime_to_str Examples -------- The MNIST data is scaled from 0 to 1, but our image type only loads integer pixel values from 0 to 255. If we just convert without scaling, all values below one would be cast to 0. >>> mnist_array = turicreate.SArray('https://static.turi.com/datasets/mnist/mnist_vec_sarray') >>> scaled_mnist_array = mnist_array * 255 >>> mnist_img_sarray = tc.SArray.pixel_array_to_image(scaled_mnist_array, 28, 28, 1, allow_rounding = True)
[ "Create", "a", "new", "SArray", "with", "all", "the", "values", "cast", "to", ":", "py", ":", "class", ":", "turicreate", ".", "image", ".", "Image", "of", "uniform", "size", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L2415-L2478
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray.astype
def astype(self, dtype, undefined_on_failure=False): """ Create a new SArray with all values cast to the given type. Throws an exception if the types are not castable to the given type. Parameters ---------- dtype : {int, float, str, list, array.array, dict, datetime.datetime} The type to cast the elements to in SArray undefined_on_failure: bool, optional If set to True, runtime cast failures will be emitted as missing values rather than failing. Returns ------- out : SArray [dtype] The SArray converted to the type ``dtype``. Notes ----- - The string parsing techniques used to handle conversion to dictionary and list types are quite generic and permit a variety of interesting formats to be interpreted. For instance, a JSON string can usually be interpreted as a list or a dictionary type. See the examples below. - For datetime-to-string and string-to-datetime conversions, use sa.datetime_to_str() and sa.str_to_datetime() functions. - For array.array to turicreate.Image conversions, use sa.pixel_array_to_image() Examples -------- >>> sa = turicreate.SArray(['1','2','3','4']) >>> sa.astype(int) dtype: int Rows: 4 [1, 2, 3, 4] Given an SArray of strings that look like dicts, convert to a dictionary type: >>> sa = turicreate.SArray(['{1:2 3:4}', '{a:b c:d}']) >>> sa.astype(dict) dtype: dict Rows: 2 [{1: 2, 3: 4}, {'a': 'b', 'c': 'd'}] """ if (dtype == _Image) and (self.dtype == array.array): raise TypeError("Cannot cast from image type to array with sarray.astype(). Please use sarray.pixel_array_to_image() instead.") with cython_context(): return SArray(_proxy=self.__proxy__.astype(dtype, undefined_on_failure))
python
def astype(self, dtype, undefined_on_failure=False): """ Create a new SArray with all values cast to the given type. Throws an exception if the types are not castable to the given type. Parameters ---------- dtype : {int, float, str, list, array.array, dict, datetime.datetime} The type to cast the elements to in SArray undefined_on_failure: bool, optional If set to True, runtime cast failures will be emitted as missing values rather than failing. Returns ------- out : SArray [dtype] The SArray converted to the type ``dtype``. Notes ----- - The string parsing techniques used to handle conversion to dictionary and list types are quite generic and permit a variety of interesting formats to be interpreted. For instance, a JSON string can usually be interpreted as a list or a dictionary type. See the examples below. - For datetime-to-string and string-to-datetime conversions, use sa.datetime_to_str() and sa.str_to_datetime() functions. - For array.array to turicreate.Image conversions, use sa.pixel_array_to_image() Examples -------- >>> sa = turicreate.SArray(['1','2','3','4']) >>> sa.astype(int) dtype: int Rows: 4 [1, 2, 3, 4] Given an SArray of strings that look like dicts, convert to a dictionary type: >>> sa = turicreate.SArray(['{1:2 3:4}', '{a:b c:d}']) >>> sa.astype(dict) dtype: dict Rows: 2 [{1: 2, 3: 4}, {'a': 'b', 'c': 'd'}] """ if (dtype == _Image) and (self.dtype == array.array): raise TypeError("Cannot cast from image type to array with sarray.astype(). Please use sarray.pixel_array_to_image() instead.") with cython_context(): return SArray(_proxy=self.__proxy__.astype(dtype, undefined_on_failure))
[ "def", "astype", "(", "self", ",", "dtype", ",", "undefined_on_failure", "=", "False", ")", ":", "if", "(", "dtype", "==", "_Image", ")", "and", "(", "self", ".", "dtype", "==", "array", ".", "array", ")", ":", "raise", "TypeError", "(", "\"Cannot cast from image type to array with sarray.astype(). Please use sarray.pixel_array_to_image() instead.\"", ")", "with", "cython_context", "(", ")", ":", "return", "SArray", "(", "_proxy", "=", "self", ".", "__proxy__", ".", "astype", "(", "dtype", ",", "undefined_on_failure", ")", ")" ]
Create a new SArray with all values cast to the given type. Throws an exception if the types are not castable to the given type. Parameters ---------- dtype : {int, float, str, list, array.array, dict, datetime.datetime} The type to cast the elements to in SArray undefined_on_failure: bool, optional If set to True, runtime cast failures will be emitted as missing values rather than failing. Returns ------- out : SArray [dtype] The SArray converted to the type ``dtype``. Notes ----- - The string parsing techniques used to handle conversion to dictionary and list types are quite generic and permit a variety of interesting formats to be interpreted. For instance, a JSON string can usually be interpreted as a list or a dictionary type. See the examples below. - For datetime-to-string and string-to-datetime conversions, use sa.datetime_to_str() and sa.str_to_datetime() functions. - For array.array to turicreate.Image conversions, use sa.pixel_array_to_image() Examples -------- >>> sa = turicreate.SArray(['1','2','3','4']) >>> sa.astype(int) dtype: int Rows: 4 [1, 2, 3, 4] Given an SArray of strings that look like dicts, convert to a dictionary type: >>> sa = turicreate.SArray(['{1:2 3:4}', '{a:b c:d}']) >>> sa.astype(dict) dtype: dict Rows: 2 [{1: 2, 3: 4}, {'a': 'b', 'c': 'd'}]
[ "Create", "a", "new", "SArray", "with", "all", "values", "cast", "to", "the", "given", "type", ".", "Throws", "an", "exception", "if", "the", "types", "are", "not", "castable", "to", "the", "given", "type", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L2480-L2531
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray.clip
def clip(self, lower=float('nan'), upper=float('nan')): """ Create a new SArray with each value clipped to be within the given bounds. In this case, "clipped" means that values below the lower bound will be set to the lower bound value. Values above the upper bound will be set to the upper bound value. This function can operate on SArrays of numeric type as well as array type, in which case each individual element in each array is clipped. By default ``lower`` and ``upper`` are set to ``float('nan')`` which indicates the respective bound should be ignored. The method fails if invoked on an SArray of non-numeric type. Parameters ---------- lower : int, optional The lower bound used to clip. Ignored if equal to ``float('nan')`` (the default). upper : int, optional The upper bound used to clip. Ignored if equal to ``float('nan')`` (the default). Returns ------- out : SArray See Also -------- clip_lower, clip_upper Examples -------- >>> sa = turicreate.SArray([1,2,3]) >>> sa.clip(2,2) dtype: int Rows: 3 [2, 2, 2] """ with cython_context(): return SArray(_proxy=self.__proxy__.clip(lower, upper))
python
def clip(self, lower=float('nan'), upper=float('nan')): """ Create a new SArray with each value clipped to be within the given bounds. In this case, "clipped" means that values below the lower bound will be set to the lower bound value. Values above the upper bound will be set to the upper bound value. This function can operate on SArrays of numeric type as well as array type, in which case each individual element in each array is clipped. By default ``lower`` and ``upper`` are set to ``float('nan')`` which indicates the respective bound should be ignored. The method fails if invoked on an SArray of non-numeric type. Parameters ---------- lower : int, optional The lower bound used to clip. Ignored if equal to ``float('nan')`` (the default). upper : int, optional The upper bound used to clip. Ignored if equal to ``float('nan')`` (the default). Returns ------- out : SArray See Also -------- clip_lower, clip_upper Examples -------- >>> sa = turicreate.SArray([1,2,3]) >>> sa.clip(2,2) dtype: int Rows: 3 [2, 2, 2] """ with cython_context(): return SArray(_proxy=self.__proxy__.clip(lower, upper))
[ "def", "clip", "(", "self", ",", "lower", "=", "float", "(", "'nan'", ")", ",", "upper", "=", "float", "(", "'nan'", ")", ")", ":", "with", "cython_context", "(", ")", ":", "return", "SArray", "(", "_proxy", "=", "self", ".", "__proxy__", ".", "clip", "(", "lower", ",", "upper", ")", ")" ]
Create a new SArray with each value clipped to be within the given bounds. In this case, "clipped" means that values below the lower bound will be set to the lower bound value. Values above the upper bound will be set to the upper bound value. This function can operate on SArrays of numeric type as well as array type, in which case each individual element in each array is clipped. By default ``lower`` and ``upper`` are set to ``float('nan')`` which indicates the respective bound should be ignored. The method fails if invoked on an SArray of non-numeric type. Parameters ---------- lower : int, optional The lower bound used to clip. Ignored if equal to ``float('nan')`` (the default). upper : int, optional The upper bound used to clip. Ignored if equal to ``float('nan')`` (the default). Returns ------- out : SArray See Also -------- clip_lower, clip_upper Examples -------- >>> sa = turicreate.SArray([1,2,3]) >>> sa.clip(2,2) dtype: int Rows: 3 [2, 2, 2]
[ "Create", "a", "new", "SArray", "with", "each", "value", "clipped", "to", "be", "within", "the", "given", "bounds", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L2533-L2573
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray.clip_lower
def clip_lower(self, threshold): """ Create new SArray with all values clipped to the given lower bound. This function can operate on numeric arrays, as well as vector arrays, in which case each individual element in each vector is clipped. Throws an exception if the SArray is empty or the types are non-numeric. Parameters ---------- threshold : float The lower bound used to clip values. Returns ------- out : SArray See Also -------- clip, clip_upper Examples -------- >>> sa = turicreate.SArray([1,2,3]) >>> sa.clip_lower(2) dtype: int Rows: 3 [2, 2, 3] """ with cython_context(): return SArray(_proxy=self.__proxy__.clip(threshold, float('nan')))
python
def clip_lower(self, threshold): """ Create new SArray with all values clipped to the given lower bound. This function can operate on numeric arrays, as well as vector arrays, in which case each individual element in each vector is clipped. Throws an exception if the SArray is empty or the types are non-numeric. Parameters ---------- threshold : float The lower bound used to clip values. Returns ------- out : SArray See Also -------- clip, clip_upper Examples -------- >>> sa = turicreate.SArray([1,2,3]) >>> sa.clip_lower(2) dtype: int Rows: 3 [2, 2, 3] """ with cython_context(): return SArray(_proxy=self.__proxy__.clip(threshold, float('nan')))
[ "def", "clip_lower", "(", "self", ",", "threshold", ")", ":", "with", "cython_context", "(", ")", ":", "return", "SArray", "(", "_proxy", "=", "self", ".", "__proxy__", ".", "clip", "(", "threshold", ",", "float", "(", "'nan'", ")", ")", ")" ]
Create new SArray with all values clipped to the given lower bound. This function can operate on numeric arrays, as well as vector arrays, in which case each individual element in each vector is clipped. Throws an exception if the SArray is empty or the types are non-numeric. Parameters ---------- threshold : float The lower bound used to clip values. Returns ------- out : SArray See Also -------- clip, clip_upper Examples -------- >>> sa = turicreate.SArray([1,2,3]) >>> sa.clip_lower(2) dtype: int Rows: 3 [2, 2, 3]
[ "Create", "new", "SArray", "with", "all", "values", "clipped", "to", "the", "given", "lower", "bound", ".", "This", "function", "can", "operate", "on", "numeric", "arrays", "as", "well", "as", "vector", "arrays", "in", "which", "case", "each", "individual", "element", "in", "each", "vector", "is", "clipped", ".", "Throws", "an", "exception", "if", "the", "SArray", "is", "empty", "or", "the", "types", "are", "non", "-", "numeric", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L2575-L2604
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray.tail
def tail(self, n=10): """ Get an SArray that contains the last n elements in the SArray. Parameters ---------- n : int The number of elements to fetch Returns ------- out : SArray A new SArray which contains the last n rows of the current SArray. """ with cython_context(): return SArray(_proxy=self.__proxy__.tail(n))
python
def tail(self, n=10): """ Get an SArray that contains the last n elements in the SArray. Parameters ---------- n : int The number of elements to fetch Returns ------- out : SArray A new SArray which contains the last n rows of the current SArray. """ with cython_context(): return SArray(_proxy=self.__proxy__.tail(n))
[ "def", "tail", "(", "self", ",", "n", "=", "10", ")", ":", "with", "cython_context", "(", ")", ":", "return", "SArray", "(", "_proxy", "=", "self", ".", "__proxy__", ".", "tail", "(", "n", ")", ")" ]
Get an SArray that contains the last n elements in the SArray. Parameters ---------- n : int The number of elements to fetch Returns ------- out : SArray A new SArray which contains the last n rows of the current SArray.
[ "Get", "an", "SArray", "that", "contains", "the", "last", "n", "elements", "in", "the", "SArray", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L2637-L2652
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray.fillna
def fillna(self, value): """ Create new SArray with all missing values (None or NaN) filled in with the given value. The size of the new SArray will be the same as the original SArray. If the given value is not the same type as the values in the SArray, `fillna` will attempt to convert the value to the original SArray's type. If this fails, an error will be raised. Parameters ---------- value : type convertible to SArray's type The value used to replace all missing values Returns ------- out : SArray A new SArray with all missing values filled """ with cython_context(): return SArray(_proxy = self.__proxy__.fill_missing_values(value))
python
def fillna(self, value): """ Create new SArray with all missing values (None or NaN) filled in with the given value. The size of the new SArray will be the same as the original SArray. If the given value is not the same type as the values in the SArray, `fillna` will attempt to convert the value to the original SArray's type. If this fails, an error will be raised. Parameters ---------- value : type convertible to SArray's type The value used to replace all missing values Returns ------- out : SArray A new SArray with all missing values filled """ with cython_context(): return SArray(_proxy = self.__proxy__.fill_missing_values(value))
[ "def", "fillna", "(", "self", ",", "value", ")", ":", "with", "cython_context", "(", ")", ":", "return", "SArray", "(", "_proxy", "=", "self", ".", "__proxy__", ".", "fill_missing_values", "(", "value", ")", ")" ]
Create new SArray with all missing values (None or NaN) filled in with the given value. The size of the new SArray will be the same as the original SArray. If the given value is not the same type as the values in the SArray, `fillna` will attempt to convert the value to the original SArray's type. If this fails, an error will be raised. Parameters ---------- value : type convertible to SArray's type The value used to replace all missing values Returns ------- out : SArray A new SArray with all missing values filled
[ "Create", "new", "SArray", "with", "all", "missing", "values", "(", "None", "or", "NaN", ")", "filled", "in", "with", "the", "given", "value", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L2673-L2695
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray.is_topk
def is_topk(self, topk=10, reverse=False): """ Create an SArray indicating which elements are in the top k. Entries are '1' if the corresponding element in the current SArray is a part of the top k elements, and '0' if that corresponding element is not. Order is descending by default. Parameters ---------- topk : int The number of elements to determine if 'top' reverse : bool If True, return the topk elements in ascending order Returns ------- out : SArray (of type int) Notes ----- This is used internally by SFrame's topk function. """ with cython_context(): return SArray(_proxy = self.__proxy__.topk_index(topk, reverse))
python
def is_topk(self, topk=10, reverse=False): """ Create an SArray indicating which elements are in the top k. Entries are '1' if the corresponding element in the current SArray is a part of the top k elements, and '0' if that corresponding element is not. Order is descending by default. Parameters ---------- topk : int The number of elements to determine if 'top' reverse : bool If True, return the topk elements in ascending order Returns ------- out : SArray (of type int) Notes ----- This is used internally by SFrame's topk function. """ with cython_context(): return SArray(_proxy = self.__proxy__.topk_index(topk, reverse))
[ "def", "is_topk", "(", "self", ",", "topk", "=", "10", ",", "reverse", "=", "False", ")", ":", "with", "cython_context", "(", ")", ":", "return", "SArray", "(", "_proxy", "=", "self", ".", "__proxy__", ".", "topk_index", "(", "topk", ",", "reverse", ")", ")" ]
Create an SArray indicating which elements are in the top k. Entries are '1' if the corresponding element in the current SArray is a part of the top k elements, and '0' if that corresponding element is not. Order is descending by default. Parameters ---------- topk : int The number of elements to determine if 'top' reverse : bool If True, return the topk elements in ascending order Returns ------- out : SArray (of type int) Notes ----- This is used internally by SFrame's topk function.
[ "Create", "an", "SArray", "indicating", "which", "elements", "are", "in", "the", "top", "k", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L2697-L2722
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray.summary
def summary(self, background=False, sub_sketch_keys=None): """ Summary statistics that can be calculated with one pass over the SArray. Returns a turicreate.Sketch object which can be further queried for many descriptive statistics over this SArray. Many of the statistics are approximate. See the :class:`~turicreate.Sketch` documentation for more detail. Parameters ---------- background : boolean, optional If True, the sketch construction will return immediately and the sketch will be constructed in the background. While this is going on, the sketch can be queried incrementally, but at a performance penalty. Defaults to False. sub_sketch_keys : int | str | list of int | list of str, optional For SArray of dict type, also constructs sketches for a given set of keys, For SArray of array type, also constructs sketches for the given indexes. The sub sketches may be queried using: :py:func:`~turicreate.Sketch.element_sub_sketch()`. Defaults to None in which case no subsketches will be constructed. Returns ------- out : Sketch Sketch object that contains descriptive statistics for this SArray. Many of the statistics are approximate. """ from ..data_structures.sketch import Sketch if (self.dtype == _Image): raise TypeError("summary() is not supported for arrays of image type") if (type(background) != bool): raise TypeError("'background' parameter has to be a boolean value") if (sub_sketch_keys is not None): if (self.dtype != dict and self.dtype != array.array): raise TypeError("sub_sketch_keys is only supported for SArray of dictionary or array type") if not _is_non_string_iterable(sub_sketch_keys): sub_sketch_keys = [sub_sketch_keys] value_types = set([type(i) for i in sub_sketch_keys]) if (len(value_types) != 1): raise ValueError("sub_sketch_keys member values need to have the same type.") value_type = value_types.pop() if (self.dtype == dict and value_type != str): raise TypeError("Only string value(s) can be passed to sub_sketch_keys for SArray of dictionary type. "+ "For dictionary types, sketch summary is computed by casting keys to string values.") if (self.dtype == array.array and value_type != int): raise TypeError("Only int value(s) can be passed to sub_sketch_keys for SArray of array type") else: sub_sketch_keys = list() return Sketch(self, background, sub_sketch_keys = sub_sketch_keys)
python
def summary(self, background=False, sub_sketch_keys=None): """ Summary statistics that can be calculated with one pass over the SArray. Returns a turicreate.Sketch object which can be further queried for many descriptive statistics over this SArray. Many of the statistics are approximate. See the :class:`~turicreate.Sketch` documentation for more detail. Parameters ---------- background : boolean, optional If True, the sketch construction will return immediately and the sketch will be constructed in the background. While this is going on, the sketch can be queried incrementally, but at a performance penalty. Defaults to False. sub_sketch_keys : int | str | list of int | list of str, optional For SArray of dict type, also constructs sketches for a given set of keys, For SArray of array type, also constructs sketches for the given indexes. The sub sketches may be queried using: :py:func:`~turicreate.Sketch.element_sub_sketch()`. Defaults to None in which case no subsketches will be constructed. Returns ------- out : Sketch Sketch object that contains descriptive statistics for this SArray. Many of the statistics are approximate. """ from ..data_structures.sketch import Sketch if (self.dtype == _Image): raise TypeError("summary() is not supported for arrays of image type") if (type(background) != bool): raise TypeError("'background' parameter has to be a boolean value") if (sub_sketch_keys is not None): if (self.dtype != dict and self.dtype != array.array): raise TypeError("sub_sketch_keys is only supported for SArray of dictionary or array type") if not _is_non_string_iterable(sub_sketch_keys): sub_sketch_keys = [sub_sketch_keys] value_types = set([type(i) for i in sub_sketch_keys]) if (len(value_types) != 1): raise ValueError("sub_sketch_keys member values need to have the same type.") value_type = value_types.pop() if (self.dtype == dict and value_type != str): raise TypeError("Only string value(s) can be passed to sub_sketch_keys for SArray of dictionary type. "+ "For dictionary types, sketch summary is computed by casting keys to string values.") if (self.dtype == array.array and value_type != int): raise TypeError("Only int value(s) can be passed to sub_sketch_keys for SArray of array type") else: sub_sketch_keys = list() return Sketch(self, background, sub_sketch_keys = sub_sketch_keys)
[ "def", "summary", "(", "self", ",", "background", "=", "False", ",", "sub_sketch_keys", "=", "None", ")", ":", "from", ".", ".", "data_structures", ".", "sketch", "import", "Sketch", "if", "(", "self", ".", "dtype", "==", "_Image", ")", ":", "raise", "TypeError", "(", "\"summary() is not supported for arrays of image type\"", ")", "if", "(", "type", "(", "background", ")", "!=", "bool", ")", ":", "raise", "TypeError", "(", "\"'background' parameter has to be a boolean value\"", ")", "if", "(", "sub_sketch_keys", "is", "not", "None", ")", ":", "if", "(", "self", ".", "dtype", "!=", "dict", "and", "self", ".", "dtype", "!=", "array", ".", "array", ")", ":", "raise", "TypeError", "(", "\"sub_sketch_keys is only supported for SArray of dictionary or array type\"", ")", "if", "not", "_is_non_string_iterable", "(", "sub_sketch_keys", ")", ":", "sub_sketch_keys", "=", "[", "sub_sketch_keys", "]", "value_types", "=", "set", "(", "[", "type", "(", "i", ")", "for", "i", "in", "sub_sketch_keys", "]", ")", "if", "(", "len", "(", "value_types", ")", "!=", "1", ")", ":", "raise", "ValueError", "(", "\"sub_sketch_keys member values need to have the same type.\"", ")", "value_type", "=", "value_types", ".", "pop", "(", ")", "if", "(", "self", ".", "dtype", "==", "dict", "and", "value_type", "!=", "str", ")", ":", "raise", "TypeError", "(", "\"Only string value(s) can be passed to sub_sketch_keys for SArray of dictionary type. \"", "+", "\"For dictionary types, sketch summary is computed by casting keys to string values.\"", ")", "if", "(", "self", ".", "dtype", "==", "array", ".", "array", "and", "value_type", "!=", "int", ")", ":", "raise", "TypeError", "(", "\"Only int value(s) can be passed to sub_sketch_keys for SArray of array type\"", ")", "else", ":", "sub_sketch_keys", "=", "list", "(", ")", "return", "Sketch", "(", "self", ",", "background", ",", "sub_sketch_keys", "=", "sub_sketch_keys", ")" ]
Summary statistics that can be calculated with one pass over the SArray. Returns a turicreate.Sketch object which can be further queried for many descriptive statistics over this SArray. Many of the statistics are approximate. See the :class:`~turicreate.Sketch` documentation for more detail. Parameters ---------- background : boolean, optional If True, the sketch construction will return immediately and the sketch will be constructed in the background. While this is going on, the sketch can be queried incrementally, but at a performance penalty. Defaults to False. sub_sketch_keys : int | str | list of int | list of str, optional For SArray of dict type, also constructs sketches for a given set of keys, For SArray of array type, also constructs sketches for the given indexes. The sub sketches may be queried using: :py:func:`~turicreate.Sketch.element_sub_sketch()`. Defaults to None in which case no subsketches will be constructed. Returns ------- out : Sketch Sketch object that contains descriptive statistics for this SArray. Many of the statistics are approximate.
[ "Summary", "statistics", "that", "can", "be", "calculated", "with", "one", "pass", "over", "the", "SArray", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L2724-L2775
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray.value_counts
def value_counts(self): """ Return an SFrame containing counts of unique values. The resulting SFrame will be sorted in descending frequency. Returns ------- out : SFrame An SFrame containing 2 columns : 'value', and 'count'. The SFrame will be sorted in descending order by the column 'count'. See Also -------- SFrame.summary Examples -------- >>> sa = turicreate.SArray([1,1,2,2,2,2,3,3,3,3,3,3,3]) >>> sa.value_counts() Columns: value int count int Rows: 3 Data: +-------+-------+ | value | count | +-------+-------+ | 3 | 7 | | 2 | 4 | | 1 | 2 | +-------+-------+ [3 rows x 2 columns] """ from .sframe import SFrame as _SFrame return _SFrame({'value':self}).groupby('value', {'count':_aggregate.COUNT}).sort('count', ascending=False)
python
def value_counts(self): """ Return an SFrame containing counts of unique values. The resulting SFrame will be sorted in descending frequency. Returns ------- out : SFrame An SFrame containing 2 columns : 'value', and 'count'. The SFrame will be sorted in descending order by the column 'count'. See Also -------- SFrame.summary Examples -------- >>> sa = turicreate.SArray([1,1,2,2,2,2,3,3,3,3,3,3,3]) >>> sa.value_counts() Columns: value int count int Rows: 3 Data: +-------+-------+ | value | count | +-------+-------+ | 3 | 7 | | 2 | 4 | | 1 | 2 | +-------+-------+ [3 rows x 2 columns] """ from .sframe import SFrame as _SFrame return _SFrame({'value':self}).groupby('value', {'count':_aggregate.COUNT}).sort('count', ascending=False)
[ "def", "value_counts", "(", "self", ")", ":", "from", ".", "sframe", "import", "SFrame", "as", "_SFrame", "return", "_SFrame", "(", "{", "'value'", ":", "self", "}", ")", ".", "groupby", "(", "'value'", ",", "{", "'count'", ":", "_aggregate", ".", "COUNT", "}", ")", ".", "sort", "(", "'count'", ",", "ascending", "=", "False", ")" ]
Return an SFrame containing counts of unique values. The resulting SFrame will be sorted in descending frequency. Returns ------- out : SFrame An SFrame containing 2 columns : 'value', and 'count'. The SFrame will be sorted in descending order by the column 'count'. See Also -------- SFrame.summary Examples -------- >>> sa = turicreate.SArray([1,1,2,2,2,2,3,3,3,3,3,3,3]) >>> sa.value_counts() Columns: value int count int Rows: 3 Data: +-------+-------+ | value | count | +-------+-------+ | 3 | 7 | | 2 | 4 | | 1 | 2 | +-------+-------+ [3 rows x 2 columns]
[ "Return", "an", "SFrame", "containing", "counts", "of", "unique", "values", ".", "The", "resulting", "SFrame", "will", "be", "sorted", "in", "descending", "frequency", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L2777-L2811
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray.append
def append(self, other): """ Append an SArray to the current SArray. Creates a new SArray with the rows from both SArrays. Both SArrays must be of the same type. Parameters ---------- other : SArray Another SArray whose rows are appended to current SArray. Returns ------- out : SArray A new SArray that contains rows from both SArrays, with rows from the ``other`` SArray coming after all rows from the current SArray. See Also -------- SFrame.append Examples -------- >>> sa = turicreate.SArray([1, 2, 3]) >>> sa2 = turicreate.SArray([4, 5, 6]) >>> sa.append(sa2) dtype: int Rows: 6 [1, 2, 3, 4, 5, 6] """ if type(other) is not SArray: raise RuntimeError("SArray append can only work with SArray") if self.dtype != other.dtype: raise RuntimeError("Data types in both SArrays have to be the same") with cython_context(): return SArray(_proxy = self.__proxy__.append(other.__proxy__))
python
def append(self, other): """ Append an SArray to the current SArray. Creates a new SArray with the rows from both SArrays. Both SArrays must be of the same type. Parameters ---------- other : SArray Another SArray whose rows are appended to current SArray. Returns ------- out : SArray A new SArray that contains rows from both SArrays, with rows from the ``other`` SArray coming after all rows from the current SArray. See Also -------- SFrame.append Examples -------- >>> sa = turicreate.SArray([1, 2, 3]) >>> sa2 = turicreate.SArray([4, 5, 6]) >>> sa.append(sa2) dtype: int Rows: 6 [1, 2, 3, 4, 5, 6] """ if type(other) is not SArray: raise RuntimeError("SArray append can only work with SArray") if self.dtype != other.dtype: raise RuntimeError("Data types in both SArrays have to be the same") with cython_context(): return SArray(_proxy = self.__proxy__.append(other.__proxy__))
[ "def", "append", "(", "self", ",", "other", ")", ":", "if", "type", "(", "other", ")", "is", "not", "SArray", ":", "raise", "RuntimeError", "(", "\"SArray append can only work with SArray\"", ")", "if", "self", ".", "dtype", "!=", "other", ".", "dtype", ":", "raise", "RuntimeError", "(", "\"Data types in both SArrays have to be the same\"", ")", "with", "cython_context", "(", ")", ":", "return", "SArray", "(", "_proxy", "=", "self", ".", "__proxy__", ".", "append", "(", "other", ".", "__proxy__", ")", ")" ]
Append an SArray to the current SArray. Creates a new SArray with the rows from both SArrays. Both SArrays must be of the same type. Parameters ---------- other : SArray Another SArray whose rows are appended to current SArray. Returns ------- out : SArray A new SArray that contains rows from both SArrays, with rows from the ``other`` SArray coming after all rows from the current SArray. See Also -------- SFrame.append Examples -------- >>> sa = turicreate.SArray([1, 2, 3]) >>> sa2 = turicreate.SArray([4, 5, 6]) >>> sa.append(sa2) dtype: int Rows: 6 [1, 2, 3, 4, 5, 6]
[ "Append", "an", "SArray", "to", "the", "current", "SArray", ".", "Creates", "a", "new", "SArray", "with", "the", "rows", "from", "both", "SArrays", ".", "Both", "SArrays", "must", "be", "of", "the", "same", "type", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L2814-L2850
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray.unique
def unique(self): """ Get all unique values in the current SArray. Raises a TypeError if the SArray is of dictionary type. Will not necessarily preserve the order of the given SArray in the new SArray. Returns ------- out : SArray A new SArray that contains the unique values of the current SArray. See Also -------- SFrame.unique """ from .sframe import SFrame as _SFrame tmp_sf = _SFrame() tmp_sf.add_column(self, 'X1', inplace=True) res = tmp_sf.groupby('X1',{}) return SArray(_proxy=res['X1'].__proxy__)
python
def unique(self): """ Get all unique values in the current SArray. Raises a TypeError if the SArray is of dictionary type. Will not necessarily preserve the order of the given SArray in the new SArray. Returns ------- out : SArray A new SArray that contains the unique values of the current SArray. See Also -------- SFrame.unique """ from .sframe import SFrame as _SFrame tmp_sf = _SFrame() tmp_sf.add_column(self, 'X1', inplace=True) res = tmp_sf.groupby('X1',{}) return SArray(_proxy=res['X1'].__proxy__)
[ "def", "unique", "(", "self", ")", ":", "from", ".", "sframe", "import", "SFrame", "as", "_SFrame", "tmp_sf", "=", "_SFrame", "(", ")", "tmp_sf", ".", "add_column", "(", "self", ",", "'X1'", ",", "inplace", "=", "True", ")", "res", "=", "tmp_sf", ".", "groupby", "(", "'X1'", ",", "{", "}", ")", "return", "SArray", "(", "_proxy", "=", "res", "[", "'X1'", "]", ".", "__proxy__", ")" ]
Get all unique values in the current SArray. Raises a TypeError if the SArray is of dictionary type. Will not necessarily preserve the order of the given SArray in the new SArray. Returns ------- out : SArray A new SArray that contains the unique values of the current SArray. See Also -------- SFrame.unique
[ "Get", "all", "unique", "values", "in", "the", "current", "SArray", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L2852-L2876
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray.show
def show(self, title=LABEL_DEFAULT, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT): """ Visualize the SArray. Notes ----- - The plot will render either inline in a Jupyter Notebook, or in a native GUI window, depending on the value provided in `turicreate.visualization.set_target` (defaults to 'auto'). Parameters ---------- title : str The plot title to show for the resulting visualization. If the title is None, the title will be omitted. xlabel : str The X axis label to show for the resulting visualization. If the xlabel is None, the X axis label will be omitted. ylabel : str The Y axis label to show for the resulting visualization. If the ylabel is None, the Y axis label will be omitted. Returns ------- None Examples -------- Suppose 'sa' is an SArray, we can view it using: >>> sa.show() To override the default plot title and axis labels: >>> sa.show(title="My Plot Title", xlabel="My X Axis", ylabel="My Y Axis") """ returned_plot = self.plot(title, xlabel, ylabel) returned_plot.show()
python
def show(self, title=LABEL_DEFAULT, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT): """ Visualize the SArray. Notes ----- - The plot will render either inline in a Jupyter Notebook, or in a native GUI window, depending on the value provided in `turicreate.visualization.set_target` (defaults to 'auto'). Parameters ---------- title : str The plot title to show for the resulting visualization. If the title is None, the title will be omitted. xlabel : str The X axis label to show for the resulting visualization. If the xlabel is None, the X axis label will be omitted. ylabel : str The Y axis label to show for the resulting visualization. If the ylabel is None, the Y axis label will be omitted. Returns ------- None Examples -------- Suppose 'sa' is an SArray, we can view it using: >>> sa.show() To override the default plot title and axis labels: >>> sa.show(title="My Plot Title", xlabel="My X Axis", ylabel="My Y Axis") """ returned_plot = self.plot(title, xlabel, ylabel) returned_plot.show()
[ "def", "show", "(", "self", ",", "title", "=", "LABEL_DEFAULT", ",", "xlabel", "=", "LABEL_DEFAULT", ",", "ylabel", "=", "LABEL_DEFAULT", ")", ":", "returned_plot", "=", "self", ".", "plot", "(", "title", ",", "xlabel", ",", "ylabel", ")", "returned_plot", ".", "show", "(", ")" ]
Visualize the SArray. Notes ----- - The plot will render either inline in a Jupyter Notebook, or in a native GUI window, depending on the value provided in `turicreate.visualization.set_target` (defaults to 'auto'). Parameters ---------- title : str The plot title to show for the resulting visualization. If the title is None, the title will be omitted. xlabel : str The X axis label to show for the resulting visualization. If the xlabel is None, the X axis label will be omitted. ylabel : str The Y axis label to show for the resulting visualization. If the ylabel is None, the Y axis label will be omitted. Returns ------- None Examples -------- Suppose 'sa' is an SArray, we can view it using: >>> sa.show() To override the default plot title and axis labels: >>> sa.show(title="My Plot Title", xlabel="My X Axis", ylabel="My Y Axis")
[ "Visualize", "the", "SArray", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L2905-L2946
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray.plot
def plot(self, title=LABEL_DEFAULT, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT): """ Create a Plot object representing the SArray. Notes ----- - The plot will render either inline in a Jupyter Notebook, or in a native GUI window, depending on the value provided in `turicreate.visualization.set_target` (defaults to 'auto'). Parameters ---------- title : str The plot title to show for the resulting visualization. If the title is None, the title will be omitted. xlabel : str The X axis label to show for the resulting visualization. If the xlabel is None, the X axis label will be omitted. ylabel : str The Y axis label to show for the resulting visualization. If the ylabel is None, the Y axis label will be omitted. Returns ------- out : Plot A :class: Plot object that is the visualization of the SArray. Examples -------- Suppose 'sa' is an SArray, we can create a plot of it using: >>> plt = sa.plot() To override the default plot title and axis labels: >>> plt = sa.plot(title="My Plot Title", xlabel="My X Axis", ylabel="My Y Axis") We can then visualize the plot using: >>> plt.show() """ if title == "": title = " " if xlabel == "": xlabel = " " if ylabel == "": ylabel = " " if title is None: title = "" # C++ otherwise gets "None" as std::string if xlabel is None: xlabel = "" if ylabel is None: ylabel = "" return Plot(self.__proxy__.plot(title, xlabel, ylabel))
python
def plot(self, title=LABEL_DEFAULT, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT): """ Create a Plot object representing the SArray. Notes ----- - The plot will render either inline in a Jupyter Notebook, or in a native GUI window, depending on the value provided in `turicreate.visualization.set_target` (defaults to 'auto'). Parameters ---------- title : str The plot title to show for the resulting visualization. If the title is None, the title will be omitted. xlabel : str The X axis label to show for the resulting visualization. If the xlabel is None, the X axis label will be omitted. ylabel : str The Y axis label to show for the resulting visualization. If the ylabel is None, the Y axis label will be omitted. Returns ------- out : Plot A :class: Plot object that is the visualization of the SArray. Examples -------- Suppose 'sa' is an SArray, we can create a plot of it using: >>> plt = sa.plot() To override the default plot title and axis labels: >>> plt = sa.plot(title="My Plot Title", xlabel="My X Axis", ylabel="My Y Axis") We can then visualize the plot using: >>> plt.show() """ if title == "": title = " " if xlabel == "": xlabel = " " if ylabel == "": ylabel = " " if title is None: title = "" # C++ otherwise gets "None" as std::string if xlabel is None: xlabel = "" if ylabel is None: ylabel = "" return Plot(self.__proxy__.plot(title, xlabel, ylabel))
[ "def", "plot", "(", "self", ",", "title", "=", "LABEL_DEFAULT", ",", "xlabel", "=", "LABEL_DEFAULT", ",", "ylabel", "=", "LABEL_DEFAULT", ")", ":", "if", "title", "==", "\"\"", ":", "title", "=", "\" \"", "if", "xlabel", "==", "\"\"", ":", "xlabel", "=", "\" \"", "if", "ylabel", "==", "\"\"", ":", "ylabel", "=", "\" \"", "if", "title", "is", "None", ":", "title", "=", "\"\"", "# C++ otherwise gets \"None\" as std::string", "if", "xlabel", "is", "None", ":", "xlabel", "=", "\"\"", "if", "ylabel", "is", "None", ":", "ylabel", "=", "\"\"", "return", "Plot", "(", "self", ".", "__proxy__", ".", "plot", "(", "title", ",", "xlabel", ",", "ylabel", ")", ")" ]
Create a Plot object representing the SArray. Notes ----- - The plot will render either inline in a Jupyter Notebook, or in a native GUI window, depending on the value provided in `turicreate.visualization.set_target` (defaults to 'auto'). Parameters ---------- title : str The plot title to show for the resulting visualization. If the title is None, the title will be omitted. xlabel : str The X axis label to show for the resulting visualization. If the xlabel is None, the X axis label will be omitted. ylabel : str The Y axis label to show for the resulting visualization. If the ylabel is None, the Y axis label will be omitted. Returns ------- out : Plot A :class: Plot object that is the visualization of the SArray. Examples -------- Suppose 'sa' is an SArray, we can create a plot of it using: >>> plt = sa.plot() To override the default plot title and axis labels: >>> plt = sa.plot(title="My Plot Title", xlabel="My X Axis", ylabel="My Y Axis") We can then visualize the plot using: >>> plt.show()
[ "Create", "a", "Plot", "object", "representing", "the", "SArray", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L2948-L3006
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray.item_length
def item_length(self): """ Length of each element in the current SArray. Only works on SArrays of dict, array, or list type. If a given element is a missing value, then the output elements is also a missing value. This function is equivalent to the following but more performant: sa_item_len = sa.apply(lambda x: len(x) if x is not None else None) Returns ------- out_sf : SArray A new SArray, each element in the SArray is the len of the corresponding items in original SArray. Examples -------- >>> sa = SArray([ ... {"is_restaurant": 1, "is_electronics": 0}, ... {"is_restaurant": 1, "is_retail": 1, "is_electronics": 0}, ... {"is_restaurant": 0, "is_retail": 1, "is_electronics": 0}, ... {"is_restaurant": 0}, ... {"is_restaurant": 1, "is_electronics": 1}, ... None]) >>> sa.item_length() dtype: int Rows: 6 [2, 3, 3, 1, 2, None] """ if (self.dtype not in [list, dict, array.array]): raise TypeError("item_length() is only applicable for SArray of type list, dict and array.") with cython_context(): return SArray(_proxy = self.__proxy__.item_length())
python
def item_length(self): """ Length of each element in the current SArray. Only works on SArrays of dict, array, or list type. If a given element is a missing value, then the output elements is also a missing value. This function is equivalent to the following but more performant: sa_item_len = sa.apply(lambda x: len(x) if x is not None else None) Returns ------- out_sf : SArray A new SArray, each element in the SArray is the len of the corresponding items in original SArray. Examples -------- >>> sa = SArray([ ... {"is_restaurant": 1, "is_electronics": 0}, ... {"is_restaurant": 1, "is_retail": 1, "is_electronics": 0}, ... {"is_restaurant": 0, "is_retail": 1, "is_electronics": 0}, ... {"is_restaurant": 0}, ... {"is_restaurant": 1, "is_electronics": 1}, ... None]) >>> sa.item_length() dtype: int Rows: 6 [2, 3, 3, 1, 2, None] """ if (self.dtype not in [list, dict, array.array]): raise TypeError("item_length() is only applicable for SArray of type list, dict and array.") with cython_context(): return SArray(_proxy = self.__proxy__.item_length())
[ "def", "item_length", "(", "self", ")", ":", "if", "(", "self", ".", "dtype", "not", "in", "[", "list", ",", "dict", ",", "array", ".", "array", "]", ")", ":", "raise", "TypeError", "(", "\"item_length() is only applicable for SArray of type list, dict and array.\"", ")", "with", "cython_context", "(", ")", ":", "return", "SArray", "(", "_proxy", "=", "self", ".", "__proxy__", ".", "item_length", "(", ")", ")" ]
Length of each element in the current SArray. Only works on SArrays of dict, array, or list type. If a given element is a missing value, then the output elements is also a missing value. This function is equivalent to the following but more performant: sa_item_len = sa.apply(lambda x: len(x) if x is not None else None) Returns ------- out_sf : SArray A new SArray, each element in the SArray is the len of the corresponding items in original SArray. Examples -------- >>> sa = SArray([ ... {"is_restaurant": 1, "is_electronics": 0}, ... {"is_restaurant": 1, "is_retail": 1, "is_electronics": 0}, ... {"is_restaurant": 0, "is_retail": 1, "is_electronics": 0}, ... {"is_restaurant": 0}, ... {"is_restaurant": 1, "is_electronics": 1}, ... None]) >>> sa.item_length() dtype: int Rows: 6 [2, 3, 3, 1, 2, None]
[ "Length", "of", "each", "element", "in", "the", "current", "SArray", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L3008-L3043
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray.random_split
def random_split(self, fraction, seed=None): """ Randomly split the rows of an SArray into two SArrays. The first SArray contains *M* rows, sampled uniformly (without replacement) from the original SArray. *M* is approximately the fraction times the original number of rows. The second SArray contains the remaining rows of the original SArray. Parameters ---------- fraction : float Approximate fraction of the rows to fetch for the first returned SArray. Must be between 0 and 1. seed : int, optional Seed for the random number generator used to split. Returns ------- out : tuple [SArray] Two new SArrays. Examples -------- Suppose we have an SArray with 1,024 rows and we want to randomly split it into training and testing datasets with about a 90%/10% split. >>> sa = turicreate.SArray(range(1024)) >>> sa_train, sa_test = sa.random_split(.9, seed=5) >>> print(len(sa_train), len(sa_test)) 922 102 """ from .sframe import SFrame temporary_sf = SFrame() temporary_sf['X1'] = self (train, test) = temporary_sf.random_split(fraction, seed) return (train['X1'], test['X1'])
python
def random_split(self, fraction, seed=None): """ Randomly split the rows of an SArray into two SArrays. The first SArray contains *M* rows, sampled uniformly (without replacement) from the original SArray. *M* is approximately the fraction times the original number of rows. The second SArray contains the remaining rows of the original SArray. Parameters ---------- fraction : float Approximate fraction of the rows to fetch for the first returned SArray. Must be between 0 and 1. seed : int, optional Seed for the random number generator used to split. Returns ------- out : tuple [SArray] Two new SArrays. Examples -------- Suppose we have an SArray with 1,024 rows and we want to randomly split it into training and testing datasets with about a 90%/10% split. >>> sa = turicreate.SArray(range(1024)) >>> sa_train, sa_test = sa.random_split(.9, seed=5) >>> print(len(sa_train), len(sa_test)) 922 102 """ from .sframe import SFrame temporary_sf = SFrame() temporary_sf['X1'] = self (train, test) = temporary_sf.random_split(fraction, seed) return (train['X1'], test['X1'])
[ "def", "random_split", "(", "self", ",", "fraction", ",", "seed", "=", "None", ")", ":", "from", ".", "sframe", "import", "SFrame", "temporary_sf", "=", "SFrame", "(", ")", "temporary_sf", "[", "'X1'", "]", "=", "self", "(", "train", ",", "test", ")", "=", "temporary_sf", ".", "random_split", "(", "fraction", ",", "seed", ")", "return", "(", "train", "[", "'X1'", "]", ",", "test", "[", "'X1'", "]", ")" ]
Randomly split the rows of an SArray into two SArrays. The first SArray contains *M* rows, sampled uniformly (without replacement) from the original SArray. *M* is approximately the fraction times the original number of rows. The second SArray contains the remaining rows of the original SArray. Parameters ---------- fraction : float Approximate fraction of the rows to fetch for the first returned SArray. Must be between 0 and 1. seed : int, optional Seed for the random number generator used to split. Returns ------- out : tuple [SArray] Two new SArrays. Examples -------- Suppose we have an SArray with 1,024 rows and we want to randomly split it into training and testing datasets with about a 90%/10% split. >>> sa = turicreate.SArray(range(1024)) >>> sa_train, sa_test = sa.random_split(.9, seed=5) >>> print(len(sa_train), len(sa_test)) 922 102
[ "Randomly", "split", "the", "rows", "of", "an", "SArray", "into", "two", "SArrays", ".", "The", "first", "SArray", "contains", "*", "M", "*", "rows", "sampled", "uniformly", "(", "without", "replacement", ")", "from", "the", "original", "SArray", ".", "*", "M", "*", "is", "approximately", "the", "fraction", "times", "the", "original", "number", "of", "rows", ".", "The", "second", "SArray", "contains", "the", "remaining", "rows", "of", "the", "original", "SArray", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L3045-L3081
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray.split_datetime
def split_datetime(self, column_name_prefix = "X", limit=None, timezone=False): """ Splits an SArray of datetime type to multiple columns, return a new SFrame that contains expanded columns. A SArray of datetime will be split by default into an SFrame of 6 columns, one for each year/month/day/hour/minute/second element. **Column Naming** When splitting a SArray of datetime type, new columns are named: prefix.year, prefix.month, etc. The prefix is set by the parameter "column_name_prefix" and defaults to 'X'. If column_name_prefix is None or empty, then no prefix is used. **Timezone Column** If timezone parameter is True, then timezone information is represented as one additional column which is a float shows the offset from GMT(0.0) or from UTC. Parameters ---------- column_name_prefix: str, optional If provided, expanded column names would start with the given prefix. Defaults to "X". limit: list[str], optional Limits the set of datetime elements to expand. Possible values are 'year','month','day','hour','minute','second', 'weekday', 'isoweekday', 'tmweekday', and 'us'. If not provided, only ['year','month','day','hour','minute','second'] are expanded. - 'year': The year number - 'month': A value between 1 and 12 where 1 is January. - 'day': Day of the months. Begins at 1. - 'hour': Hours since midnight. - 'minute': Minutes after the hour. - 'second': Seconds after the minute. - 'us': Microseconds after the second. Between 0 and 999,999. - 'weekday': A value between 0 and 6 where 0 is Monday. - 'isoweekday': A value between 1 and 7 where 1 is Monday. - 'tmweekday': A value between 0 and 7 where 0 is Sunday timezone: bool, optional A boolean parameter that determines whether to show timezone column or not. Defaults to False. Returns ------- out : SFrame A new SFrame that contains all expanded columns Examples -------- To expand only day and year elements of a datetime SArray >>> sa = SArray( [datetime(2011, 1, 21, 7, 7, 21, tzinfo=GMT(0)), datetime(2010, 2, 5, 7, 8, 21, tzinfo=GMT(4.5)]) >>> sa.split_datetime(column_name_prefix=None,limit=['day','year']) Columns: day int year int Rows: 2 Data: +-------+--------+ | day | year | +-------+--------+ | 21 | 2011 | | 5 | 2010 | +-------+--------+ [2 rows x 2 columns] To expand only year and timezone elements of a datetime SArray with timezone column represented as a string. Columns are named with prefix: 'Y.column_name'. >>> sa.split_datetime(column_name_prefix="Y",limit=['year'],timezone=True) Columns: Y.year int Y.timezone float Rows: 2 Data: +----------+---------+ | Y.year | Y.timezone | +----------+---------+ | 2011 | 0.0 | | 2010 | 4.5 | +----------+---------+ [2 rows x 2 columns] """ from .sframe import SFrame as _SFrame if self.dtype != datetime.datetime: raise TypeError("Only column of datetime type is supported.") if column_name_prefix is None: column_name_prefix = "" if six.PY2 and type(column_name_prefix) == unicode: column_name_prefix = column_name_prefix.encode('utf-8') if type(column_name_prefix) != str: raise TypeError("'column_name_prefix' must be a string") # convert limit to column_keys if limit is not None: if not _is_non_string_iterable(limit): raise TypeError("'limit' must be a list") name_types = set([type(i) for i in limit]) if (len(name_types) != 1): raise TypeError("'limit' contains values that are different types") if (name_types.pop() != str): raise TypeError("'limit' must contain string values.") if len(set(limit)) != len(limit): raise ValueError("'limit' contains duplicate values") column_types = [] if(limit is None): limit = ['year','month','day','hour','minute','second'] column_types = [int] * len(limit) if(timezone == True): limit += ['timezone'] column_types += [float] with cython_context(): return _SFrame(_proxy=self.__proxy__.expand(column_name_prefix, limit, column_types))
python
def split_datetime(self, column_name_prefix = "X", limit=None, timezone=False): """ Splits an SArray of datetime type to multiple columns, return a new SFrame that contains expanded columns. A SArray of datetime will be split by default into an SFrame of 6 columns, one for each year/month/day/hour/minute/second element. **Column Naming** When splitting a SArray of datetime type, new columns are named: prefix.year, prefix.month, etc. The prefix is set by the parameter "column_name_prefix" and defaults to 'X'. If column_name_prefix is None or empty, then no prefix is used. **Timezone Column** If timezone parameter is True, then timezone information is represented as one additional column which is a float shows the offset from GMT(0.0) or from UTC. Parameters ---------- column_name_prefix: str, optional If provided, expanded column names would start with the given prefix. Defaults to "X". limit: list[str], optional Limits the set of datetime elements to expand. Possible values are 'year','month','day','hour','minute','second', 'weekday', 'isoweekday', 'tmweekday', and 'us'. If not provided, only ['year','month','day','hour','minute','second'] are expanded. - 'year': The year number - 'month': A value between 1 and 12 where 1 is January. - 'day': Day of the months. Begins at 1. - 'hour': Hours since midnight. - 'minute': Minutes after the hour. - 'second': Seconds after the minute. - 'us': Microseconds after the second. Between 0 and 999,999. - 'weekday': A value between 0 and 6 where 0 is Monday. - 'isoweekday': A value between 1 and 7 where 1 is Monday. - 'tmweekday': A value between 0 and 7 where 0 is Sunday timezone: bool, optional A boolean parameter that determines whether to show timezone column or not. Defaults to False. Returns ------- out : SFrame A new SFrame that contains all expanded columns Examples -------- To expand only day and year elements of a datetime SArray >>> sa = SArray( [datetime(2011, 1, 21, 7, 7, 21, tzinfo=GMT(0)), datetime(2010, 2, 5, 7, 8, 21, tzinfo=GMT(4.5)]) >>> sa.split_datetime(column_name_prefix=None,limit=['day','year']) Columns: day int year int Rows: 2 Data: +-------+--------+ | day | year | +-------+--------+ | 21 | 2011 | | 5 | 2010 | +-------+--------+ [2 rows x 2 columns] To expand only year and timezone elements of a datetime SArray with timezone column represented as a string. Columns are named with prefix: 'Y.column_name'. >>> sa.split_datetime(column_name_prefix="Y",limit=['year'],timezone=True) Columns: Y.year int Y.timezone float Rows: 2 Data: +----------+---------+ | Y.year | Y.timezone | +----------+---------+ | 2011 | 0.0 | | 2010 | 4.5 | +----------+---------+ [2 rows x 2 columns] """ from .sframe import SFrame as _SFrame if self.dtype != datetime.datetime: raise TypeError("Only column of datetime type is supported.") if column_name_prefix is None: column_name_prefix = "" if six.PY2 and type(column_name_prefix) == unicode: column_name_prefix = column_name_prefix.encode('utf-8') if type(column_name_prefix) != str: raise TypeError("'column_name_prefix' must be a string") # convert limit to column_keys if limit is not None: if not _is_non_string_iterable(limit): raise TypeError("'limit' must be a list") name_types = set([type(i) for i in limit]) if (len(name_types) != 1): raise TypeError("'limit' contains values that are different types") if (name_types.pop() != str): raise TypeError("'limit' must contain string values.") if len(set(limit)) != len(limit): raise ValueError("'limit' contains duplicate values") column_types = [] if(limit is None): limit = ['year','month','day','hour','minute','second'] column_types = [int] * len(limit) if(timezone == True): limit += ['timezone'] column_types += [float] with cython_context(): return _SFrame(_proxy=self.__proxy__.expand(column_name_prefix, limit, column_types))
[ "def", "split_datetime", "(", "self", ",", "column_name_prefix", "=", "\"X\"", ",", "limit", "=", "None", ",", "timezone", "=", "False", ")", ":", "from", ".", "sframe", "import", "SFrame", "as", "_SFrame", "if", "self", ".", "dtype", "!=", "datetime", ".", "datetime", ":", "raise", "TypeError", "(", "\"Only column of datetime type is supported.\"", ")", "if", "column_name_prefix", "is", "None", ":", "column_name_prefix", "=", "\"\"", "if", "six", ".", "PY2", "and", "type", "(", "column_name_prefix", ")", "==", "unicode", ":", "column_name_prefix", "=", "column_name_prefix", ".", "encode", "(", "'utf-8'", ")", "if", "type", "(", "column_name_prefix", ")", "!=", "str", ":", "raise", "TypeError", "(", "\"'column_name_prefix' must be a string\"", ")", "# convert limit to column_keys", "if", "limit", "is", "not", "None", ":", "if", "not", "_is_non_string_iterable", "(", "limit", ")", ":", "raise", "TypeError", "(", "\"'limit' must be a list\"", ")", "name_types", "=", "set", "(", "[", "type", "(", "i", ")", "for", "i", "in", "limit", "]", ")", "if", "(", "len", "(", "name_types", ")", "!=", "1", ")", ":", "raise", "TypeError", "(", "\"'limit' contains values that are different types\"", ")", "if", "(", "name_types", ".", "pop", "(", ")", "!=", "str", ")", ":", "raise", "TypeError", "(", "\"'limit' must contain string values.\"", ")", "if", "len", "(", "set", "(", "limit", ")", ")", "!=", "len", "(", "limit", ")", ":", "raise", "ValueError", "(", "\"'limit' contains duplicate values\"", ")", "column_types", "=", "[", "]", "if", "(", "limit", "is", "None", ")", ":", "limit", "=", "[", "'year'", ",", "'month'", ",", "'day'", ",", "'hour'", ",", "'minute'", ",", "'second'", "]", "column_types", "=", "[", "int", "]", "*", "len", "(", "limit", ")", "if", "(", "timezone", "==", "True", ")", ":", "limit", "+=", "[", "'timezone'", "]", "column_types", "+=", "[", "float", "]", "with", "cython_context", "(", ")", ":", "return", "_SFrame", "(", "_proxy", "=", "self", ".", "__proxy__", ".", "expand", "(", "column_name_prefix", ",", "limit", ",", "column_types", ")", ")" ]
Splits an SArray of datetime type to multiple columns, return a new SFrame that contains expanded columns. A SArray of datetime will be split by default into an SFrame of 6 columns, one for each year/month/day/hour/minute/second element. **Column Naming** When splitting a SArray of datetime type, new columns are named: prefix.year, prefix.month, etc. The prefix is set by the parameter "column_name_prefix" and defaults to 'X'. If column_name_prefix is None or empty, then no prefix is used. **Timezone Column** If timezone parameter is True, then timezone information is represented as one additional column which is a float shows the offset from GMT(0.0) or from UTC. Parameters ---------- column_name_prefix: str, optional If provided, expanded column names would start with the given prefix. Defaults to "X". limit: list[str], optional Limits the set of datetime elements to expand. Possible values are 'year','month','day','hour','minute','second', 'weekday', 'isoweekday', 'tmweekday', and 'us'. If not provided, only ['year','month','day','hour','minute','second'] are expanded. - 'year': The year number - 'month': A value between 1 and 12 where 1 is January. - 'day': Day of the months. Begins at 1. - 'hour': Hours since midnight. - 'minute': Minutes after the hour. - 'second': Seconds after the minute. - 'us': Microseconds after the second. Between 0 and 999,999. - 'weekday': A value between 0 and 6 where 0 is Monday. - 'isoweekday': A value between 1 and 7 where 1 is Monday. - 'tmweekday': A value between 0 and 7 where 0 is Sunday timezone: bool, optional A boolean parameter that determines whether to show timezone column or not. Defaults to False. Returns ------- out : SFrame A new SFrame that contains all expanded columns Examples -------- To expand only day and year elements of a datetime SArray >>> sa = SArray( [datetime(2011, 1, 21, 7, 7, 21, tzinfo=GMT(0)), datetime(2010, 2, 5, 7, 8, 21, tzinfo=GMT(4.5)]) >>> sa.split_datetime(column_name_prefix=None,limit=['day','year']) Columns: day int year int Rows: 2 Data: +-------+--------+ | day | year | +-------+--------+ | 21 | 2011 | | 5 | 2010 | +-------+--------+ [2 rows x 2 columns] To expand only year and timezone elements of a datetime SArray with timezone column represented as a string. Columns are named with prefix: 'Y.column_name'. >>> sa.split_datetime(column_name_prefix="Y",limit=['year'],timezone=True) Columns: Y.year int Y.timezone float Rows: 2 Data: +----------+---------+ | Y.year | Y.timezone | +----------+---------+ | 2011 | 0.0 | | 2010 | 4.5 | +----------+---------+ [2 rows x 2 columns]
[ "Splits", "an", "SArray", "of", "datetime", "type", "to", "multiple", "columns", "return", "a", "new", "SFrame", "that", "contains", "expanded", "columns", ".", "A", "SArray", "of", "datetime", "will", "be", "split", "by", "default", "into", "an", "SFrame", "of", "6", "columns", "one", "for", "each", "year", "/", "month", "/", "day", "/", "hour", "/", "minute", "/", "second", "element", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L3083-L3217
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray.stack
def stack(self, new_column_name=None, drop_na=False, new_column_type=None): """ Convert a "wide" SArray to one or two "tall" columns in an SFrame by stacking all values. The stack works only for columns of dict, list, or array type. If the column is dict type, two new columns are created as a result of stacking: one column holds the key and another column holds the value. The rest of the columns are repeated for each key/value pair. If the column is array or list type, one new column is created as a result of stacking. With each row holds one element of the array or list value, and the rest columns from the same original row repeated. The returned SFrame includes the newly created column(s). Parameters -------------- new_column_name : str | list of str, optional The new column name(s). If original column is list/array type, new_column_name must a string. If original column is dict type, new_column_name must be a list of two strings. If not given, column names are generated automatically. drop_na : boolean, optional If True, missing values and empty list/array/dict are all dropped from the resulting column(s). If False, missing values are maintained in stacked column(s). new_column_type : type | list of types, optional The new column types. If original column is a list/array type new_column_type must be a single type, or a list of one type. If original column is of dict type, new_column_type must be a list of two types. If not provided, the types are automatically inferred from the first 100 values of the SFrame. Returns ------- out : SFrame A new SFrame that contains the newly stacked column(s). Examples --------- Suppose 'sa' is an SArray of dict type: >>> sa = turicreate.SArray([{'a':3, 'cat':2}, ... {'a':1, 'the':2}, ... {'the':1, 'dog':3}, ... {}]) [{'a': 3, 'cat': 2}, {'a': 1, 'the': 2}, {'the': 1, 'dog': 3}, {}] Stack would stack all keys in one column and all values in another column: >>> sa.stack(new_column_name=['word', 'count']) +------+-------+ | word | count | +------+-------+ | a | 3 | | cat | 2 | | a | 1 | | the | 2 | | the | 1 | | dog | 3 | | None | None | +------+-------+ [7 rows x 2 columns] Observe that since topic 4 had no words, an empty row is inserted. To drop that row, set drop_na=True in the parameters to stack. """ from .sframe import SFrame as _SFrame return _SFrame({'SArray': self}).stack('SArray', new_column_name=new_column_name, drop_na=drop_na, new_column_type=new_column_type)
python
def stack(self, new_column_name=None, drop_na=False, new_column_type=None): """ Convert a "wide" SArray to one or two "tall" columns in an SFrame by stacking all values. The stack works only for columns of dict, list, or array type. If the column is dict type, two new columns are created as a result of stacking: one column holds the key and another column holds the value. The rest of the columns are repeated for each key/value pair. If the column is array or list type, one new column is created as a result of stacking. With each row holds one element of the array or list value, and the rest columns from the same original row repeated. The returned SFrame includes the newly created column(s). Parameters -------------- new_column_name : str | list of str, optional The new column name(s). If original column is list/array type, new_column_name must a string. If original column is dict type, new_column_name must be a list of two strings. If not given, column names are generated automatically. drop_na : boolean, optional If True, missing values and empty list/array/dict are all dropped from the resulting column(s). If False, missing values are maintained in stacked column(s). new_column_type : type | list of types, optional The new column types. If original column is a list/array type new_column_type must be a single type, or a list of one type. If original column is of dict type, new_column_type must be a list of two types. If not provided, the types are automatically inferred from the first 100 values of the SFrame. Returns ------- out : SFrame A new SFrame that contains the newly stacked column(s). Examples --------- Suppose 'sa' is an SArray of dict type: >>> sa = turicreate.SArray([{'a':3, 'cat':2}, ... {'a':1, 'the':2}, ... {'the':1, 'dog':3}, ... {}]) [{'a': 3, 'cat': 2}, {'a': 1, 'the': 2}, {'the': 1, 'dog': 3}, {}] Stack would stack all keys in one column and all values in another column: >>> sa.stack(new_column_name=['word', 'count']) +------+-------+ | word | count | +------+-------+ | a | 3 | | cat | 2 | | a | 1 | | the | 2 | | the | 1 | | dog | 3 | | None | None | +------+-------+ [7 rows x 2 columns] Observe that since topic 4 had no words, an empty row is inserted. To drop that row, set drop_na=True in the parameters to stack. """ from .sframe import SFrame as _SFrame return _SFrame({'SArray': self}).stack('SArray', new_column_name=new_column_name, drop_na=drop_na, new_column_type=new_column_type)
[ "def", "stack", "(", "self", ",", "new_column_name", "=", "None", ",", "drop_na", "=", "False", ",", "new_column_type", "=", "None", ")", ":", "from", ".", "sframe", "import", "SFrame", "as", "_SFrame", "return", "_SFrame", "(", "{", "'SArray'", ":", "self", "}", ")", ".", "stack", "(", "'SArray'", ",", "new_column_name", "=", "new_column_name", ",", "drop_na", "=", "drop_na", ",", "new_column_type", "=", "new_column_type", ")" ]
Convert a "wide" SArray to one or two "tall" columns in an SFrame by stacking all values. The stack works only for columns of dict, list, or array type. If the column is dict type, two new columns are created as a result of stacking: one column holds the key and another column holds the value. The rest of the columns are repeated for each key/value pair. If the column is array or list type, one new column is created as a result of stacking. With each row holds one element of the array or list value, and the rest columns from the same original row repeated. The returned SFrame includes the newly created column(s). Parameters -------------- new_column_name : str | list of str, optional The new column name(s). If original column is list/array type, new_column_name must a string. If original column is dict type, new_column_name must be a list of two strings. If not given, column names are generated automatically. drop_na : boolean, optional If True, missing values and empty list/array/dict are all dropped from the resulting column(s). If False, missing values are maintained in stacked column(s). new_column_type : type | list of types, optional The new column types. If original column is a list/array type new_column_type must be a single type, or a list of one type. If original column is of dict type, new_column_type must be a list of two types. If not provided, the types are automatically inferred from the first 100 values of the SFrame. Returns ------- out : SFrame A new SFrame that contains the newly stacked column(s). Examples --------- Suppose 'sa' is an SArray of dict type: >>> sa = turicreate.SArray([{'a':3, 'cat':2}, ... {'a':1, 'the':2}, ... {'the':1, 'dog':3}, ... {}]) [{'a': 3, 'cat': 2}, {'a': 1, 'the': 2}, {'the': 1, 'dog': 3}, {}] Stack would stack all keys in one column and all values in another column: >>> sa.stack(new_column_name=['word', 'count']) +------+-------+ | word | count | +------+-------+ | a | 3 | | cat | 2 | | a | 1 | | the | 2 | | the | 1 | | dog | 3 | | None | None | +------+-------+ [7 rows x 2 columns] Observe that since topic 4 had no words, an empty row is inserted. To drop that row, set drop_na=True in the parameters to stack.
[ "Convert", "a", "wide", "SArray", "to", "one", "or", "two", "tall", "columns", "in", "an", "SFrame", "by", "stacking", "all", "values", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L3219-L3294
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray.unpack
def unpack(self, column_name_prefix = "X", column_types=None, na_value=None, limit=None): """ Convert an SArray of list, array, or dict type to an SFrame with multiple columns. `unpack` expands an SArray using the values of each list/array/dict as elements in a new SFrame of multiple columns. For example, an SArray of lists each of length 4 will be expanded into an SFrame of 4 columns, one for each list element. An SArray of lists/arrays of varying size will be expand to a number of columns equal to the longest list/array. An SArray of dictionaries will be expanded into as many columns as there are keys. When unpacking an SArray of list or array type, new columns are named: `column_name_prefix`.0, `column_name_prefix`.1, etc. If unpacking a column of dict type, unpacked columns are named `column_name_prefix`.key1, `column_name_prefix`.key2, etc. When unpacking an SArray of list or dictionary types, missing values in the original element remain as missing values in the resultant columns. If the `na_value` parameter is specified, all values equal to this given value are also replaced with missing values. In an SArray of array.array type, NaN is interpreted as a missing value. :py:func:`turicreate.SFrame.pack_columns()` is the reverse effect of unpack Parameters ---------- column_name_prefix: str, optional If provided, unpacked column names would start with the given prefix. column_types: list[type], optional Column types for the unpacked columns. If not provided, column types are automatically inferred from first 100 rows. Defaults to None. na_value: optional Convert all values that are equal to `na_value` to missing value if specified. limit: list, optional Limits the set of list/array/dict keys to unpack. For list/array SArrays, 'limit' must contain integer indices. For dict SArray, 'limit' must contain dictionary keys. Returns ------- out : SFrame A new SFrame that contains all unpacked columns Examples -------- To unpack a dict SArray >>> sa = SArray([{ 'word': 'a', 'count': 1}, ... { 'word': 'cat', 'count': 2}, ... { 'word': 'is', 'count': 3}, ... { 'word': 'coming','count': 4}]) Normal case of unpacking SArray of type dict: >>> sa.unpack(column_name_prefix=None) Columns: count int word str <BLANKLINE> Rows: 4 <BLANKLINE> Data: +-------+--------+ | count | word | +-------+--------+ | 1 | a | | 2 | cat | | 3 | is | | 4 | coming | +-------+--------+ [4 rows x 2 columns] <BLANKLINE> Unpack only keys with 'word': >>> sa.unpack(limit=['word']) Columns: X.word str <BLANKLINE> Rows: 4 <BLANKLINE> Data: +--------+ | X.word | +--------+ | a | | cat | | is | | coming | +--------+ [4 rows x 1 columns] <BLANKLINE> >>> sa2 = SArray([ ... [1, 0, 1], ... [1, 1, 1], ... [0, 1]]) Convert all zeros to missing values: >>> sa2.unpack(column_types=[int, int, int], na_value=0) Columns: X.0 int X.1 int X.2 int <BLANKLINE> Rows: 3 <BLANKLINE> Data: +------+------+------+ | X.0 | X.1 | X.2 | +------+------+------+ | 1 | None | 1 | | 1 | 1 | 1 | | None | 1 | None | +------+------+------+ [3 rows x 3 columns] <BLANKLINE> """ from .sframe import SFrame as _SFrame if self.dtype not in [dict, array.array, list]: raise TypeError("Only SArray of dict/list/array type supports unpack") if column_name_prefix is None: column_name_prefix = "" if not(isinstance(column_name_prefix, six.string_types)): raise TypeError("'column_name_prefix' must be a string") # validate 'limit' if limit is not None: if (not _is_non_string_iterable(limit)): raise TypeError("'limit' must be a list") name_types = set([type(i) for i in limit]) if (len(name_types) != 1): raise TypeError("'limit' contains values that are different types") # limit value should be numeric if unpacking sarray.array value if (self.dtype != dict) and (name_types.pop() != int): raise TypeError("'limit' must contain integer values.") if len(set(limit)) != len(limit): raise ValueError("'limit' contains duplicate values") if (column_types is not None): if not _is_non_string_iterable(column_types): raise TypeError("column_types must be a list") for column_type in column_types: if (column_type not in (int, float, str, list, dict, array.array)): raise TypeError("column_types contains unsupported types. Supported types are ['float', 'int', 'list', 'dict', 'str', 'array.array']") if limit is not None: if len(limit) != len(column_types): raise ValueError("limit and column_types do not have the same length") elif self.dtype == dict: raise ValueError("if 'column_types' is given, 'limit' has to be provided to unpack dict type.") else: limit = range(len(column_types)) else: head_rows = self.head(100).dropna() lengths = [len(i) for i in head_rows] if len(lengths) == 0 or max(lengths) == 0: raise RuntimeError("Cannot infer number of items from the SArray, SArray may be empty. please explicitly provide column types") # infer column types for dict type at server side, for list and array, infer from client side if self.dtype != dict: length = max(lengths) if limit is None: limit = range(length) else: # adjust the length length = len(limit) if self.dtype == array.array: column_types = [float for i in range(length)] else: column_types = list() for i in limit: t = [(x[i] if ((x is not None) and len(x) > i) else None) for x in head_rows] column_types.append(infer_type_of_list(t)) with cython_context(): if (self.dtype == dict and column_types is None): limit = limit if limit is not None else [] return _SFrame(_proxy=self.__proxy__.unpack_dict(column_name_prefix.encode('utf-8'), limit, na_value)) else: return _SFrame(_proxy=self.__proxy__.unpack(column_name_prefix.encode('utf-8'), limit, column_types, na_value))
python
def unpack(self, column_name_prefix = "X", column_types=None, na_value=None, limit=None): """ Convert an SArray of list, array, or dict type to an SFrame with multiple columns. `unpack` expands an SArray using the values of each list/array/dict as elements in a new SFrame of multiple columns. For example, an SArray of lists each of length 4 will be expanded into an SFrame of 4 columns, one for each list element. An SArray of lists/arrays of varying size will be expand to a number of columns equal to the longest list/array. An SArray of dictionaries will be expanded into as many columns as there are keys. When unpacking an SArray of list or array type, new columns are named: `column_name_prefix`.0, `column_name_prefix`.1, etc. If unpacking a column of dict type, unpacked columns are named `column_name_prefix`.key1, `column_name_prefix`.key2, etc. When unpacking an SArray of list or dictionary types, missing values in the original element remain as missing values in the resultant columns. If the `na_value` parameter is specified, all values equal to this given value are also replaced with missing values. In an SArray of array.array type, NaN is interpreted as a missing value. :py:func:`turicreate.SFrame.pack_columns()` is the reverse effect of unpack Parameters ---------- column_name_prefix: str, optional If provided, unpacked column names would start with the given prefix. column_types: list[type], optional Column types for the unpacked columns. If not provided, column types are automatically inferred from first 100 rows. Defaults to None. na_value: optional Convert all values that are equal to `na_value` to missing value if specified. limit: list, optional Limits the set of list/array/dict keys to unpack. For list/array SArrays, 'limit' must contain integer indices. For dict SArray, 'limit' must contain dictionary keys. Returns ------- out : SFrame A new SFrame that contains all unpacked columns Examples -------- To unpack a dict SArray >>> sa = SArray([{ 'word': 'a', 'count': 1}, ... { 'word': 'cat', 'count': 2}, ... { 'word': 'is', 'count': 3}, ... { 'word': 'coming','count': 4}]) Normal case of unpacking SArray of type dict: >>> sa.unpack(column_name_prefix=None) Columns: count int word str <BLANKLINE> Rows: 4 <BLANKLINE> Data: +-------+--------+ | count | word | +-------+--------+ | 1 | a | | 2 | cat | | 3 | is | | 4 | coming | +-------+--------+ [4 rows x 2 columns] <BLANKLINE> Unpack only keys with 'word': >>> sa.unpack(limit=['word']) Columns: X.word str <BLANKLINE> Rows: 4 <BLANKLINE> Data: +--------+ | X.word | +--------+ | a | | cat | | is | | coming | +--------+ [4 rows x 1 columns] <BLANKLINE> >>> sa2 = SArray([ ... [1, 0, 1], ... [1, 1, 1], ... [0, 1]]) Convert all zeros to missing values: >>> sa2.unpack(column_types=[int, int, int], na_value=0) Columns: X.0 int X.1 int X.2 int <BLANKLINE> Rows: 3 <BLANKLINE> Data: +------+------+------+ | X.0 | X.1 | X.2 | +------+------+------+ | 1 | None | 1 | | 1 | 1 | 1 | | None | 1 | None | +------+------+------+ [3 rows x 3 columns] <BLANKLINE> """ from .sframe import SFrame as _SFrame if self.dtype not in [dict, array.array, list]: raise TypeError("Only SArray of dict/list/array type supports unpack") if column_name_prefix is None: column_name_prefix = "" if not(isinstance(column_name_prefix, six.string_types)): raise TypeError("'column_name_prefix' must be a string") # validate 'limit' if limit is not None: if (not _is_non_string_iterable(limit)): raise TypeError("'limit' must be a list") name_types = set([type(i) for i in limit]) if (len(name_types) != 1): raise TypeError("'limit' contains values that are different types") # limit value should be numeric if unpacking sarray.array value if (self.dtype != dict) and (name_types.pop() != int): raise TypeError("'limit' must contain integer values.") if len(set(limit)) != len(limit): raise ValueError("'limit' contains duplicate values") if (column_types is not None): if not _is_non_string_iterable(column_types): raise TypeError("column_types must be a list") for column_type in column_types: if (column_type not in (int, float, str, list, dict, array.array)): raise TypeError("column_types contains unsupported types. Supported types are ['float', 'int', 'list', 'dict', 'str', 'array.array']") if limit is not None: if len(limit) != len(column_types): raise ValueError("limit and column_types do not have the same length") elif self.dtype == dict: raise ValueError("if 'column_types' is given, 'limit' has to be provided to unpack dict type.") else: limit = range(len(column_types)) else: head_rows = self.head(100).dropna() lengths = [len(i) for i in head_rows] if len(lengths) == 0 or max(lengths) == 0: raise RuntimeError("Cannot infer number of items from the SArray, SArray may be empty. please explicitly provide column types") # infer column types for dict type at server side, for list and array, infer from client side if self.dtype != dict: length = max(lengths) if limit is None: limit = range(length) else: # adjust the length length = len(limit) if self.dtype == array.array: column_types = [float for i in range(length)] else: column_types = list() for i in limit: t = [(x[i] if ((x is not None) and len(x) > i) else None) for x in head_rows] column_types.append(infer_type_of_list(t)) with cython_context(): if (self.dtype == dict and column_types is None): limit = limit if limit is not None else [] return _SFrame(_proxy=self.__proxy__.unpack_dict(column_name_prefix.encode('utf-8'), limit, na_value)) else: return _SFrame(_proxy=self.__proxy__.unpack(column_name_prefix.encode('utf-8'), limit, column_types, na_value))
[ "def", "unpack", "(", "self", ",", "column_name_prefix", "=", "\"X\"", ",", "column_types", "=", "None", ",", "na_value", "=", "None", ",", "limit", "=", "None", ")", ":", "from", ".", "sframe", "import", "SFrame", "as", "_SFrame", "if", "self", ".", "dtype", "not", "in", "[", "dict", ",", "array", ".", "array", ",", "list", "]", ":", "raise", "TypeError", "(", "\"Only SArray of dict/list/array type supports unpack\"", ")", "if", "column_name_prefix", "is", "None", ":", "column_name_prefix", "=", "\"\"", "if", "not", "(", "isinstance", "(", "column_name_prefix", ",", "six", ".", "string_types", ")", ")", ":", "raise", "TypeError", "(", "\"'column_name_prefix' must be a string\"", ")", "# validate 'limit'", "if", "limit", "is", "not", "None", ":", "if", "(", "not", "_is_non_string_iterable", "(", "limit", ")", ")", ":", "raise", "TypeError", "(", "\"'limit' must be a list\"", ")", "name_types", "=", "set", "(", "[", "type", "(", "i", ")", "for", "i", "in", "limit", "]", ")", "if", "(", "len", "(", "name_types", ")", "!=", "1", ")", ":", "raise", "TypeError", "(", "\"'limit' contains values that are different types\"", ")", "# limit value should be numeric if unpacking sarray.array value", "if", "(", "self", ".", "dtype", "!=", "dict", ")", "and", "(", "name_types", ".", "pop", "(", ")", "!=", "int", ")", ":", "raise", "TypeError", "(", "\"'limit' must contain integer values.\"", ")", "if", "len", "(", "set", "(", "limit", ")", ")", "!=", "len", "(", "limit", ")", ":", "raise", "ValueError", "(", "\"'limit' contains duplicate values\"", ")", "if", "(", "column_types", "is", "not", "None", ")", ":", "if", "not", "_is_non_string_iterable", "(", "column_types", ")", ":", "raise", "TypeError", "(", "\"column_types must be a list\"", ")", "for", "column_type", "in", "column_types", ":", "if", "(", "column_type", "not", "in", "(", "int", ",", "float", ",", "str", ",", "list", ",", "dict", ",", "array", ".", "array", ")", ")", ":", "raise", "TypeError", "(", "\"column_types contains unsupported types. Supported types are ['float', 'int', 'list', 'dict', 'str', 'array.array']\"", ")", "if", "limit", "is", "not", "None", ":", "if", "len", "(", "limit", ")", "!=", "len", "(", "column_types", ")", ":", "raise", "ValueError", "(", "\"limit and column_types do not have the same length\"", ")", "elif", "self", ".", "dtype", "==", "dict", ":", "raise", "ValueError", "(", "\"if 'column_types' is given, 'limit' has to be provided to unpack dict type.\"", ")", "else", ":", "limit", "=", "range", "(", "len", "(", "column_types", ")", ")", "else", ":", "head_rows", "=", "self", ".", "head", "(", "100", ")", ".", "dropna", "(", ")", "lengths", "=", "[", "len", "(", "i", ")", "for", "i", "in", "head_rows", "]", "if", "len", "(", "lengths", ")", "==", "0", "or", "max", "(", "lengths", ")", "==", "0", ":", "raise", "RuntimeError", "(", "\"Cannot infer number of items from the SArray, SArray may be empty. please explicitly provide column types\"", ")", "# infer column types for dict type at server side, for list and array, infer from client side", "if", "self", ".", "dtype", "!=", "dict", ":", "length", "=", "max", "(", "lengths", ")", "if", "limit", "is", "None", ":", "limit", "=", "range", "(", "length", ")", "else", ":", "# adjust the length", "length", "=", "len", "(", "limit", ")", "if", "self", ".", "dtype", "==", "array", ".", "array", ":", "column_types", "=", "[", "float", "for", "i", "in", "range", "(", "length", ")", "]", "else", ":", "column_types", "=", "list", "(", ")", "for", "i", "in", "limit", ":", "t", "=", "[", "(", "x", "[", "i", "]", "if", "(", "(", "x", "is", "not", "None", ")", "and", "len", "(", "x", ")", ">", "i", ")", "else", "None", ")", "for", "x", "in", "head_rows", "]", "column_types", ".", "append", "(", "infer_type_of_list", "(", "t", ")", ")", "with", "cython_context", "(", ")", ":", "if", "(", "self", ".", "dtype", "==", "dict", "and", "column_types", "is", "None", ")", ":", "limit", "=", "limit", "if", "limit", "is", "not", "None", "else", "[", "]", "return", "_SFrame", "(", "_proxy", "=", "self", ".", "__proxy__", ".", "unpack_dict", "(", "column_name_prefix", ".", "encode", "(", "'utf-8'", ")", ",", "limit", ",", "na_value", ")", ")", "else", ":", "return", "_SFrame", "(", "_proxy", "=", "self", ".", "__proxy__", ".", "unpack", "(", "column_name_prefix", ".", "encode", "(", "'utf-8'", ")", ",", "limit", ",", "column_types", ",", "na_value", ")", ")" ]
Convert an SArray of list, array, or dict type to an SFrame with multiple columns. `unpack` expands an SArray using the values of each list/array/dict as elements in a new SFrame of multiple columns. For example, an SArray of lists each of length 4 will be expanded into an SFrame of 4 columns, one for each list element. An SArray of lists/arrays of varying size will be expand to a number of columns equal to the longest list/array. An SArray of dictionaries will be expanded into as many columns as there are keys. When unpacking an SArray of list or array type, new columns are named: `column_name_prefix`.0, `column_name_prefix`.1, etc. If unpacking a column of dict type, unpacked columns are named `column_name_prefix`.key1, `column_name_prefix`.key2, etc. When unpacking an SArray of list or dictionary types, missing values in the original element remain as missing values in the resultant columns. If the `na_value` parameter is specified, all values equal to this given value are also replaced with missing values. In an SArray of array.array type, NaN is interpreted as a missing value. :py:func:`turicreate.SFrame.pack_columns()` is the reverse effect of unpack Parameters ---------- column_name_prefix: str, optional If provided, unpacked column names would start with the given prefix. column_types: list[type], optional Column types for the unpacked columns. If not provided, column types are automatically inferred from first 100 rows. Defaults to None. na_value: optional Convert all values that are equal to `na_value` to missing value if specified. limit: list, optional Limits the set of list/array/dict keys to unpack. For list/array SArrays, 'limit' must contain integer indices. For dict SArray, 'limit' must contain dictionary keys. Returns ------- out : SFrame A new SFrame that contains all unpacked columns Examples -------- To unpack a dict SArray >>> sa = SArray([{ 'word': 'a', 'count': 1}, ... { 'word': 'cat', 'count': 2}, ... { 'word': 'is', 'count': 3}, ... { 'word': 'coming','count': 4}]) Normal case of unpacking SArray of type dict: >>> sa.unpack(column_name_prefix=None) Columns: count int word str <BLANKLINE> Rows: 4 <BLANKLINE> Data: +-------+--------+ | count | word | +-------+--------+ | 1 | a | | 2 | cat | | 3 | is | | 4 | coming | +-------+--------+ [4 rows x 2 columns] <BLANKLINE> Unpack only keys with 'word': >>> sa.unpack(limit=['word']) Columns: X.word str <BLANKLINE> Rows: 4 <BLANKLINE> Data: +--------+ | X.word | +--------+ | a | | cat | | is | | coming | +--------+ [4 rows x 1 columns] <BLANKLINE> >>> sa2 = SArray([ ... [1, 0, 1], ... [1, 1, 1], ... [0, 1]]) Convert all zeros to missing values: >>> sa2.unpack(column_types=[int, int, int], na_value=0) Columns: X.0 int X.1 int X.2 int <BLANKLINE> Rows: 3 <BLANKLINE> Data: +------+------+------+ | X.0 | X.1 | X.2 | +------+------+------+ | 1 | None | 1 | | 1 | 1 | 1 | | None | 1 | None | +------+------+------+ [3 rows x 3 columns] <BLANKLINE>
[ "Convert", "an", "SArray", "of", "list", "array", "or", "dict", "type", "to", "an", "SFrame", "with", "multiple", "columns", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L3296-L3493
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray.sort
def sort(self, ascending=True): """ Sort all values in this SArray. Sort only works for sarray of type str, int and float, otherwise TypeError will be raised. Creates a new, sorted SArray. Parameters ---------- ascending: boolean, optional If true, the sarray values are sorted in ascending order, otherwise, descending order. Returns ------- out: SArray Examples -------- >>> sa = SArray([3,2,1]) >>> sa.sort() dtype: int Rows: 3 [1, 2, 3] """ from .sframe import SFrame as _SFrame if self.dtype not in (int, float, str, datetime.datetime): raise TypeError("Only sarray with type (int, float, str, datetime.datetime) can be sorted") sf = _SFrame() sf['a'] = self return sf.sort('a', ascending)['a']
python
def sort(self, ascending=True): """ Sort all values in this SArray. Sort only works for sarray of type str, int and float, otherwise TypeError will be raised. Creates a new, sorted SArray. Parameters ---------- ascending: boolean, optional If true, the sarray values are sorted in ascending order, otherwise, descending order. Returns ------- out: SArray Examples -------- >>> sa = SArray([3,2,1]) >>> sa.sort() dtype: int Rows: 3 [1, 2, 3] """ from .sframe import SFrame as _SFrame if self.dtype not in (int, float, str, datetime.datetime): raise TypeError("Only sarray with type (int, float, str, datetime.datetime) can be sorted") sf = _SFrame() sf['a'] = self return sf.sort('a', ascending)['a']
[ "def", "sort", "(", "self", ",", "ascending", "=", "True", ")", ":", "from", ".", "sframe", "import", "SFrame", "as", "_SFrame", "if", "self", ".", "dtype", "not", "in", "(", "int", ",", "float", ",", "str", ",", "datetime", ".", "datetime", ")", ":", "raise", "TypeError", "(", "\"Only sarray with type (int, float, str, datetime.datetime) can be sorted\"", ")", "sf", "=", "_SFrame", "(", ")", "sf", "[", "'a'", "]", "=", "self", "return", "sf", ".", "sort", "(", "'a'", ",", "ascending", ")", "[", "'a'", "]" ]
Sort all values in this SArray. Sort only works for sarray of type str, int and float, otherwise TypeError will be raised. Creates a new, sorted SArray. Parameters ---------- ascending: boolean, optional If true, the sarray values are sorted in ascending order, otherwise, descending order. Returns ------- out: SArray Examples -------- >>> sa = SArray([3,2,1]) >>> sa.sort() dtype: int Rows: 3 [1, 2, 3]
[ "Sort", "all", "values", "in", "this", "SArray", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L3495-L3526
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray.rolling_sum
def rolling_sum(self, window_start, window_end, min_observations=None): """ Calculate a new SArray of the sum of different subsets over this SArray. Also known as a "moving sum" or "running sum". The subset that the sum is calculated over is defined as an inclusive range relative to the position to each value in the SArray, using `window_start` and `window_end`. For a better understanding of this, see the examples below. Parameters ---------- window_start : int The start of the subset to calculate the sum relative to the current value. window_end : int The end of the subset to calculate the sum relative to the current value. Must be greater than `window_start`. min_observations : int Minimum number of non-missing observations in window required to calculate the sum (otherwise result is None). None signifies that the entire window must not include a missing value. A negative number throws an error. Returns ------- out : SArray Examples -------- >>> import pandas >>> sa = SArray([1,2,3,4,5]) >>> series = pandas.Series([1,2,3,4,5]) A rolling sum with a window including the previous 2 entries including the current: >>> sa.rolling_sum(-2,0) dtype: int Rows: 5 [None, None, 6, 9, 12] Pandas equivalent: >>> pandas.rolling_sum(series, 3) 0 NaN 1 NaN 2 6 3 9 4 12 dtype: float64 Same rolling sum operation, but 2 minimum observations: >>> sa.rolling_sum(-2,0,min_observations=2) dtype: int Rows: 5 [None, 3, 6, 9, 12] Pandas equivalent: >>> pandas.rolling_sum(series, 3, min_periods=2) 0 NaN 1 3 2 6 3 9 4 12 dtype: float64 A rolling sum with a size of 3, centered around the current: >>> sa.rolling_sum(-1,1) dtype: int Rows: 5 [None, 6, 9, 12, None] Pandas equivalent: >>> pandas.rolling_sum(series, 3, center=True) 0 NaN 1 6 2 9 3 12 4 NaN dtype: float64 A rolling sum with a window including the current and the 2 entries following: >>> sa.rolling_sum(0,2) dtype: int Rows: 5 [6, 9, 12, None, None] A rolling sum with a window including the previous 2 entries NOT including the current: >>> sa.rolling_sum(-2,-1) dtype: int Rows: 5 [None, None, 3, 5, 7] """ min_observations = self.__check_min_observations(min_observations) agg_op = None if self.dtype is array.array: agg_op = '__builtin__vector__sum__' else: agg_op = '__builtin__sum__' return SArray(_proxy=self.__proxy__.builtin_rolling_apply(agg_op, window_start, window_end, min_observations))
python
def rolling_sum(self, window_start, window_end, min_observations=None): """ Calculate a new SArray of the sum of different subsets over this SArray. Also known as a "moving sum" or "running sum". The subset that the sum is calculated over is defined as an inclusive range relative to the position to each value in the SArray, using `window_start` and `window_end`. For a better understanding of this, see the examples below. Parameters ---------- window_start : int The start of the subset to calculate the sum relative to the current value. window_end : int The end of the subset to calculate the sum relative to the current value. Must be greater than `window_start`. min_observations : int Minimum number of non-missing observations in window required to calculate the sum (otherwise result is None). None signifies that the entire window must not include a missing value. A negative number throws an error. Returns ------- out : SArray Examples -------- >>> import pandas >>> sa = SArray([1,2,3,4,5]) >>> series = pandas.Series([1,2,3,4,5]) A rolling sum with a window including the previous 2 entries including the current: >>> sa.rolling_sum(-2,0) dtype: int Rows: 5 [None, None, 6, 9, 12] Pandas equivalent: >>> pandas.rolling_sum(series, 3) 0 NaN 1 NaN 2 6 3 9 4 12 dtype: float64 Same rolling sum operation, but 2 minimum observations: >>> sa.rolling_sum(-2,0,min_observations=2) dtype: int Rows: 5 [None, 3, 6, 9, 12] Pandas equivalent: >>> pandas.rolling_sum(series, 3, min_periods=2) 0 NaN 1 3 2 6 3 9 4 12 dtype: float64 A rolling sum with a size of 3, centered around the current: >>> sa.rolling_sum(-1,1) dtype: int Rows: 5 [None, 6, 9, 12, None] Pandas equivalent: >>> pandas.rolling_sum(series, 3, center=True) 0 NaN 1 6 2 9 3 12 4 NaN dtype: float64 A rolling sum with a window including the current and the 2 entries following: >>> sa.rolling_sum(0,2) dtype: int Rows: 5 [6, 9, 12, None, None] A rolling sum with a window including the previous 2 entries NOT including the current: >>> sa.rolling_sum(-2,-1) dtype: int Rows: 5 [None, None, 3, 5, 7] """ min_observations = self.__check_min_observations(min_observations) agg_op = None if self.dtype is array.array: agg_op = '__builtin__vector__sum__' else: agg_op = '__builtin__sum__' return SArray(_proxy=self.__proxy__.builtin_rolling_apply(agg_op, window_start, window_end, min_observations))
[ "def", "rolling_sum", "(", "self", ",", "window_start", ",", "window_end", ",", "min_observations", "=", "None", ")", ":", "min_observations", "=", "self", ".", "__check_min_observations", "(", "min_observations", ")", "agg_op", "=", "None", "if", "self", ".", "dtype", "is", "array", ".", "array", ":", "agg_op", "=", "'__builtin__vector__sum__'", "else", ":", "agg_op", "=", "'__builtin__sum__'", "return", "SArray", "(", "_proxy", "=", "self", ".", "__proxy__", ".", "builtin_rolling_apply", "(", "agg_op", ",", "window_start", ",", "window_end", ",", "min_observations", ")", ")" ]
Calculate a new SArray of the sum of different subsets over this SArray. Also known as a "moving sum" or "running sum". The subset that the sum is calculated over is defined as an inclusive range relative to the position to each value in the SArray, using `window_start` and `window_end`. For a better understanding of this, see the examples below. Parameters ---------- window_start : int The start of the subset to calculate the sum relative to the current value. window_end : int The end of the subset to calculate the sum relative to the current value. Must be greater than `window_start`. min_observations : int Minimum number of non-missing observations in window required to calculate the sum (otherwise result is None). None signifies that the entire window must not include a missing value. A negative number throws an error. Returns ------- out : SArray Examples -------- >>> import pandas >>> sa = SArray([1,2,3,4,5]) >>> series = pandas.Series([1,2,3,4,5]) A rolling sum with a window including the previous 2 entries including the current: >>> sa.rolling_sum(-2,0) dtype: int Rows: 5 [None, None, 6, 9, 12] Pandas equivalent: >>> pandas.rolling_sum(series, 3) 0 NaN 1 NaN 2 6 3 9 4 12 dtype: float64 Same rolling sum operation, but 2 minimum observations: >>> sa.rolling_sum(-2,0,min_observations=2) dtype: int Rows: 5 [None, 3, 6, 9, 12] Pandas equivalent: >>> pandas.rolling_sum(series, 3, min_periods=2) 0 NaN 1 3 2 6 3 9 4 12 dtype: float64 A rolling sum with a size of 3, centered around the current: >>> sa.rolling_sum(-1,1) dtype: int Rows: 5 [None, 6, 9, 12, None] Pandas equivalent: >>> pandas.rolling_sum(series, 3, center=True) 0 NaN 1 6 2 9 3 12 4 NaN dtype: float64 A rolling sum with a window including the current and the 2 entries following: >>> sa.rolling_sum(0,2) dtype: int Rows: 5 [6, 9, 12, None, None] A rolling sum with a window including the previous 2 entries NOT including the current: >>> sa.rolling_sum(-2,-1) dtype: int Rows: 5 [None, None, 3, 5, 7]
[ "Calculate", "a", "new", "SArray", "of", "the", "sum", "of", "different", "subsets", "over", "this", "SArray", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L3640-L3743
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray.rolling_max
def rolling_max(self, window_start, window_end, min_observations=None): """ Calculate a new SArray of the maximum value of different subsets over this SArray. The subset that the maximum is calculated over is defined as an inclusive range relative to the position to each value in the SArray, using `window_start` and `window_end`. For a better understanding of this, see the examples below. Parameters ---------- window_start : int The start of the subset to calculate the maximum relative to the current value. window_end : int The end of the subset to calculate the maximum relative to the current value. Must be greater than `window_start`. min_observations : int Minimum number of non-missing observations in window required to calculate the maximum (otherwise result is None). None signifies that the entire window must not include a missing value. A negative number throws an error. Returns ------- out : SArray Examples -------- >>> import pandas >>> sa = SArray([1,2,3,4,5]) >>> series = pandas.Series([1,2,3,4,5]) A rolling max with a window including the previous 2 entries including the current: >>> sa.rolling_max(-2,0) dtype: int Rows: 5 [None, None, 3, 4, 5] Pandas equivalent: >>> pandas.rolling_max(series, 3) 0 NaN 1 NaN 2 3 3 4 4 5 dtype: float64 Same rolling max operation, but 2 minimum observations: >>> sa.rolling_max(-2,0,min_observations=2) dtype: int Rows: 5 [None, 2, 3, 4, 5] Pandas equivalent: >>> pandas.rolling_max(series, 3, min_periods=2) 0 NaN 1 2 2 3 3 4 4 5 dtype: float64 A rolling max with a size of 3, centered around the current: >>> sa.rolling_max(-1,1) dtype: int Rows: 5 [None, 3, 4, 5, None] Pandas equivalent: >>> pandas.rolling_max(series, 3, center=True) 0 NaN 1 3 2 4 3 5 4 NaN dtype: float64 A rolling max with a window including the current and the 2 entries following: >>> sa.rolling_max(0,2) dtype: int Rows: 5 [3, 4, 5, None, None] A rolling max with a window including the previous 2 entries NOT including the current: >>> sa.rolling_max(-2,-1) dtype: int Rows: 5 [None, None, 2, 3, 4] """ min_observations = self.__check_min_observations(min_observations) agg_op = '__builtin__max__' return SArray(_proxy=self.__proxy__.builtin_rolling_apply(agg_op, window_start, window_end, min_observations))
python
def rolling_max(self, window_start, window_end, min_observations=None): """ Calculate a new SArray of the maximum value of different subsets over this SArray. The subset that the maximum is calculated over is defined as an inclusive range relative to the position to each value in the SArray, using `window_start` and `window_end`. For a better understanding of this, see the examples below. Parameters ---------- window_start : int The start of the subset to calculate the maximum relative to the current value. window_end : int The end of the subset to calculate the maximum relative to the current value. Must be greater than `window_start`. min_observations : int Minimum number of non-missing observations in window required to calculate the maximum (otherwise result is None). None signifies that the entire window must not include a missing value. A negative number throws an error. Returns ------- out : SArray Examples -------- >>> import pandas >>> sa = SArray([1,2,3,4,5]) >>> series = pandas.Series([1,2,3,4,5]) A rolling max with a window including the previous 2 entries including the current: >>> sa.rolling_max(-2,0) dtype: int Rows: 5 [None, None, 3, 4, 5] Pandas equivalent: >>> pandas.rolling_max(series, 3) 0 NaN 1 NaN 2 3 3 4 4 5 dtype: float64 Same rolling max operation, but 2 minimum observations: >>> sa.rolling_max(-2,0,min_observations=2) dtype: int Rows: 5 [None, 2, 3, 4, 5] Pandas equivalent: >>> pandas.rolling_max(series, 3, min_periods=2) 0 NaN 1 2 2 3 3 4 4 5 dtype: float64 A rolling max with a size of 3, centered around the current: >>> sa.rolling_max(-1,1) dtype: int Rows: 5 [None, 3, 4, 5, None] Pandas equivalent: >>> pandas.rolling_max(series, 3, center=True) 0 NaN 1 3 2 4 3 5 4 NaN dtype: float64 A rolling max with a window including the current and the 2 entries following: >>> sa.rolling_max(0,2) dtype: int Rows: 5 [3, 4, 5, None, None] A rolling max with a window including the previous 2 entries NOT including the current: >>> sa.rolling_max(-2,-1) dtype: int Rows: 5 [None, None, 2, 3, 4] """ min_observations = self.__check_min_observations(min_observations) agg_op = '__builtin__max__' return SArray(_proxy=self.__proxy__.builtin_rolling_apply(agg_op, window_start, window_end, min_observations))
[ "def", "rolling_max", "(", "self", ",", "window_start", ",", "window_end", ",", "min_observations", "=", "None", ")", ":", "min_observations", "=", "self", ".", "__check_min_observations", "(", "min_observations", ")", "agg_op", "=", "'__builtin__max__'", "return", "SArray", "(", "_proxy", "=", "self", ".", "__proxy__", ".", "builtin_rolling_apply", "(", "agg_op", ",", "window_start", ",", "window_end", ",", "min_observations", ")", ")" ]
Calculate a new SArray of the maximum value of different subsets over this SArray. The subset that the maximum is calculated over is defined as an inclusive range relative to the position to each value in the SArray, using `window_start` and `window_end`. For a better understanding of this, see the examples below. Parameters ---------- window_start : int The start of the subset to calculate the maximum relative to the current value. window_end : int The end of the subset to calculate the maximum relative to the current value. Must be greater than `window_start`. min_observations : int Minimum number of non-missing observations in window required to calculate the maximum (otherwise result is None). None signifies that the entire window must not include a missing value. A negative number throws an error. Returns ------- out : SArray Examples -------- >>> import pandas >>> sa = SArray([1,2,3,4,5]) >>> series = pandas.Series([1,2,3,4,5]) A rolling max with a window including the previous 2 entries including the current: >>> sa.rolling_max(-2,0) dtype: int Rows: 5 [None, None, 3, 4, 5] Pandas equivalent: >>> pandas.rolling_max(series, 3) 0 NaN 1 NaN 2 3 3 4 4 5 dtype: float64 Same rolling max operation, but 2 minimum observations: >>> sa.rolling_max(-2,0,min_observations=2) dtype: int Rows: 5 [None, 2, 3, 4, 5] Pandas equivalent: >>> pandas.rolling_max(series, 3, min_periods=2) 0 NaN 1 2 2 3 3 4 4 5 dtype: float64 A rolling max with a size of 3, centered around the current: >>> sa.rolling_max(-1,1) dtype: int Rows: 5 [None, 3, 4, 5, None] Pandas equivalent: >>> pandas.rolling_max(series, 3, center=True) 0 NaN 1 3 2 4 3 5 4 NaN dtype: float64 A rolling max with a window including the current and the 2 entries following: >>> sa.rolling_max(0,2) dtype: int Rows: 5 [3, 4, 5, None, None] A rolling max with a window including the previous 2 entries NOT including the current: >>> sa.rolling_max(-2,-1) dtype: int Rows: 5 [None, None, 2, 3, 4]
[ "Calculate", "a", "new", "SArray", "of", "the", "maximum", "value", "of", "different", "subsets", "over", "this", "SArray", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L3745-L3843
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray.rolling_count
def rolling_count(self, window_start, window_end): """ Count the number of non-NULL values of different subsets over this SArray. The subset that the count is executed on is defined as an inclusive range relative to the position to each value in the SArray, using `window_start` and `window_end`. For a better understanding of this, see the examples below. Parameters ---------- window_start : int The start of the subset to count relative to the current value. window_end : int The end of the subset to count relative to the current value. Must be greater than `window_start`. Returns ------- out : SArray Examples -------- >>> import pandas >>> sa = SArray([1,2,3,None,5]) >>> series = pandas.Series([1,2,3,None,5]) A rolling count with a window including the previous 2 entries including the current: >>> sa.rolling_count(-2,0) dtype: int Rows: 5 [1, 2, 3, 2, 2] Pandas equivalent: >>> pandas.rolling_count(series, 3) 0 1 1 2 2 3 3 2 4 2 dtype: float64 A rolling count with a size of 3, centered around the current: >>> sa.rolling_count(-1,1) dtype: int Rows: 5 [2, 3, 2, 2, 1] Pandas equivalent: >>> pandas.rolling_count(series, 3, center=True) 0 2 1 3 2 2 3 2 4 1 dtype: float64 A rolling count with a window including the current and the 2 entries following: >>> sa.rolling_count(0,2) dtype: int Rows: 5 [3, 2, 2, 1, 1] A rolling count with a window including the previous 2 entries NOT including the current: >>> sa.rolling_count(-2,-1) dtype: int Rows: 5 [0, 1, 2, 2, 1] """ agg_op = '__builtin__nonnull__count__' return SArray(_proxy=self.__proxy__.builtin_rolling_apply(agg_op, window_start, window_end, 0))
python
def rolling_count(self, window_start, window_end): """ Count the number of non-NULL values of different subsets over this SArray. The subset that the count is executed on is defined as an inclusive range relative to the position to each value in the SArray, using `window_start` and `window_end`. For a better understanding of this, see the examples below. Parameters ---------- window_start : int The start of the subset to count relative to the current value. window_end : int The end of the subset to count relative to the current value. Must be greater than `window_start`. Returns ------- out : SArray Examples -------- >>> import pandas >>> sa = SArray([1,2,3,None,5]) >>> series = pandas.Series([1,2,3,None,5]) A rolling count with a window including the previous 2 entries including the current: >>> sa.rolling_count(-2,0) dtype: int Rows: 5 [1, 2, 3, 2, 2] Pandas equivalent: >>> pandas.rolling_count(series, 3) 0 1 1 2 2 3 3 2 4 2 dtype: float64 A rolling count with a size of 3, centered around the current: >>> sa.rolling_count(-1,1) dtype: int Rows: 5 [2, 3, 2, 2, 1] Pandas equivalent: >>> pandas.rolling_count(series, 3, center=True) 0 2 1 3 2 2 3 2 4 1 dtype: float64 A rolling count with a window including the current and the 2 entries following: >>> sa.rolling_count(0,2) dtype: int Rows: 5 [3, 2, 2, 1, 1] A rolling count with a window including the previous 2 entries NOT including the current: >>> sa.rolling_count(-2,-1) dtype: int Rows: 5 [0, 1, 2, 2, 1] """ agg_op = '__builtin__nonnull__count__' return SArray(_proxy=self.__proxy__.builtin_rolling_apply(agg_op, window_start, window_end, 0))
[ "def", "rolling_count", "(", "self", ",", "window_start", ",", "window_end", ")", ":", "agg_op", "=", "'__builtin__nonnull__count__'", "return", "SArray", "(", "_proxy", "=", "self", ".", "__proxy__", ".", "builtin_rolling_apply", "(", "agg_op", ",", "window_start", ",", "window_end", ",", "0", ")", ")" ]
Count the number of non-NULL values of different subsets over this SArray. The subset that the count is executed on is defined as an inclusive range relative to the position to each value in the SArray, using `window_start` and `window_end`. For a better understanding of this, see the examples below. Parameters ---------- window_start : int The start of the subset to count relative to the current value. window_end : int The end of the subset to count relative to the current value. Must be greater than `window_start`. Returns ------- out : SArray Examples -------- >>> import pandas >>> sa = SArray([1,2,3,None,5]) >>> series = pandas.Series([1,2,3,None,5]) A rolling count with a window including the previous 2 entries including the current: >>> sa.rolling_count(-2,0) dtype: int Rows: 5 [1, 2, 3, 2, 2] Pandas equivalent: >>> pandas.rolling_count(series, 3) 0 1 1 2 2 3 3 2 4 2 dtype: float64 A rolling count with a size of 3, centered around the current: >>> sa.rolling_count(-1,1) dtype: int Rows: 5 [2, 3, 2, 2, 1] Pandas equivalent: >>> pandas.rolling_count(series, 3, center=True) 0 2 1 3 2 2 3 2 4 1 dtype: float64 A rolling count with a window including the current and the 2 entries following: >>> sa.rolling_count(0,2) dtype: int Rows: 5 [3, 2, 2, 1, 1] A rolling count with a window including the previous 2 entries NOT including the current: >>> sa.rolling_count(-2,-1) dtype: int Rows: 5 [0, 1, 2, 2, 1]
[ "Count", "the", "number", "of", "non", "-", "NULL", "values", "of", "different", "subsets", "over", "this", "SArray", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L4146-L4221
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray.cumulative_sum
def cumulative_sum(self): """ Return the cumulative sum of the elements in the SArray. Returns an SArray where each element in the output corresponds to the sum of all the elements preceding and including it. The SArray is expected to be of numeric type (int, float), or a numeric vector type. Returns ------- out : sarray[int, float, array.array] Notes ----- - Missing values are ignored while performing the cumulative aggregate operation. - For SArray's of type array.array, all entries are expected to be of the same size. Examples -------- >>> sa = SArray([1, 2, 3, 4, 5]) >>> sa.cumulative_sum() dtype: int rows: 3 [1, 3, 6, 10, 15] """ from .. import extensions agg_op = "__builtin__cum_sum__" return SArray(_proxy = self.__proxy__.builtin_cumulative_aggregate(agg_op))
python
def cumulative_sum(self): """ Return the cumulative sum of the elements in the SArray. Returns an SArray where each element in the output corresponds to the sum of all the elements preceding and including it. The SArray is expected to be of numeric type (int, float), or a numeric vector type. Returns ------- out : sarray[int, float, array.array] Notes ----- - Missing values are ignored while performing the cumulative aggregate operation. - For SArray's of type array.array, all entries are expected to be of the same size. Examples -------- >>> sa = SArray([1, 2, 3, 4, 5]) >>> sa.cumulative_sum() dtype: int rows: 3 [1, 3, 6, 10, 15] """ from .. import extensions agg_op = "__builtin__cum_sum__" return SArray(_proxy = self.__proxy__.builtin_cumulative_aggregate(agg_op))
[ "def", "cumulative_sum", "(", "self", ")", ":", "from", ".", ".", "import", "extensions", "agg_op", "=", "\"__builtin__cum_sum__\"", "return", "SArray", "(", "_proxy", "=", "self", ".", "__proxy__", ".", "builtin_cumulative_aggregate", "(", "agg_op", ")", ")" ]
Return the cumulative sum of the elements in the SArray. Returns an SArray where each element in the output corresponds to the sum of all the elements preceding and including it. The SArray is expected to be of numeric type (int, float), or a numeric vector type. Returns ------- out : sarray[int, float, array.array] Notes ----- - Missing values are ignored while performing the cumulative aggregate operation. - For SArray's of type array.array, all entries are expected to be of the same size. Examples -------- >>> sa = SArray([1, 2, 3, 4, 5]) >>> sa.cumulative_sum() dtype: int rows: 3 [1, 3, 6, 10, 15]
[ "Return", "the", "cumulative", "sum", "of", "the", "elements", "in", "the", "SArray", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L4223-L4252
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray.cumulative_mean
def cumulative_mean(self): """ Return the cumulative mean of the elements in the SArray. Returns an SArray where each element in the output corresponds to the mean value of all the elements preceding and including it. The SArray is expected to be of numeric type (int, float), or a numeric vector type. Returns ------- out : Sarray[float, array.array] Notes ----- - Missing values are ignored while performing the cumulative aggregate operation. - For SArray's of type array.array, all entries are expected to be of the same size. Examples -------- >>> sa = SArray([1, 2, 3, 4, 5]) >>> sa.cumulative_mean() dtype: float rows: 3 [1, 1.5, 2, 2.5, 3] """ from .. import extensions agg_op = "__builtin__cum_avg__" return SArray(_proxy = self.__proxy__.builtin_cumulative_aggregate(agg_op))
python
def cumulative_mean(self): """ Return the cumulative mean of the elements in the SArray. Returns an SArray where each element in the output corresponds to the mean value of all the elements preceding and including it. The SArray is expected to be of numeric type (int, float), or a numeric vector type. Returns ------- out : Sarray[float, array.array] Notes ----- - Missing values are ignored while performing the cumulative aggregate operation. - For SArray's of type array.array, all entries are expected to be of the same size. Examples -------- >>> sa = SArray([1, 2, 3, 4, 5]) >>> sa.cumulative_mean() dtype: float rows: 3 [1, 1.5, 2, 2.5, 3] """ from .. import extensions agg_op = "__builtin__cum_avg__" return SArray(_proxy = self.__proxy__.builtin_cumulative_aggregate(agg_op))
[ "def", "cumulative_mean", "(", "self", ")", ":", "from", ".", ".", "import", "extensions", "agg_op", "=", "\"__builtin__cum_avg__\"", "return", "SArray", "(", "_proxy", "=", "self", ".", "__proxy__", ".", "builtin_cumulative_aggregate", "(", "agg_op", ")", ")" ]
Return the cumulative mean of the elements in the SArray. Returns an SArray where each element in the output corresponds to the mean value of all the elements preceding and including it. The SArray is expected to be of numeric type (int, float), or a numeric vector type. Returns ------- out : Sarray[float, array.array] Notes ----- - Missing values are ignored while performing the cumulative aggregate operation. - For SArray's of type array.array, all entries are expected to be of the same size. Examples -------- >>> sa = SArray([1, 2, 3, 4, 5]) >>> sa.cumulative_mean() dtype: float rows: 3 [1, 1.5, 2, 2.5, 3]
[ "Return", "the", "cumulative", "mean", "of", "the", "elements", "in", "the", "SArray", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L4254-L4284
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray.cumulative_min
def cumulative_min(self): """ Return the cumulative minimum value of the elements in the SArray. Returns an SArray where each element in the output corresponds to the minimum value of all the elements preceding and including it. The SArray is expected to be of numeric type (int, float). Returns ------- out : SArray[int, float] Notes ----- - Missing values are ignored while performing the cumulative aggregate operation. Examples -------- >>> sa = SArray([1, 2, 3, 4, 0]) >>> sa.cumulative_min() dtype: int rows: 3 [1, 1, 1, 1, 0] """ from .. import extensions agg_op = "__builtin__cum_min__" return SArray(_proxy = self.__proxy__.builtin_cumulative_aggregate(agg_op))
python
def cumulative_min(self): """ Return the cumulative minimum value of the elements in the SArray. Returns an SArray where each element in the output corresponds to the minimum value of all the elements preceding and including it. The SArray is expected to be of numeric type (int, float). Returns ------- out : SArray[int, float] Notes ----- - Missing values are ignored while performing the cumulative aggregate operation. Examples -------- >>> sa = SArray([1, 2, 3, 4, 0]) >>> sa.cumulative_min() dtype: int rows: 3 [1, 1, 1, 1, 0] """ from .. import extensions agg_op = "__builtin__cum_min__" return SArray(_proxy = self.__proxy__.builtin_cumulative_aggregate(agg_op))
[ "def", "cumulative_min", "(", "self", ")", ":", "from", ".", ".", "import", "extensions", "agg_op", "=", "\"__builtin__cum_min__\"", "return", "SArray", "(", "_proxy", "=", "self", ".", "__proxy__", ".", "builtin_cumulative_aggregate", "(", "agg_op", ")", ")" ]
Return the cumulative minimum value of the elements in the SArray. Returns an SArray where each element in the output corresponds to the minimum value of all the elements preceding and including it. The SArray is expected to be of numeric type (int, float). Returns ------- out : SArray[int, float] Notes ----- - Missing values are ignored while performing the cumulative aggregate operation. Examples -------- >>> sa = SArray([1, 2, 3, 4, 0]) >>> sa.cumulative_min() dtype: int rows: 3 [1, 1, 1, 1, 0]
[ "Return", "the", "cumulative", "minimum", "value", "of", "the", "elements", "in", "the", "SArray", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L4286-L4313
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray.cumulative_max
def cumulative_max(self): """ Return the cumulative maximum value of the elements in the SArray. Returns an SArray where each element in the output corresponds to the maximum value of all the elements preceding and including it. The SArray is expected to be of numeric type (int, float). Returns ------- out : SArray[int, float] Notes ----- - Missing values are ignored while performing the cumulative aggregate operation. Examples -------- >>> sa = SArray([1, 0, 3, 4, 2]) >>> sa.cumulative_max() dtype: int rows: 3 [1, 1, 3, 4, 4] """ from .. import extensions agg_op = "__builtin__cum_max__" return SArray(_proxy = self.__proxy__.builtin_cumulative_aggregate(agg_op))
python
def cumulative_max(self): """ Return the cumulative maximum value of the elements in the SArray. Returns an SArray where each element in the output corresponds to the maximum value of all the elements preceding and including it. The SArray is expected to be of numeric type (int, float). Returns ------- out : SArray[int, float] Notes ----- - Missing values are ignored while performing the cumulative aggregate operation. Examples -------- >>> sa = SArray([1, 0, 3, 4, 2]) >>> sa.cumulative_max() dtype: int rows: 3 [1, 1, 3, 4, 4] """ from .. import extensions agg_op = "__builtin__cum_max__" return SArray(_proxy = self.__proxy__.builtin_cumulative_aggregate(agg_op))
[ "def", "cumulative_max", "(", "self", ")", ":", "from", ".", ".", "import", "extensions", "agg_op", "=", "\"__builtin__cum_max__\"", "return", "SArray", "(", "_proxy", "=", "self", ".", "__proxy__", ".", "builtin_cumulative_aggregate", "(", "agg_op", ")", ")" ]
Return the cumulative maximum value of the elements in the SArray. Returns an SArray where each element in the output corresponds to the maximum value of all the elements preceding and including it. The SArray is expected to be of numeric type (int, float). Returns ------- out : SArray[int, float] Notes ----- - Missing values are ignored while performing the cumulative aggregate operation. Examples -------- >>> sa = SArray([1, 0, 3, 4, 2]) >>> sa.cumulative_max() dtype: int rows: 3 [1, 1, 3, 4, 4]
[ "Return", "the", "cumulative", "maximum", "value", "of", "the", "elements", "in", "the", "SArray", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L4315-L4342
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray.cumulative_std
def cumulative_std(self): """ Return the cumulative standard deviation of the elements in the SArray. Returns an SArray where each element in the output corresponds to the standard deviation of all the elements preceding and including it. The SArray is expected to be of numeric type, or a numeric vector type. Returns ------- out : SArray[int, float] Notes ----- - Missing values are ignored while performing the cumulative aggregate operation. Examples -------- >>> sa = SArray([1, 2, 3, 4, 0]) >>> sa.cumulative_std() dtype: float rows: 3 [0.0, 0.5, 0.816496580927726, 1.118033988749895, 1.4142135623730951] """ from .. import extensions agg_op = "__builtin__cum_std__" return SArray(_proxy = self.__proxy__.builtin_cumulative_aggregate(agg_op))
python
def cumulative_std(self): """ Return the cumulative standard deviation of the elements in the SArray. Returns an SArray where each element in the output corresponds to the standard deviation of all the elements preceding and including it. The SArray is expected to be of numeric type, or a numeric vector type. Returns ------- out : SArray[int, float] Notes ----- - Missing values are ignored while performing the cumulative aggregate operation. Examples -------- >>> sa = SArray([1, 2, 3, 4, 0]) >>> sa.cumulative_std() dtype: float rows: 3 [0.0, 0.5, 0.816496580927726, 1.118033988749895, 1.4142135623730951] """ from .. import extensions agg_op = "__builtin__cum_std__" return SArray(_proxy = self.__proxy__.builtin_cumulative_aggregate(agg_op))
[ "def", "cumulative_std", "(", "self", ")", ":", "from", ".", ".", "import", "extensions", "agg_op", "=", "\"__builtin__cum_std__\"", "return", "SArray", "(", "_proxy", "=", "self", ".", "__proxy__", ".", "builtin_cumulative_aggregate", "(", "agg_op", ")", ")" ]
Return the cumulative standard deviation of the elements in the SArray. Returns an SArray where each element in the output corresponds to the standard deviation of all the elements preceding and including it. The SArray is expected to be of numeric type, or a numeric vector type. Returns ------- out : SArray[int, float] Notes ----- - Missing values are ignored while performing the cumulative aggregate operation. Examples -------- >>> sa = SArray([1, 2, 3, 4, 0]) >>> sa.cumulative_std() dtype: float rows: 3 [0.0, 0.5, 0.816496580927726, 1.118033988749895, 1.4142135623730951]
[ "Return", "the", "cumulative", "standard", "deviation", "of", "the", "elements", "in", "the", "SArray", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L4344-L4371
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray.cumulative_var
def cumulative_var(self): """ Return the cumulative variance of the elements in the SArray. Returns an SArray where each element in the output corresponds to the variance of all the elements preceding and including it. The SArray is expected to be of numeric type, or a numeric vector type. Returns ------- out : SArray[int, float] Notes ----- - Missing values are ignored while performing the cumulative aggregate operation. Examples -------- >>> sa = SArray([1, 2, 3, 4, 0]) >>> sa.cumulative_var() dtype: float rows: 3 [0.0, 0.25, 0.6666666666666666, 1.25, 2.0] """ from .. import extensions agg_op = "__builtin__cum_var__" return SArray(_proxy = self.__proxy__.builtin_cumulative_aggregate(agg_op))
python
def cumulative_var(self): """ Return the cumulative variance of the elements in the SArray. Returns an SArray where each element in the output corresponds to the variance of all the elements preceding and including it. The SArray is expected to be of numeric type, or a numeric vector type. Returns ------- out : SArray[int, float] Notes ----- - Missing values are ignored while performing the cumulative aggregate operation. Examples -------- >>> sa = SArray([1, 2, 3, 4, 0]) >>> sa.cumulative_var() dtype: float rows: 3 [0.0, 0.25, 0.6666666666666666, 1.25, 2.0] """ from .. import extensions agg_op = "__builtin__cum_var__" return SArray(_proxy = self.__proxy__.builtin_cumulative_aggregate(agg_op))
[ "def", "cumulative_var", "(", "self", ")", ":", "from", ".", ".", "import", "extensions", "agg_op", "=", "\"__builtin__cum_var__\"", "return", "SArray", "(", "_proxy", "=", "self", ".", "__proxy__", ".", "builtin_cumulative_aggregate", "(", "agg_op", ")", ")" ]
Return the cumulative variance of the elements in the SArray. Returns an SArray where each element in the output corresponds to the variance of all the elements preceding and including it. The SArray is expected to be of numeric type, or a numeric vector type. Returns ------- out : SArray[int, float] Notes ----- - Missing values are ignored while performing the cumulative aggregate operation. Examples -------- >>> sa = SArray([1, 2, 3, 4, 0]) >>> sa.cumulative_var() dtype: float rows: 3 [0.0, 0.25, 0.6666666666666666, 1.25, 2.0]
[ "Return", "the", "cumulative", "variance", "of", "the", "elements", "in", "the", "SArray", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L4373-L4400
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
SArray.filter_by
def filter_by(self, values, exclude=False): """ Filter an SArray by values inside an iterable object. The result is an SArray that only includes (or excludes) the values in the given ``values`` :class:`~turicreate.SArray`. If ``values`` is not an SArray, we attempt to convert it to one before filtering. Parameters ---------- values : SArray | list | numpy.ndarray | pandas.Series | str The values to use to filter the SArray. The resulting SArray will only include rows that have one of these values in the given column. exclude : bool If True, the result SArray will contain all rows EXCEPT those that have one of the ``values``. Returns ------- out : SArray The filtered SArray. Examples -------- >>> sa = SArray(['dog', 'cat', 'cow', 'horse']) >>> sa.filter_by(['cat', 'hamster', 'dog', 'fish', 'bird', 'snake']) dtype: str Rows: 2 ['dog', 'cat'] >>> sa.filter_by(['cat', 'hamster', 'dog', 'fish', 'bird', 'snake'], exclude=True) dtype: str Rows: 2 ['horse', 'cow'] """ from .sframe import SFrame as _SFrame column_name = 'sarray' # Convert values to SArray if not isinstance(values, SArray): #type(values) is not SArray: # If we were given a single element, try to put in list and convert # to SArray if not _is_non_string_iterable(values): values = [values] values = SArray(values) # Convert values to SFrame value_sf = _SFrame() value_sf.add_column(values, column_name, inplace=True) given_type = value_sf.column_types()[0] #value column type existing_type = self.dtype sarray_sf = _SFrame() sarray_sf.add_column(self, column_name, inplace=True) if given_type != existing_type: raise TypeError("Type of given values does not match type of the SArray") # Make sure the values list has unique values, or else join will not # filter. value_sf = value_sf.groupby(column_name, {}) with cython_context(): if exclude: id_name = "id" value_sf = value_sf.add_row_number(id_name) tmp = _SFrame(_proxy=sarray_sf.__proxy__.join(value_sf.__proxy__, 'left', {column_name:column_name})) ret_sf = tmp[tmp[id_name] == None] return ret_sf[column_name] else: ret_sf = _SFrame(_proxy=sarray_sf.__proxy__.join(value_sf.__proxy__, 'inner', {column_name:column_name})) return ret_sf[column_name]
python
def filter_by(self, values, exclude=False): """ Filter an SArray by values inside an iterable object. The result is an SArray that only includes (or excludes) the values in the given ``values`` :class:`~turicreate.SArray`. If ``values`` is not an SArray, we attempt to convert it to one before filtering. Parameters ---------- values : SArray | list | numpy.ndarray | pandas.Series | str The values to use to filter the SArray. The resulting SArray will only include rows that have one of these values in the given column. exclude : bool If True, the result SArray will contain all rows EXCEPT those that have one of the ``values``. Returns ------- out : SArray The filtered SArray. Examples -------- >>> sa = SArray(['dog', 'cat', 'cow', 'horse']) >>> sa.filter_by(['cat', 'hamster', 'dog', 'fish', 'bird', 'snake']) dtype: str Rows: 2 ['dog', 'cat'] >>> sa.filter_by(['cat', 'hamster', 'dog', 'fish', 'bird', 'snake'], exclude=True) dtype: str Rows: 2 ['horse', 'cow'] """ from .sframe import SFrame as _SFrame column_name = 'sarray' # Convert values to SArray if not isinstance(values, SArray): #type(values) is not SArray: # If we were given a single element, try to put in list and convert # to SArray if not _is_non_string_iterable(values): values = [values] values = SArray(values) # Convert values to SFrame value_sf = _SFrame() value_sf.add_column(values, column_name, inplace=True) given_type = value_sf.column_types()[0] #value column type existing_type = self.dtype sarray_sf = _SFrame() sarray_sf.add_column(self, column_name, inplace=True) if given_type != existing_type: raise TypeError("Type of given values does not match type of the SArray") # Make sure the values list has unique values, or else join will not # filter. value_sf = value_sf.groupby(column_name, {}) with cython_context(): if exclude: id_name = "id" value_sf = value_sf.add_row_number(id_name) tmp = _SFrame(_proxy=sarray_sf.__proxy__.join(value_sf.__proxy__, 'left', {column_name:column_name})) ret_sf = tmp[tmp[id_name] == None] return ret_sf[column_name] else: ret_sf = _SFrame(_proxy=sarray_sf.__proxy__.join(value_sf.__proxy__, 'inner', {column_name:column_name})) return ret_sf[column_name]
[ "def", "filter_by", "(", "self", ",", "values", ",", "exclude", "=", "False", ")", ":", "from", ".", "sframe", "import", "SFrame", "as", "_SFrame", "column_name", "=", "'sarray'", "# Convert values to SArray", "if", "not", "isinstance", "(", "values", ",", "SArray", ")", ":", "#type(values) is not SArray:", "# If we were given a single element, try to put in list and convert", "# to SArray", "if", "not", "_is_non_string_iterable", "(", "values", ")", ":", "values", "=", "[", "values", "]", "values", "=", "SArray", "(", "values", ")", "# Convert values to SFrame", "value_sf", "=", "_SFrame", "(", ")", "value_sf", ".", "add_column", "(", "values", ",", "column_name", ",", "inplace", "=", "True", ")", "given_type", "=", "value_sf", ".", "column_types", "(", ")", "[", "0", "]", "#value column type", "existing_type", "=", "self", ".", "dtype", "sarray_sf", "=", "_SFrame", "(", ")", "sarray_sf", ".", "add_column", "(", "self", ",", "column_name", ",", "inplace", "=", "True", ")", "if", "given_type", "!=", "existing_type", ":", "raise", "TypeError", "(", "\"Type of given values does not match type of the SArray\"", ")", "# Make sure the values list has unique values, or else join will not", "# filter.", "value_sf", "=", "value_sf", ".", "groupby", "(", "column_name", ",", "{", "}", ")", "with", "cython_context", "(", ")", ":", "if", "exclude", ":", "id_name", "=", "\"id\"", "value_sf", "=", "value_sf", ".", "add_row_number", "(", "id_name", ")", "tmp", "=", "_SFrame", "(", "_proxy", "=", "sarray_sf", ".", "__proxy__", ".", "join", "(", "value_sf", ".", "__proxy__", ",", "'left'", ",", "{", "column_name", ":", "column_name", "}", ")", ")", "ret_sf", "=", "tmp", "[", "tmp", "[", "id_name", "]", "==", "None", "]", "return", "ret_sf", "[", "column_name", "]", "else", ":", "ret_sf", "=", "_SFrame", "(", "_proxy", "=", "sarray_sf", ".", "__proxy__", ".", "join", "(", "value_sf", ".", "__proxy__", ",", "'inner'", ",", "{", "column_name", ":", "column_name", "}", ")", ")", "return", "ret_sf", "[", "column_name", "]" ]
Filter an SArray by values inside an iterable object. The result is an SArray that only includes (or excludes) the values in the given ``values`` :class:`~turicreate.SArray`. If ``values`` is not an SArray, we attempt to convert it to one before filtering. Parameters ---------- values : SArray | list | numpy.ndarray | pandas.Series | str The values to use to filter the SArray. The resulting SArray will only include rows that have one of these values in the given column. exclude : bool If True, the result SArray will contain all rows EXCEPT those that have one of the ``values``. Returns ------- out : SArray The filtered SArray. Examples -------- >>> sa = SArray(['dog', 'cat', 'cow', 'horse']) >>> sa.filter_by(['cat', 'hamster', 'dog', 'fish', 'bird', 'snake']) dtype: str Rows: 2 ['dog', 'cat'] >>> sa.filter_by(['cat', 'hamster', 'dog', 'fish', 'bird', 'snake'], exclude=True) dtype: str Rows: 2 ['horse', 'cow']
[ "Filter", "an", "SArray", "by", "values", "inside", "an", "iterable", "object", ".", "The", "result", "is", "an", "SArray", "that", "only", "includes", "(", "or", "excludes", ")", "the", "values", "in", "the", "given", "values", ":", "class", ":", "~turicreate", ".", "SArray", ".", "If", "values", "is", "not", "an", "SArray", "we", "attempt", "to", "convert", "it", "to", "one", "before", "filtering", ".", "Parameters", "----------", "values", ":", "SArray", "|", "list", "|", "numpy", ".", "ndarray", "|", "pandas", ".", "Series", "|", "str", "The", "values", "to", "use", "to", "filter", "the", "SArray", ".", "The", "resulting", "SArray", "will", "only", "include", "rows", "that", "have", "one", "of", "these", "values", "in", "the", "given", "column", ".", "exclude", ":", "bool", "If", "True", "the", "result", "SArray", "will", "contain", "all", "rows", "EXCEPT", "those", "that", "have", "one", "of", "the", "values", ".", "Returns", "-------", "out", ":", "SArray", "The", "filtered", "SArray", ".", "Examples", "--------", ">>>", "sa", "=", "SArray", "(", "[", "dog", "cat", "cow", "horse", "]", ")", ">>>", "sa", ".", "filter_by", "(", "[", "cat", "hamster", "dog", "fish", "bird", "snake", "]", ")", "dtype", ":", "str", "Rows", ":", "2", "[", "dog", "cat", "]", ">>>", "sa", ".", "filter_by", "(", "[", "cat", "hamster", "dog", "fish", "bird", "snake", "]", "exclude", "=", "True", ")", "dtype", ":", "str", "Rows", ":", "2", "[", "horse", "cow", "]" ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L4402-L4480
train
apple/turicreate
src/external/xgboost/subtree/rabit/doc/conf.py
run_build_lib
def run_build_lib(folder): """Run the doxygen make command in the designated folder.""" try: retcode = subprocess.call("cd %s; make" % folder, shell=True) retcode = subprocess.call("rm -rf _build/html/doxygen", shell=True) retcode = subprocess.call("mkdir _build", shell=True) retcode = subprocess.call("mkdir _build/html", shell=True) retcode = subprocess.call("cp -rf doxygen/html _build/html/doxygen", shell=True) if retcode < 0: sys.stderr.write("build terminated by signal %s" % (-retcode)) except OSError as e: sys.stderr.write("build execution failed: %s" % e)
python
def run_build_lib(folder): """Run the doxygen make command in the designated folder.""" try: retcode = subprocess.call("cd %s; make" % folder, shell=True) retcode = subprocess.call("rm -rf _build/html/doxygen", shell=True) retcode = subprocess.call("mkdir _build", shell=True) retcode = subprocess.call("mkdir _build/html", shell=True) retcode = subprocess.call("cp -rf doxygen/html _build/html/doxygen", shell=True) if retcode < 0: sys.stderr.write("build terminated by signal %s" % (-retcode)) except OSError as e: sys.stderr.write("build execution failed: %s" % e)
[ "def", "run_build_lib", "(", "folder", ")", ":", "try", ":", "retcode", "=", "subprocess", ".", "call", "(", "\"cd %s; make\"", "%", "folder", ",", "shell", "=", "True", ")", "retcode", "=", "subprocess", ".", "call", "(", "\"rm -rf _build/html/doxygen\"", ",", "shell", "=", "True", ")", "retcode", "=", "subprocess", ".", "call", "(", "\"mkdir _build\"", ",", "shell", "=", "True", ")", "retcode", "=", "subprocess", ".", "call", "(", "\"mkdir _build/html\"", ",", "shell", "=", "True", ")", "retcode", "=", "subprocess", ".", "call", "(", "\"cp -rf doxygen/html _build/html/doxygen\"", ",", "shell", "=", "True", ")", "if", "retcode", "<", "0", ":", "sys", ".", "stderr", ".", "write", "(", "\"build terminated by signal %s\"", "%", "(", "-", "retcode", ")", ")", "except", "OSError", "as", "e", ":", "sys", ".", "stderr", ".", "write", "(", "\"build execution failed: %s\"", "%", "e", ")" ]
Run the doxygen make command in the designated folder.
[ "Run", "the", "doxygen", "make", "command", "in", "the", "designated", "folder", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/subtree/rabit/doc/conf.py#L153-L164
train
apple/turicreate
src/external/xgboost/subtree/rabit/doc/conf.py
generate_doxygen_xml
def generate_doxygen_xml(app): """Run the doxygen make commands if we're on the ReadTheDocs server""" read_the_docs_build = os.environ.get('READTHEDOCS', None) == 'True' if read_the_docs_build: run_doxygen('..') sys.stderr.write('Check if shared lib exists\n') run_build_lib('..') sys.stderr.write('The wrapper path: %s\n' % str(os.listdir('../wrapper'))) rabit._loadlib()
python
def generate_doxygen_xml(app): """Run the doxygen make commands if we're on the ReadTheDocs server""" read_the_docs_build = os.environ.get('READTHEDOCS', None) == 'True' if read_the_docs_build: run_doxygen('..') sys.stderr.write('Check if shared lib exists\n') run_build_lib('..') sys.stderr.write('The wrapper path: %s\n' % str(os.listdir('../wrapper'))) rabit._loadlib()
[ "def", "generate_doxygen_xml", "(", "app", ")", ":", "read_the_docs_build", "=", "os", ".", "environ", ".", "get", "(", "'READTHEDOCS'", ",", "None", ")", "==", "'True'", "if", "read_the_docs_build", ":", "run_doxygen", "(", "'..'", ")", "sys", ".", "stderr", ".", "write", "(", "'Check if shared lib exists\\n'", ")", "run_build_lib", "(", "'..'", ")", "sys", ".", "stderr", ".", "write", "(", "'The wrapper path: %s\\n'", "%", "str", "(", "os", ".", "listdir", "(", "'../wrapper'", ")", ")", ")", "rabit", ".", "_loadlib", "(", ")" ]
Run the doxygen make commands if we're on the ReadTheDocs server
[ "Run", "the", "doxygen", "make", "commands", "if", "we", "re", "on", "the", "ReadTheDocs", "server" ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/subtree/rabit/doc/conf.py#L167-L175
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py
MessageToJson
def MessageToJson(message, including_default_value_fields=False, preserving_proto_field_name=False): """Converts protobuf message to JSON format. Args: message: The protocol buffers message instance to serialize. including_default_value_fields: If True, singular primitive fields, repeated fields, and map fields will always be serialized. If False, only serialize non-empty fields. Singular message fields and oneof fields are not affected by this option. preserving_proto_field_name: If True, use the original proto field names as defined in the .proto file. If False, convert the field names to lowerCamelCase. Returns: A string containing the JSON formatted protocol buffer message. """ printer = _Printer(including_default_value_fields, preserving_proto_field_name) return printer.ToJsonString(message)
python
def MessageToJson(message, including_default_value_fields=False, preserving_proto_field_name=False): """Converts protobuf message to JSON format. Args: message: The protocol buffers message instance to serialize. including_default_value_fields: If True, singular primitive fields, repeated fields, and map fields will always be serialized. If False, only serialize non-empty fields. Singular message fields and oneof fields are not affected by this option. preserving_proto_field_name: If True, use the original proto field names as defined in the .proto file. If False, convert the field names to lowerCamelCase. Returns: A string containing the JSON formatted protocol buffer message. """ printer = _Printer(including_default_value_fields, preserving_proto_field_name) return printer.ToJsonString(message)
[ "def", "MessageToJson", "(", "message", ",", "including_default_value_fields", "=", "False", ",", "preserving_proto_field_name", "=", "False", ")", ":", "printer", "=", "_Printer", "(", "including_default_value_fields", ",", "preserving_proto_field_name", ")", "return", "printer", ".", "ToJsonString", "(", "message", ")" ]
Converts protobuf message to JSON format. Args: message: The protocol buffers message instance to serialize. including_default_value_fields: If True, singular primitive fields, repeated fields, and map fields will always be serialized. If False, only serialize non-empty fields. Singular message fields and oneof fields are not affected by this option. preserving_proto_field_name: If True, use the original proto field names as defined in the .proto file. If False, convert the field names to lowerCamelCase. Returns: A string containing the JSON formatted protocol buffer message.
[ "Converts", "protobuf", "message", "to", "JSON", "format", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py#L89-L109
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py
MessageToDict
def MessageToDict(message, including_default_value_fields=False, preserving_proto_field_name=False): """Converts protobuf message to a JSON dictionary. Args: message: The protocol buffers message instance to serialize. including_default_value_fields: If True, singular primitive fields, repeated fields, and map fields will always be serialized. If False, only serialize non-empty fields. Singular message fields and oneof fields are not affected by this option. preserving_proto_field_name: If True, use the original proto field names as defined in the .proto file. If False, convert the field names to lowerCamelCase. Returns: A dict representation of the JSON formatted protocol buffer message. """ printer = _Printer(including_default_value_fields, preserving_proto_field_name) # pylint: disable=protected-access return printer._MessageToJsonObject(message)
python
def MessageToDict(message, including_default_value_fields=False, preserving_proto_field_name=False): """Converts protobuf message to a JSON dictionary. Args: message: The protocol buffers message instance to serialize. including_default_value_fields: If True, singular primitive fields, repeated fields, and map fields will always be serialized. If False, only serialize non-empty fields. Singular message fields and oneof fields are not affected by this option. preserving_proto_field_name: If True, use the original proto field names as defined in the .proto file. If False, convert the field names to lowerCamelCase. Returns: A dict representation of the JSON formatted protocol buffer message. """ printer = _Printer(including_default_value_fields, preserving_proto_field_name) # pylint: disable=protected-access return printer._MessageToJsonObject(message)
[ "def", "MessageToDict", "(", "message", ",", "including_default_value_fields", "=", "False", ",", "preserving_proto_field_name", "=", "False", ")", ":", "printer", "=", "_Printer", "(", "including_default_value_fields", ",", "preserving_proto_field_name", ")", "# pylint: disable=protected-access", "return", "printer", ".", "_MessageToJsonObject", "(", "message", ")" ]
Converts protobuf message to a JSON dictionary. Args: message: The protocol buffers message instance to serialize. including_default_value_fields: If True, singular primitive fields, repeated fields, and map fields will always be serialized. If False, only serialize non-empty fields. Singular message fields and oneof fields are not affected by this option. preserving_proto_field_name: If True, use the original proto field names as defined in the .proto file. If False, convert the field names to lowerCamelCase. Returns: A dict representation of the JSON formatted protocol buffer message.
[ "Converts", "protobuf", "message", "to", "a", "JSON", "dictionary", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py#L112-L133
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py
ParseDict
def ParseDict(js_dict, message, ignore_unknown_fields=False): """Parses a JSON dictionary representation into a message. Args: js_dict: Dict representation of a JSON message. message: A protocol buffer message to merge into. ignore_unknown_fields: If True, do not raise errors for unknown fields. Returns: The same message passed as argument. """ parser = _Parser(ignore_unknown_fields) parser.ConvertMessage(js_dict, message) return message
python
def ParseDict(js_dict, message, ignore_unknown_fields=False): """Parses a JSON dictionary representation into a message. Args: js_dict: Dict representation of a JSON message. message: A protocol buffer message to merge into. ignore_unknown_fields: If True, do not raise errors for unknown fields. Returns: The same message passed as argument. """ parser = _Parser(ignore_unknown_fields) parser.ConvertMessage(js_dict, message) return message
[ "def", "ParseDict", "(", "js_dict", ",", "message", ",", "ignore_unknown_fields", "=", "False", ")", ":", "parser", "=", "_Parser", "(", "ignore_unknown_fields", ")", "parser", ".", "ConvertMessage", "(", "js_dict", ",", "message", ")", "return", "message" ]
Parses a JSON dictionary representation into a message. Args: js_dict: Dict representation of a JSON message. message: A protocol buffer message to merge into. ignore_unknown_fields: If True, do not raise errors for unknown fields. Returns: The same message passed as argument.
[ "Parses", "a", "JSON", "dictionary", "representation", "into", "a", "message", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py#L372-L385
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py
_ConvertScalarFieldValue
def _ConvertScalarFieldValue(value, field, require_str=False): """Convert a single scalar field value. Args: value: A scalar value to convert the scalar field value. field: The descriptor of the field to convert. require_str: If True, the field value must be a str. Returns: The converted scalar field value Raises: ParseError: In case of convert problems. """ if field.cpp_type in _INT_TYPES: return _ConvertInteger(value) elif field.cpp_type in _FLOAT_TYPES: return _ConvertFloat(value) elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL: return _ConvertBool(value, require_str) elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_STRING: if field.type == descriptor.FieldDescriptor.TYPE_BYTES: return base64.b64decode(value) else: # Checking for unpaired surrogates appears to be unreliable, # depending on the specific Python version, so we check manually. if _UNPAIRED_SURROGATE_PATTERN.search(value): raise ParseError('Unpaired surrogate') return value elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM: # Convert an enum value. enum_value = field.enum_type.values_by_name.get(value, None) if enum_value is None: try: number = int(value) enum_value = field.enum_type.values_by_number.get(number, None) except ValueError: raise ParseError('Invalid enum value {0} for enum type {1}.'.format( value, field.enum_type.full_name)) if enum_value is None: raise ParseError('Invalid enum value {0} for enum type {1}.'.format( value, field.enum_type.full_name)) return enum_value.number
python
def _ConvertScalarFieldValue(value, field, require_str=False): """Convert a single scalar field value. Args: value: A scalar value to convert the scalar field value. field: The descriptor of the field to convert. require_str: If True, the field value must be a str. Returns: The converted scalar field value Raises: ParseError: In case of convert problems. """ if field.cpp_type in _INT_TYPES: return _ConvertInteger(value) elif field.cpp_type in _FLOAT_TYPES: return _ConvertFloat(value) elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL: return _ConvertBool(value, require_str) elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_STRING: if field.type == descriptor.FieldDescriptor.TYPE_BYTES: return base64.b64decode(value) else: # Checking for unpaired surrogates appears to be unreliable, # depending on the specific Python version, so we check manually. if _UNPAIRED_SURROGATE_PATTERN.search(value): raise ParseError('Unpaired surrogate') return value elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM: # Convert an enum value. enum_value = field.enum_type.values_by_name.get(value, None) if enum_value is None: try: number = int(value) enum_value = field.enum_type.values_by_number.get(number, None) except ValueError: raise ParseError('Invalid enum value {0} for enum type {1}.'.format( value, field.enum_type.full_name)) if enum_value is None: raise ParseError('Invalid enum value {0} for enum type {1}.'.format( value, field.enum_type.full_name)) return enum_value.number
[ "def", "_ConvertScalarFieldValue", "(", "value", ",", "field", ",", "require_str", "=", "False", ")", ":", "if", "field", ".", "cpp_type", "in", "_INT_TYPES", ":", "return", "_ConvertInteger", "(", "value", ")", "elif", "field", ".", "cpp_type", "in", "_FLOAT_TYPES", ":", "return", "_ConvertFloat", "(", "value", ")", "elif", "field", ".", "cpp_type", "==", "descriptor", ".", "FieldDescriptor", ".", "CPPTYPE_BOOL", ":", "return", "_ConvertBool", "(", "value", ",", "require_str", ")", "elif", "field", ".", "cpp_type", "==", "descriptor", ".", "FieldDescriptor", ".", "CPPTYPE_STRING", ":", "if", "field", ".", "type", "==", "descriptor", ".", "FieldDescriptor", ".", "TYPE_BYTES", ":", "return", "base64", ".", "b64decode", "(", "value", ")", "else", ":", "# Checking for unpaired surrogates appears to be unreliable,", "# depending on the specific Python version, so we check manually.", "if", "_UNPAIRED_SURROGATE_PATTERN", ".", "search", "(", "value", ")", ":", "raise", "ParseError", "(", "'Unpaired surrogate'", ")", "return", "value", "elif", "field", ".", "cpp_type", "==", "descriptor", ".", "FieldDescriptor", ".", "CPPTYPE_ENUM", ":", "# Convert an enum value.", "enum_value", "=", "field", ".", "enum_type", ".", "values_by_name", ".", "get", "(", "value", ",", "None", ")", "if", "enum_value", "is", "None", ":", "try", ":", "number", "=", "int", "(", "value", ")", "enum_value", "=", "field", ".", "enum_type", ".", "values_by_number", ".", "get", "(", "number", ",", "None", ")", "except", "ValueError", ":", "raise", "ParseError", "(", "'Invalid enum value {0} for enum type {1}.'", ".", "format", "(", "value", ",", "field", ".", "enum_type", ".", "full_name", ")", ")", "if", "enum_value", "is", "None", ":", "raise", "ParseError", "(", "'Invalid enum value {0} for enum type {1}.'", ".", "format", "(", "value", ",", "field", ".", "enum_type", ".", "full_name", ")", ")", "return", "enum_value", ".", "number" ]
Convert a single scalar field value. Args: value: A scalar value to convert the scalar field value. field: The descriptor of the field to convert. require_str: If True, the field value must be a str. Returns: The converted scalar field value Raises: ParseError: In case of convert problems.
[ "Convert", "a", "single", "scalar", "field", "value", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py#L606-L648
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py
_ConvertInteger
def _ConvertInteger(value): """Convert an integer. Args: value: A scalar value to convert. Returns: The integer value. Raises: ParseError: If an integer couldn't be consumed. """ if isinstance(value, float) and not value.is_integer(): raise ParseError('Couldn\'t parse integer: {0}.'.format(value)) if isinstance(value, six.text_type) and value.find(' ') != -1: raise ParseError('Couldn\'t parse integer: "{0}".'.format(value)) return int(value)
python
def _ConvertInteger(value): """Convert an integer. Args: value: A scalar value to convert. Returns: The integer value. Raises: ParseError: If an integer couldn't be consumed. """ if isinstance(value, float) and not value.is_integer(): raise ParseError('Couldn\'t parse integer: {0}.'.format(value)) if isinstance(value, six.text_type) and value.find(' ') != -1: raise ParseError('Couldn\'t parse integer: "{0}".'.format(value)) return int(value)
[ "def", "_ConvertInteger", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "float", ")", "and", "not", "value", ".", "is_integer", "(", ")", ":", "raise", "ParseError", "(", "'Couldn\\'t parse integer: {0}.'", ".", "format", "(", "value", ")", ")", "if", "isinstance", "(", "value", ",", "six", ".", "text_type", ")", "and", "value", ".", "find", "(", "' '", ")", "!=", "-", "1", ":", "raise", "ParseError", "(", "'Couldn\\'t parse integer: \"{0}\".'", ".", "format", "(", "value", ")", ")", "return", "int", "(", "value", ")" ]
Convert an integer. Args: value: A scalar value to convert. Returns: The integer value. Raises: ParseError: If an integer couldn't be consumed.
[ "Convert", "an", "integer", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py#L651-L669
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py
_ConvertFloat
def _ConvertFloat(value): """Convert an floating point number.""" if value == 'nan': raise ParseError('Couldn\'t parse float "nan", use "NaN" instead.') try: # Assume Python compatible syntax. return float(value) except ValueError: # Check alternative spellings. if value == _NEG_INFINITY: return float('-inf') elif value == _INFINITY: return float('inf') elif value == _NAN: return float('nan') else: raise ParseError('Couldn\'t parse float: {0}.'.format(value))
python
def _ConvertFloat(value): """Convert an floating point number.""" if value == 'nan': raise ParseError('Couldn\'t parse float "nan", use "NaN" instead.') try: # Assume Python compatible syntax. return float(value) except ValueError: # Check alternative spellings. if value == _NEG_INFINITY: return float('-inf') elif value == _INFINITY: return float('inf') elif value == _NAN: return float('nan') else: raise ParseError('Couldn\'t parse float: {0}.'.format(value))
[ "def", "_ConvertFloat", "(", "value", ")", ":", "if", "value", "==", "'nan'", ":", "raise", "ParseError", "(", "'Couldn\\'t parse float \"nan\", use \"NaN\" instead.'", ")", "try", ":", "# Assume Python compatible syntax.", "return", "float", "(", "value", ")", "except", "ValueError", ":", "# Check alternative spellings.", "if", "value", "==", "_NEG_INFINITY", ":", "return", "float", "(", "'-inf'", ")", "elif", "value", "==", "_INFINITY", ":", "return", "float", "(", "'inf'", ")", "elif", "value", "==", "_NAN", ":", "return", "float", "(", "'nan'", ")", "else", ":", "raise", "ParseError", "(", "'Couldn\\'t parse float: {0}.'", ".", "format", "(", "value", ")", ")" ]
Convert an floating point number.
[ "Convert", "an", "floating", "point", "number", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py#L672-L688
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py
_ConvertBool
def _ConvertBool(value, require_str): """Convert a boolean value. Args: value: A scalar value to convert. require_str: If True, value must be a str. Returns: The bool parsed. Raises: ParseError: If a boolean value couldn't be consumed. """ if require_str: if value == 'true': return True elif value == 'false': return False else: raise ParseError('Expected "true" or "false", not {0}.'.format(value)) if not isinstance(value, bool): raise ParseError('Expected true or false without quotes.') return value
python
def _ConvertBool(value, require_str): """Convert a boolean value. Args: value: A scalar value to convert. require_str: If True, value must be a str. Returns: The bool parsed. Raises: ParseError: If a boolean value couldn't be consumed. """ if require_str: if value == 'true': return True elif value == 'false': return False else: raise ParseError('Expected "true" or "false", not {0}.'.format(value)) if not isinstance(value, bool): raise ParseError('Expected true or false without quotes.') return value
[ "def", "_ConvertBool", "(", "value", ",", "require_str", ")", ":", "if", "require_str", ":", "if", "value", "==", "'true'", ":", "return", "True", "elif", "value", "==", "'false'", ":", "return", "False", "else", ":", "raise", "ParseError", "(", "'Expected \"true\" or \"false\", not {0}.'", ".", "format", "(", "value", ")", ")", "if", "not", "isinstance", "(", "value", ",", "bool", ")", ":", "raise", "ParseError", "(", "'Expected true or false without quotes.'", ")", "return", "value" ]
Convert a boolean value. Args: value: A scalar value to convert. require_str: If True, value must be a str. Returns: The bool parsed. Raises: ParseError: If a boolean value couldn't be consumed.
[ "Convert", "a", "boolean", "value", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py#L691-L714
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py
_Printer._MessageToJsonObject
def _MessageToJsonObject(self, message): """Converts message to an object according to Proto3 JSON Specification.""" message_descriptor = message.DESCRIPTOR full_name = message_descriptor.full_name if _IsWrapperMessage(message_descriptor): return self._WrapperMessageToJsonObject(message) if full_name in _WKTJSONMETHODS: return methodcaller(_WKTJSONMETHODS[full_name][0], message)(self) js = {} return self._RegularMessageToJsonObject(message, js)
python
def _MessageToJsonObject(self, message): """Converts message to an object according to Proto3 JSON Specification.""" message_descriptor = message.DESCRIPTOR full_name = message_descriptor.full_name if _IsWrapperMessage(message_descriptor): return self._WrapperMessageToJsonObject(message) if full_name in _WKTJSONMETHODS: return methodcaller(_WKTJSONMETHODS[full_name][0], message)(self) js = {} return self._RegularMessageToJsonObject(message, js)
[ "def", "_MessageToJsonObject", "(", "self", ",", "message", ")", ":", "message_descriptor", "=", "message", ".", "DESCRIPTOR", "full_name", "=", "message_descriptor", ".", "full_name", "if", "_IsWrapperMessage", "(", "message_descriptor", ")", ":", "return", "self", ".", "_WrapperMessageToJsonObject", "(", "message", ")", "if", "full_name", "in", "_WKTJSONMETHODS", ":", "return", "methodcaller", "(", "_WKTJSONMETHODS", "[", "full_name", "]", "[", "0", "]", ",", "message", ")", "(", "self", ")", "js", "=", "{", "}", "return", "self", ".", "_RegularMessageToJsonObject", "(", "message", ",", "js", ")" ]
Converts message to an object according to Proto3 JSON Specification.
[ "Converts", "message", "to", "an", "object", "according", "to", "Proto3", "JSON", "Specification", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py#L155-L164
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py
_Printer._RegularMessageToJsonObject
def _RegularMessageToJsonObject(self, message, js): """Converts normal message according to Proto3 JSON Specification.""" fields = message.ListFields() try: for field, value in fields: if self.preserving_proto_field_name: name = field.name else: name = field.json_name if _IsMapEntry(field): # Convert a map field. v_field = field.message_type.fields_by_name['value'] js_map = {} for key in value: if isinstance(key, bool): if key: recorded_key = 'true' else: recorded_key = 'false' else: recorded_key = key js_map[recorded_key] = self._FieldToJsonObject( v_field, value[key]) js[name] = js_map elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED: # Convert a repeated field. js[name] = [self._FieldToJsonObject(field, k) for k in value] else: js[name] = self._FieldToJsonObject(field, value) # Serialize default value if including_default_value_fields is True. if self.including_default_value_fields: message_descriptor = message.DESCRIPTOR for field in message_descriptor.fields: # Singular message fields and oneof fields will not be affected. if ((field.label != descriptor.FieldDescriptor.LABEL_REPEATED and field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE) or field.containing_oneof): continue if self.preserving_proto_field_name: name = field.name else: name = field.json_name if name in js: # Skip the field which has been serailized already. continue if _IsMapEntry(field): js[name] = {} elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED: js[name] = [] else: js[name] = self._FieldToJsonObject(field, field.default_value) except ValueError as e: raise SerializeToJsonError( 'Failed to serialize {0} field: {1}.'.format(field.name, e)) return js
python
def _RegularMessageToJsonObject(self, message, js): """Converts normal message according to Proto3 JSON Specification.""" fields = message.ListFields() try: for field, value in fields: if self.preserving_proto_field_name: name = field.name else: name = field.json_name if _IsMapEntry(field): # Convert a map field. v_field = field.message_type.fields_by_name['value'] js_map = {} for key in value: if isinstance(key, bool): if key: recorded_key = 'true' else: recorded_key = 'false' else: recorded_key = key js_map[recorded_key] = self._FieldToJsonObject( v_field, value[key]) js[name] = js_map elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED: # Convert a repeated field. js[name] = [self._FieldToJsonObject(field, k) for k in value] else: js[name] = self._FieldToJsonObject(field, value) # Serialize default value if including_default_value_fields is True. if self.including_default_value_fields: message_descriptor = message.DESCRIPTOR for field in message_descriptor.fields: # Singular message fields and oneof fields will not be affected. if ((field.label != descriptor.FieldDescriptor.LABEL_REPEATED and field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE) or field.containing_oneof): continue if self.preserving_proto_field_name: name = field.name else: name = field.json_name if name in js: # Skip the field which has been serailized already. continue if _IsMapEntry(field): js[name] = {} elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED: js[name] = [] else: js[name] = self._FieldToJsonObject(field, field.default_value) except ValueError as e: raise SerializeToJsonError( 'Failed to serialize {0} field: {1}.'.format(field.name, e)) return js
[ "def", "_RegularMessageToJsonObject", "(", "self", ",", "message", ",", "js", ")", ":", "fields", "=", "message", ".", "ListFields", "(", ")", "try", ":", "for", "field", ",", "value", "in", "fields", ":", "if", "self", ".", "preserving_proto_field_name", ":", "name", "=", "field", ".", "name", "else", ":", "name", "=", "field", ".", "json_name", "if", "_IsMapEntry", "(", "field", ")", ":", "# Convert a map field.", "v_field", "=", "field", ".", "message_type", ".", "fields_by_name", "[", "'value'", "]", "js_map", "=", "{", "}", "for", "key", "in", "value", ":", "if", "isinstance", "(", "key", ",", "bool", ")", ":", "if", "key", ":", "recorded_key", "=", "'true'", "else", ":", "recorded_key", "=", "'false'", "else", ":", "recorded_key", "=", "key", "js_map", "[", "recorded_key", "]", "=", "self", ".", "_FieldToJsonObject", "(", "v_field", ",", "value", "[", "key", "]", ")", "js", "[", "name", "]", "=", "js_map", "elif", "field", ".", "label", "==", "descriptor", ".", "FieldDescriptor", ".", "LABEL_REPEATED", ":", "# Convert a repeated field.", "js", "[", "name", "]", "=", "[", "self", ".", "_FieldToJsonObject", "(", "field", ",", "k", ")", "for", "k", "in", "value", "]", "else", ":", "js", "[", "name", "]", "=", "self", ".", "_FieldToJsonObject", "(", "field", ",", "value", ")", "# Serialize default value if including_default_value_fields is True.", "if", "self", ".", "including_default_value_fields", ":", "message_descriptor", "=", "message", ".", "DESCRIPTOR", "for", "field", "in", "message_descriptor", ".", "fields", ":", "# Singular message fields and oneof fields will not be affected.", "if", "(", "(", "field", ".", "label", "!=", "descriptor", ".", "FieldDescriptor", ".", "LABEL_REPEATED", "and", "field", ".", "cpp_type", "==", "descriptor", ".", "FieldDescriptor", ".", "CPPTYPE_MESSAGE", ")", "or", "field", ".", "containing_oneof", ")", ":", "continue", "if", "self", ".", "preserving_proto_field_name", ":", "name", "=", "field", ".", "name", "else", ":", "name", "=", "field", ".", "json_name", "if", "name", "in", "js", ":", "# Skip the field which has been serailized already.", "continue", "if", "_IsMapEntry", "(", "field", ")", ":", "js", "[", "name", "]", "=", "{", "}", "elif", "field", ".", "label", "==", "descriptor", ".", "FieldDescriptor", ".", "LABEL_REPEATED", ":", "js", "[", "name", "]", "=", "[", "]", "else", ":", "js", "[", "name", "]", "=", "self", ".", "_FieldToJsonObject", "(", "field", ",", "field", ".", "default_value", ")", "except", "ValueError", "as", "e", ":", "raise", "SerializeToJsonError", "(", "'Failed to serialize {0} field: {1}.'", ".", "format", "(", "field", ".", "name", ",", "e", ")", ")", "return", "js" ]
Converts normal message according to Proto3 JSON Specification.
[ "Converts", "normal", "message", "according", "to", "Proto3", "JSON", "Specification", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py#L166-L225
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py
_Printer._FieldToJsonObject
def _FieldToJsonObject(self, field, value): """Converts field value according to Proto3 JSON Specification.""" if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE: return self._MessageToJsonObject(value) elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM: enum_value = field.enum_type.values_by_number.get(value, None) if enum_value is not None: return enum_value.name else: raise SerializeToJsonError('Enum field contains an integer value ' 'which can not mapped to an enum value.') elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_STRING: if field.type == descriptor.FieldDescriptor.TYPE_BYTES: # Use base64 Data encoding for bytes return base64.b64encode(value).decode('utf-8') else: return value elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL: return bool(value) elif field.cpp_type in _INT64_TYPES: return str(value) elif field.cpp_type in _FLOAT_TYPES: if math.isinf(value): if value < 0.0: return _NEG_INFINITY else: return _INFINITY if math.isnan(value): return _NAN return value
python
def _FieldToJsonObject(self, field, value): """Converts field value according to Proto3 JSON Specification.""" if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE: return self._MessageToJsonObject(value) elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM: enum_value = field.enum_type.values_by_number.get(value, None) if enum_value is not None: return enum_value.name else: raise SerializeToJsonError('Enum field contains an integer value ' 'which can not mapped to an enum value.') elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_STRING: if field.type == descriptor.FieldDescriptor.TYPE_BYTES: # Use base64 Data encoding for bytes return base64.b64encode(value).decode('utf-8') else: return value elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL: return bool(value) elif field.cpp_type in _INT64_TYPES: return str(value) elif field.cpp_type in _FLOAT_TYPES: if math.isinf(value): if value < 0.0: return _NEG_INFINITY else: return _INFINITY if math.isnan(value): return _NAN return value
[ "def", "_FieldToJsonObject", "(", "self", ",", "field", ",", "value", ")", ":", "if", "field", ".", "cpp_type", "==", "descriptor", ".", "FieldDescriptor", ".", "CPPTYPE_MESSAGE", ":", "return", "self", ".", "_MessageToJsonObject", "(", "value", ")", "elif", "field", ".", "cpp_type", "==", "descriptor", ".", "FieldDescriptor", ".", "CPPTYPE_ENUM", ":", "enum_value", "=", "field", ".", "enum_type", ".", "values_by_number", ".", "get", "(", "value", ",", "None", ")", "if", "enum_value", "is", "not", "None", ":", "return", "enum_value", ".", "name", "else", ":", "raise", "SerializeToJsonError", "(", "'Enum field contains an integer value '", "'which can not mapped to an enum value.'", ")", "elif", "field", ".", "cpp_type", "==", "descriptor", ".", "FieldDescriptor", ".", "CPPTYPE_STRING", ":", "if", "field", ".", "type", "==", "descriptor", ".", "FieldDescriptor", ".", "TYPE_BYTES", ":", "# Use base64 Data encoding for bytes", "return", "base64", ".", "b64encode", "(", "value", ")", ".", "decode", "(", "'utf-8'", ")", "else", ":", "return", "value", "elif", "field", ".", "cpp_type", "==", "descriptor", ".", "FieldDescriptor", ".", "CPPTYPE_BOOL", ":", "return", "bool", "(", "value", ")", "elif", "field", ".", "cpp_type", "in", "_INT64_TYPES", ":", "return", "str", "(", "value", ")", "elif", "field", ".", "cpp_type", "in", "_FLOAT_TYPES", ":", "if", "math", ".", "isinf", "(", "value", ")", ":", "if", "value", "<", "0.0", ":", "return", "_NEG_INFINITY", "else", ":", "return", "_INFINITY", "if", "math", ".", "isnan", "(", "value", ")", ":", "return", "_NAN", "return", "value" ]
Converts field value according to Proto3 JSON Specification.
[ "Converts", "field", "value", "according", "to", "Proto3", "JSON", "Specification", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py#L227-L256
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py
_Printer._AnyMessageToJsonObject
def _AnyMessageToJsonObject(self, message): """Converts Any message according to Proto3 JSON Specification.""" if not message.ListFields(): return {} # Must print @type first, use OrderedDict instead of {} js = OrderedDict() type_url = message.type_url js['@type'] = type_url sub_message = _CreateMessageFromTypeUrl(type_url) sub_message.ParseFromString(message.value) message_descriptor = sub_message.DESCRIPTOR full_name = message_descriptor.full_name if _IsWrapperMessage(message_descriptor): js['value'] = self._WrapperMessageToJsonObject(sub_message) return js if full_name in _WKTJSONMETHODS: js['value'] = methodcaller(_WKTJSONMETHODS[full_name][0], sub_message)(self) return js return self._RegularMessageToJsonObject(sub_message, js)
python
def _AnyMessageToJsonObject(self, message): """Converts Any message according to Proto3 JSON Specification.""" if not message.ListFields(): return {} # Must print @type first, use OrderedDict instead of {} js = OrderedDict() type_url = message.type_url js['@type'] = type_url sub_message = _CreateMessageFromTypeUrl(type_url) sub_message.ParseFromString(message.value) message_descriptor = sub_message.DESCRIPTOR full_name = message_descriptor.full_name if _IsWrapperMessage(message_descriptor): js['value'] = self._WrapperMessageToJsonObject(sub_message) return js if full_name in _WKTJSONMETHODS: js['value'] = methodcaller(_WKTJSONMETHODS[full_name][0], sub_message)(self) return js return self._RegularMessageToJsonObject(sub_message, js)
[ "def", "_AnyMessageToJsonObject", "(", "self", ",", "message", ")", ":", "if", "not", "message", ".", "ListFields", "(", ")", ":", "return", "{", "}", "# Must print @type first, use OrderedDict instead of {}", "js", "=", "OrderedDict", "(", ")", "type_url", "=", "message", ".", "type_url", "js", "[", "'@type'", "]", "=", "type_url", "sub_message", "=", "_CreateMessageFromTypeUrl", "(", "type_url", ")", "sub_message", ".", "ParseFromString", "(", "message", ".", "value", ")", "message_descriptor", "=", "sub_message", ".", "DESCRIPTOR", "full_name", "=", "message_descriptor", ".", "full_name", "if", "_IsWrapperMessage", "(", "message_descriptor", ")", ":", "js", "[", "'value'", "]", "=", "self", ".", "_WrapperMessageToJsonObject", "(", "sub_message", ")", "return", "js", "if", "full_name", "in", "_WKTJSONMETHODS", ":", "js", "[", "'value'", "]", "=", "methodcaller", "(", "_WKTJSONMETHODS", "[", "full_name", "]", "[", "0", "]", ",", "sub_message", ")", "(", "self", ")", "return", "js", "return", "self", ".", "_RegularMessageToJsonObject", "(", "sub_message", ",", "js", ")" ]
Converts Any message according to Proto3 JSON Specification.
[ "Converts", "Any", "message", "according", "to", "Proto3", "JSON", "Specification", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py#L258-L277
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py
_Printer._ValueMessageToJsonObject
def _ValueMessageToJsonObject(self, message): """Converts Value message according to Proto3 JSON Specification.""" which = message.WhichOneof('kind') # If the Value message is not set treat as null_value when serialize # to JSON. The parse back result will be different from original message. if which is None or which == 'null_value': return None if which == 'list_value': return self._ListValueMessageToJsonObject(message.list_value) if which == 'struct_value': value = message.struct_value else: value = getattr(message, which) oneof_descriptor = message.DESCRIPTOR.fields_by_name[which] return self._FieldToJsonObject(oneof_descriptor, value)
python
def _ValueMessageToJsonObject(self, message): """Converts Value message according to Proto3 JSON Specification.""" which = message.WhichOneof('kind') # If the Value message is not set treat as null_value when serialize # to JSON. The parse back result will be different from original message. if which is None or which == 'null_value': return None if which == 'list_value': return self._ListValueMessageToJsonObject(message.list_value) if which == 'struct_value': value = message.struct_value else: value = getattr(message, which) oneof_descriptor = message.DESCRIPTOR.fields_by_name[which] return self._FieldToJsonObject(oneof_descriptor, value)
[ "def", "_ValueMessageToJsonObject", "(", "self", ",", "message", ")", ":", "which", "=", "message", ".", "WhichOneof", "(", "'kind'", ")", "# If the Value message is not set treat as null_value when serialize", "# to JSON. The parse back result will be different from original message.", "if", "which", "is", "None", "or", "which", "==", "'null_value'", ":", "return", "None", "if", "which", "==", "'list_value'", ":", "return", "self", ".", "_ListValueMessageToJsonObject", "(", "message", ".", "list_value", ")", "if", "which", "==", "'struct_value'", ":", "value", "=", "message", ".", "struct_value", "else", ":", "value", "=", "getattr", "(", "message", ",", "which", ")", "oneof_descriptor", "=", "message", ".", "DESCRIPTOR", ".", "fields_by_name", "[", "which", "]", "return", "self", ".", "_FieldToJsonObject", "(", "oneof_descriptor", ",", "value", ")" ]
Converts Value message according to Proto3 JSON Specification.
[ "Converts", "Value", "message", "according", "to", "Proto3", "JSON", "Specification", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py#L285-L299
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py
_Printer._StructMessageToJsonObject
def _StructMessageToJsonObject(self, message): """Converts Struct message according to Proto3 JSON Specification.""" fields = message.fields ret = {} for key in fields: ret[key] = self._ValueMessageToJsonObject(fields[key]) return ret
python
def _StructMessageToJsonObject(self, message): """Converts Struct message according to Proto3 JSON Specification.""" fields = message.fields ret = {} for key in fields: ret[key] = self._ValueMessageToJsonObject(fields[key]) return ret
[ "def", "_StructMessageToJsonObject", "(", "self", ",", "message", ")", ":", "fields", "=", "message", ".", "fields", "ret", "=", "{", "}", "for", "key", "in", "fields", ":", "ret", "[", "key", "]", "=", "self", ".", "_ValueMessageToJsonObject", "(", "fields", "[", "key", "]", ")", "return", "ret" ]
Converts Struct message according to Proto3 JSON Specification.
[ "Converts", "Struct", "message", "according", "to", "Proto3", "JSON", "Specification", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py#L306-L312
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py
_Parser.ConvertMessage
def ConvertMessage(self, value, message): """Convert a JSON object into a message. Args: value: A JSON object. message: A WKT or regular protocol message to record the data. Raises: ParseError: In case of convert problems. """ message_descriptor = message.DESCRIPTOR full_name = message_descriptor.full_name if _IsWrapperMessage(message_descriptor): self._ConvertWrapperMessage(value, message) elif full_name in _WKTJSONMETHODS: methodcaller(_WKTJSONMETHODS[full_name][1], value, message)(self) else: self._ConvertFieldValuePair(value, message)
python
def ConvertMessage(self, value, message): """Convert a JSON object into a message. Args: value: A JSON object. message: A WKT or regular protocol message to record the data. Raises: ParseError: In case of convert problems. """ message_descriptor = message.DESCRIPTOR full_name = message_descriptor.full_name if _IsWrapperMessage(message_descriptor): self._ConvertWrapperMessage(value, message) elif full_name in _WKTJSONMETHODS: methodcaller(_WKTJSONMETHODS[full_name][1], value, message)(self) else: self._ConvertFieldValuePair(value, message)
[ "def", "ConvertMessage", "(", "self", ",", "value", ",", "message", ")", ":", "message_descriptor", "=", "message", ".", "DESCRIPTOR", "full_name", "=", "message_descriptor", ".", "full_name", "if", "_IsWrapperMessage", "(", "message_descriptor", ")", ":", "self", ".", "_ConvertWrapperMessage", "(", "value", ",", "message", ")", "elif", "full_name", "in", "_WKTJSONMETHODS", ":", "methodcaller", "(", "_WKTJSONMETHODS", "[", "full_name", "]", "[", "1", "]", ",", "value", ",", "message", ")", "(", "self", ")", "else", ":", "self", ".", "_ConvertFieldValuePair", "(", "value", ",", "message", ")" ]
Convert a JSON object into a message. Args: value: A JSON object. message: A WKT or regular protocol message to record the data. Raises: ParseError: In case of convert problems.
[ "Convert", "a", "JSON", "object", "into", "a", "message", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py#L398-L415
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py
_Parser._ConvertFieldValuePair
def _ConvertFieldValuePair(self, js, message): """Convert field value pairs into regular message. Args: js: A JSON object to convert the field value pairs. message: A regular protocol message to record the data. Raises: ParseError: In case of problems converting. """ names = [] message_descriptor = message.DESCRIPTOR fields_by_json_name = dict((f.json_name, f) for f in message_descriptor.fields) for name in js: try: field = fields_by_json_name.get(name, None) if not field: field = message_descriptor.fields_by_name.get(name, None) if not field: if self.ignore_unknown_fields: continue raise ParseError( 'Message type "{0}" has no field named "{1}".'.format( message_descriptor.full_name, name)) if name in names: raise ParseError('Message type "{0}" should not have multiple ' '"{1}" fields.'.format( message.DESCRIPTOR.full_name, name)) names.append(name) # Check no other oneof field is parsed. if field.containing_oneof is not None: oneof_name = field.containing_oneof.name if oneof_name in names: raise ParseError('Message type "{0}" should not have multiple ' '"{1}" oneof fields.'.format( message.DESCRIPTOR.full_name, oneof_name)) names.append(oneof_name) value = js[name] if value is None: if (field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE and field.message_type.full_name == 'google.protobuf.Value'): sub_message = getattr(message, field.name) sub_message.null_value = 0 else: message.ClearField(field.name) continue # Parse field value. if _IsMapEntry(field): message.ClearField(field.name) self._ConvertMapFieldValue(value, message, field) elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED: message.ClearField(field.name) if not isinstance(value, list): raise ParseError('repeated field {0} must be in [] which is ' '{1}.'.format(name, value)) if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE: # Repeated message field. for item in value: sub_message = getattr(message, field.name).add() # None is a null_value in Value. if (item is None and sub_message.DESCRIPTOR.full_name != 'google.protobuf.Value'): raise ParseError('null is not allowed to be used as an element' ' in a repeated field.') self.ConvertMessage(item, sub_message) else: # Repeated scalar field. for item in value: if item is None: raise ParseError('null is not allowed to be used as an element' ' in a repeated field.') getattr(message, field.name).append( _ConvertScalarFieldValue(item, field)) elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE: sub_message = getattr(message, field.name) sub_message.SetInParent() self.ConvertMessage(value, sub_message) else: setattr(message, field.name, _ConvertScalarFieldValue(value, field)) except ParseError as e: if field and field.containing_oneof is None: raise ParseError('Failed to parse {0} field: {1}'.format(name, e)) else: raise ParseError(str(e)) except ValueError as e: raise ParseError('Failed to parse {0} field: {1}.'.format(name, e)) except TypeError as e: raise ParseError('Failed to parse {0} field: {1}.'.format(name, e))
python
def _ConvertFieldValuePair(self, js, message): """Convert field value pairs into regular message. Args: js: A JSON object to convert the field value pairs. message: A regular protocol message to record the data. Raises: ParseError: In case of problems converting. """ names = [] message_descriptor = message.DESCRIPTOR fields_by_json_name = dict((f.json_name, f) for f in message_descriptor.fields) for name in js: try: field = fields_by_json_name.get(name, None) if not field: field = message_descriptor.fields_by_name.get(name, None) if not field: if self.ignore_unknown_fields: continue raise ParseError( 'Message type "{0}" has no field named "{1}".'.format( message_descriptor.full_name, name)) if name in names: raise ParseError('Message type "{0}" should not have multiple ' '"{1}" fields.'.format( message.DESCRIPTOR.full_name, name)) names.append(name) # Check no other oneof field is parsed. if field.containing_oneof is not None: oneof_name = field.containing_oneof.name if oneof_name in names: raise ParseError('Message type "{0}" should not have multiple ' '"{1}" oneof fields.'.format( message.DESCRIPTOR.full_name, oneof_name)) names.append(oneof_name) value = js[name] if value is None: if (field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE and field.message_type.full_name == 'google.protobuf.Value'): sub_message = getattr(message, field.name) sub_message.null_value = 0 else: message.ClearField(field.name) continue # Parse field value. if _IsMapEntry(field): message.ClearField(field.name) self._ConvertMapFieldValue(value, message, field) elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED: message.ClearField(field.name) if not isinstance(value, list): raise ParseError('repeated field {0} must be in [] which is ' '{1}.'.format(name, value)) if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE: # Repeated message field. for item in value: sub_message = getattr(message, field.name).add() # None is a null_value in Value. if (item is None and sub_message.DESCRIPTOR.full_name != 'google.protobuf.Value'): raise ParseError('null is not allowed to be used as an element' ' in a repeated field.') self.ConvertMessage(item, sub_message) else: # Repeated scalar field. for item in value: if item is None: raise ParseError('null is not allowed to be used as an element' ' in a repeated field.') getattr(message, field.name).append( _ConvertScalarFieldValue(item, field)) elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE: sub_message = getattr(message, field.name) sub_message.SetInParent() self.ConvertMessage(value, sub_message) else: setattr(message, field.name, _ConvertScalarFieldValue(value, field)) except ParseError as e: if field and field.containing_oneof is None: raise ParseError('Failed to parse {0} field: {1}'.format(name, e)) else: raise ParseError(str(e)) except ValueError as e: raise ParseError('Failed to parse {0} field: {1}.'.format(name, e)) except TypeError as e: raise ParseError('Failed to parse {0} field: {1}.'.format(name, e))
[ "def", "_ConvertFieldValuePair", "(", "self", ",", "js", ",", "message", ")", ":", "names", "=", "[", "]", "message_descriptor", "=", "message", ".", "DESCRIPTOR", "fields_by_json_name", "=", "dict", "(", "(", "f", ".", "json_name", ",", "f", ")", "for", "f", "in", "message_descriptor", ".", "fields", ")", "for", "name", "in", "js", ":", "try", ":", "field", "=", "fields_by_json_name", ".", "get", "(", "name", ",", "None", ")", "if", "not", "field", ":", "field", "=", "message_descriptor", ".", "fields_by_name", ".", "get", "(", "name", ",", "None", ")", "if", "not", "field", ":", "if", "self", ".", "ignore_unknown_fields", ":", "continue", "raise", "ParseError", "(", "'Message type \"{0}\" has no field named \"{1}\".'", ".", "format", "(", "message_descriptor", ".", "full_name", ",", "name", ")", ")", "if", "name", "in", "names", ":", "raise", "ParseError", "(", "'Message type \"{0}\" should not have multiple '", "'\"{1}\" fields.'", ".", "format", "(", "message", ".", "DESCRIPTOR", ".", "full_name", ",", "name", ")", ")", "names", ".", "append", "(", "name", ")", "# Check no other oneof field is parsed.", "if", "field", ".", "containing_oneof", "is", "not", "None", ":", "oneof_name", "=", "field", ".", "containing_oneof", ".", "name", "if", "oneof_name", "in", "names", ":", "raise", "ParseError", "(", "'Message type \"{0}\" should not have multiple '", "'\"{1}\" oneof fields.'", ".", "format", "(", "message", ".", "DESCRIPTOR", ".", "full_name", ",", "oneof_name", ")", ")", "names", ".", "append", "(", "oneof_name", ")", "value", "=", "js", "[", "name", "]", "if", "value", "is", "None", ":", "if", "(", "field", ".", "cpp_type", "==", "descriptor", ".", "FieldDescriptor", ".", "CPPTYPE_MESSAGE", "and", "field", ".", "message_type", ".", "full_name", "==", "'google.protobuf.Value'", ")", ":", "sub_message", "=", "getattr", "(", "message", ",", "field", ".", "name", ")", "sub_message", ".", "null_value", "=", "0", "else", ":", "message", ".", "ClearField", "(", "field", ".", "name", ")", "continue", "# Parse field value.", "if", "_IsMapEntry", "(", "field", ")", ":", "message", ".", "ClearField", "(", "field", ".", "name", ")", "self", ".", "_ConvertMapFieldValue", "(", "value", ",", "message", ",", "field", ")", "elif", "field", ".", "label", "==", "descriptor", ".", "FieldDescriptor", ".", "LABEL_REPEATED", ":", "message", ".", "ClearField", "(", "field", ".", "name", ")", "if", "not", "isinstance", "(", "value", ",", "list", ")", ":", "raise", "ParseError", "(", "'repeated field {0} must be in [] which is '", "'{1}.'", ".", "format", "(", "name", ",", "value", ")", ")", "if", "field", ".", "cpp_type", "==", "descriptor", ".", "FieldDescriptor", ".", "CPPTYPE_MESSAGE", ":", "# Repeated message field.", "for", "item", "in", "value", ":", "sub_message", "=", "getattr", "(", "message", ",", "field", ".", "name", ")", ".", "add", "(", ")", "# None is a null_value in Value.", "if", "(", "item", "is", "None", "and", "sub_message", ".", "DESCRIPTOR", ".", "full_name", "!=", "'google.protobuf.Value'", ")", ":", "raise", "ParseError", "(", "'null is not allowed to be used as an element'", "' in a repeated field.'", ")", "self", ".", "ConvertMessage", "(", "item", ",", "sub_message", ")", "else", ":", "# Repeated scalar field.", "for", "item", "in", "value", ":", "if", "item", "is", "None", ":", "raise", "ParseError", "(", "'null is not allowed to be used as an element'", "' in a repeated field.'", ")", "getattr", "(", "message", ",", "field", ".", "name", ")", ".", "append", "(", "_ConvertScalarFieldValue", "(", "item", ",", "field", ")", ")", "elif", "field", ".", "cpp_type", "==", "descriptor", ".", "FieldDescriptor", ".", "CPPTYPE_MESSAGE", ":", "sub_message", "=", "getattr", "(", "message", ",", "field", ".", "name", ")", "sub_message", ".", "SetInParent", "(", ")", "self", ".", "ConvertMessage", "(", "value", ",", "sub_message", ")", "else", ":", "setattr", "(", "message", ",", "field", ".", "name", ",", "_ConvertScalarFieldValue", "(", "value", ",", "field", ")", ")", "except", "ParseError", "as", "e", ":", "if", "field", "and", "field", ".", "containing_oneof", "is", "None", ":", "raise", "ParseError", "(", "'Failed to parse {0} field: {1}'", ".", "format", "(", "name", ",", "e", ")", ")", "else", ":", "raise", "ParseError", "(", "str", "(", "e", ")", ")", "except", "ValueError", "as", "e", ":", "raise", "ParseError", "(", "'Failed to parse {0} field: {1}.'", ".", "format", "(", "name", ",", "e", ")", ")", "except", "TypeError", "as", "e", ":", "raise", "ParseError", "(", "'Failed to parse {0} field: {1}.'", ".", "format", "(", "name", ",", "e", ")", ")" ]
Convert field value pairs into regular message. Args: js: A JSON object to convert the field value pairs. message: A regular protocol message to record the data. Raises: ParseError: In case of problems converting.
[ "Convert", "field", "value", "pairs", "into", "regular", "message", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py#L417-L507
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py
_Parser._ConvertAnyMessage
def _ConvertAnyMessage(self, value, message): """Convert a JSON representation into Any message.""" if isinstance(value, dict) and not value: return try: type_url = value['@type'] except KeyError: raise ParseError('@type is missing when parsing any message.') sub_message = _CreateMessageFromTypeUrl(type_url) message_descriptor = sub_message.DESCRIPTOR full_name = message_descriptor.full_name if _IsWrapperMessage(message_descriptor): self._ConvertWrapperMessage(value['value'], sub_message) elif full_name in _WKTJSONMETHODS: methodcaller( _WKTJSONMETHODS[full_name][1], value['value'], sub_message)(self) else: del value['@type'] self._ConvertFieldValuePair(value, sub_message) # Sets Any message message.value = sub_message.SerializeToString() message.type_url = type_url
python
def _ConvertAnyMessage(self, value, message): """Convert a JSON representation into Any message.""" if isinstance(value, dict) and not value: return try: type_url = value['@type'] except KeyError: raise ParseError('@type is missing when parsing any message.') sub_message = _CreateMessageFromTypeUrl(type_url) message_descriptor = sub_message.DESCRIPTOR full_name = message_descriptor.full_name if _IsWrapperMessage(message_descriptor): self._ConvertWrapperMessage(value['value'], sub_message) elif full_name in _WKTJSONMETHODS: methodcaller( _WKTJSONMETHODS[full_name][1], value['value'], sub_message)(self) else: del value['@type'] self._ConvertFieldValuePair(value, sub_message) # Sets Any message message.value = sub_message.SerializeToString() message.type_url = type_url
[ "def", "_ConvertAnyMessage", "(", "self", ",", "value", ",", "message", ")", ":", "if", "isinstance", "(", "value", ",", "dict", ")", "and", "not", "value", ":", "return", "try", ":", "type_url", "=", "value", "[", "'@type'", "]", "except", "KeyError", ":", "raise", "ParseError", "(", "'@type is missing when parsing any message.'", ")", "sub_message", "=", "_CreateMessageFromTypeUrl", "(", "type_url", ")", "message_descriptor", "=", "sub_message", ".", "DESCRIPTOR", "full_name", "=", "message_descriptor", ".", "full_name", "if", "_IsWrapperMessage", "(", "message_descriptor", ")", ":", "self", ".", "_ConvertWrapperMessage", "(", "value", "[", "'value'", "]", ",", "sub_message", ")", "elif", "full_name", "in", "_WKTJSONMETHODS", ":", "methodcaller", "(", "_WKTJSONMETHODS", "[", "full_name", "]", "[", "1", "]", ",", "value", "[", "'value'", "]", ",", "sub_message", ")", "(", "self", ")", "else", ":", "del", "value", "[", "'@type'", "]", "self", ".", "_ConvertFieldValuePair", "(", "value", ",", "sub_message", ")", "# Sets Any message", "message", ".", "value", "=", "sub_message", ".", "SerializeToString", "(", ")", "message", ".", "type_url", "=", "type_url" ]
Convert a JSON representation into Any message.
[ "Convert", "a", "JSON", "representation", "into", "Any", "message", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py#L509-L531
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py
_Parser._ConvertWrapperMessage
def _ConvertWrapperMessage(self, value, message): """Convert a JSON representation into Wrapper message.""" field = message.DESCRIPTOR.fields_by_name['value'] setattr(message, 'value', _ConvertScalarFieldValue(value, field))
python
def _ConvertWrapperMessage(self, value, message): """Convert a JSON representation into Wrapper message.""" field = message.DESCRIPTOR.fields_by_name['value'] setattr(message, 'value', _ConvertScalarFieldValue(value, field))
[ "def", "_ConvertWrapperMessage", "(", "self", ",", "value", ",", "message", ")", ":", "field", "=", "message", ".", "DESCRIPTOR", ".", "fields_by_name", "[", "'value'", "]", "setattr", "(", "message", ",", "'value'", ",", "_ConvertScalarFieldValue", "(", "value", ",", "field", ")", ")" ]
Convert a JSON representation into Wrapper message.
[ "Convert", "a", "JSON", "representation", "into", "Wrapper", "message", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py#L574-L577
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py
_Parser._ConvertMapFieldValue
def _ConvertMapFieldValue(self, value, message, field): """Convert map field value for a message map field. Args: value: A JSON object to convert the map field value. message: A protocol message to record the converted data. field: The descriptor of the map field to be converted. Raises: ParseError: In case of convert problems. """ if not isinstance(value, dict): raise ParseError( 'Map field {0} must be in a dict which is {1}.'.format( field.name, value)) key_field = field.message_type.fields_by_name['key'] value_field = field.message_type.fields_by_name['value'] for key in value: key_value = _ConvertScalarFieldValue(key, key_field, True) if value_field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE: self.ConvertMessage(value[key], getattr( message, field.name)[key_value]) else: getattr(message, field.name)[key_value] = _ConvertScalarFieldValue( value[key], value_field)
python
def _ConvertMapFieldValue(self, value, message, field): """Convert map field value for a message map field. Args: value: A JSON object to convert the map field value. message: A protocol message to record the converted data. field: The descriptor of the map field to be converted. Raises: ParseError: In case of convert problems. """ if not isinstance(value, dict): raise ParseError( 'Map field {0} must be in a dict which is {1}.'.format( field.name, value)) key_field = field.message_type.fields_by_name['key'] value_field = field.message_type.fields_by_name['value'] for key in value: key_value = _ConvertScalarFieldValue(key, key_field, True) if value_field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE: self.ConvertMessage(value[key], getattr( message, field.name)[key_value]) else: getattr(message, field.name)[key_value] = _ConvertScalarFieldValue( value[key], value_field)
[ "def", "_ConvertMapFieldValue", "(", "self", ",", "value", ",", "message", ",", "field", ")", ":", "if", "not", "isinstance", "(", "value", ",", "dict", ")", ":", "raise", "ParseError", "(", "'Map field {0} must be in a dict which is {1}.'", ".", "format", "(", "field", ".", "name", ",", "value", ")", ")", "key_field", "=", "field", ".", "message_type", ".", "fields_by_name", "[", "'key'", "]", "value_field", "=", "field", ".", "message_type", ".", "fields_by_name", "[", "'value'", "]", "for", "key", "in", "value", ":", "key_value", "=", "_ConvertScalarFieldValue", "(", "key", ",", "key_field", ",", "True", ")", "if", "value_field", ".", "cpp_type", "==", "descriptor", ".", "FieldDescriptor", ".", "CPPTYPE_MESSAGE", ":", "self", ".", "ConvertMessage", "(", "value", "[", "key", "]", ",", "getattr", "(", "message", ",", "field", ".", "name", ")", "[", "key_value", "]", ")", "else", ":", "getattr", "(", "message", ",", "field", ".", "name", ")", "[", "key_value", "]", "=", "_ConvertScalarFieldValue", "(", "value", "[", "key", "]", ",", "value_field", ")" ]
Convert map field value for a message map field. Args: value: A JSON object to convert the map field value. message: A protocol message to record the converted data. field: The descriptor of the map field to be converted. Raises: ParseError: In case of convert problems.
[ "Convert", "map", "field", "value", "for", "a", "message", "map", "field", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py#L579-L603
train
apple/turicreate
src/unity/python/turicreate/visualization/show.py
plot
def plot(x, y, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT, title=LABEL_DEFAULT): """ Plots the data in `x` on the X axis and the data in `y` on the Y axis in a 2d visualization, and shows the resulting visualization. Uses the following heuristic to choose the visualization: * If `x` and `y` are both numeric (SArray of int or float), and they contain fewer than or equal to 5,000 values, show a scatter plot. * If `x` and `y` are both numeric (SArray of int or float), and they contain more than 5,000 values, show a heat map. * If `x` is numeric and `y` is an SArray of string, show a box and whisker plot for the distribution of numeric values for each categorical (string) value. * If `x` and `y` are both SArrays of string, show a categorical heat map. This show method supports SArrays of dtypes: int, float, str. Notes ----- - The plot will be returned as a Plot object, which can then be shown, saved, etc. and will display automatically in a Jupyter Notebook. Parameters ---------- x : SArray The data to plot on the X axis of a 2d visualization. y : SArray The data to plot on the Y axis of a 2d visualization. Must be the same length as `x`. xlabel : str (optional) The text label for the X axis. Defaults to "X". ylabel : str (optional) The text label for the Y axis. Defaults to "Y". title : str (optional) The title of the plot. Defaults to LABEL_DEFAULT. If the value is LABEL_DEFAULT, the title will be "<xlabel> vs. <ylabel>". If the value is None, the title will be omitted. Otherwise, the string passed in as the title will be used as the plot title. Examples -------- Show a categorical heat map of pets and their feelings. >>> x = turicreate.SArray(['dog', 'cat', 'dog', 'dog', 'cat']) >>> y = turicreate.SArray(['happy', 'grumpy', 'grumpy', 'happy', 'grumpy']) >>> turicreate.show(x, y) Show a scatter plot of the function y = 2x, for x from 0 through 9, labeling the axes and plot title with custom strings. >>> x = turicreate.SArray(range(10)) >>> y = x * 2 >>> turicreate.show(x, y, ... xlabel="Custom X label", ... ylabel="Custom Y label", ... title="Custom title") """ title = _get_title(title) plt_ref = tc.extensions.plot(x, y, xlabel, ylabel, title) return Plot(plt_ref)
python
def plot(x, y, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT, title=LABEL_DEFAULT): """ Plots the data in `x` on the X axis and the data in `y` on the Y axis in a 2d visualization, and shows the resulting visualization. Uses the following heuristic to choose the visualization: * If `x` and `y` are both numeric (SArray of int or float), and they contain fewer than or equal to 5,000 values, show a scatter plot. * If `x` and `y` are both numeric (SArray of int or float), and they contain more than 5,000 values, show a heat map. * If `x` is numeric and `y` is an SArray of string, show a box and whisker plot for the distribution of numeric values for each categorical (string) value. * If `x` and `y` are both SArrays of string, show a categorical heat map. This show method supports SArrays of dtypes: int, float, str. Notes ----- - The plot will be returned as a Plot object, which can then be shown, saved, etc. and will display automatically in a Jupyter Notebook. Parameters ---------- x : SArray The data to plot on the X axis of a 2d visualization. y : SArray The data to plot on the Y axis of a 2d visualization. Must be the same length as `x`. xlabel : str (optional) The text label for the X axis. Defaults to "X". ylabel : str (optional) The text label for the Y axis. Defaults to "Y". title : str (optional) The title of the plot. Defaults to LABEL_DEFAULT. If the value is LABEL_DEFAULT, the title will be "<xlabel> vs. <ylabel>". If the value is None, the title will be omitted. Otherwise, the string passed in as the title will be used as the plot title. Examples -------- Show a categorical heat map of pets and their feelings. >>> x = turicreate.SArray(['dog', 'cat', 'dog', 'dog', 'cat']) >>> y = turicreate.SArray(['happy', 'grumpy', 'grumpy', 'happy', 'grumpy']) >>> turicreate.show(x, y) Show a scatter plot of the function y = 2x, for x from 0 through 9, labeling the axes and plot title with custom strings. >>> x = turicreate.SArray(range(10)) >>> y = x * 2 >>> turicreate.show(x, y, ... xlabel="Custom X label", ... ylabel="Custom Y label", ... title="Custom title") """ title = _get_title(title) plt_ref = tc.extensions.plot(x, y, xlabel, ylabel, title) return Plot(plt_ref)
[ "def", "plot", "(", "x", ",", "y", ",", "xlabel", "=", "LABEL_DEFAULT", ",", "ylabel", "=", "LABEL_DEFAULT", ",", "title", "=", "LABEL_DEFAULT", ")", ":", "title", "=", "_get_title", "(", "title", ")", "plt_ref", "=", "tc", ".", "extensions", ".", "plot", "(", "x", ",", "y", ",", "xlabel", ",", "ylabel", ",", "title", ")", "return", "Plot", "(", "plt_ref", ")" ]
Plots the data in `x` on the X axis and the data in `y` on the Y axis in a 2d visualization, and shows the resulting visualization. Uses the following heuristic to choose the visualization: * If `x` and `y` are both numeric (SArray of int or float), and they contain fewer than or equal to 5,000 values, show a scatter plot. * If `x` and `y` are both numeric (SArray of int or float), and they contain more than 5,000 values, show a heat map. * If `x` is numeric and `y` is an SArray of string, show a box and whisker plot for the distribution of numeric values for each categorical (string) value. * If `x` and `y` are both SArrays of string, show a categorical heat map. This show method supports SArrays of dtypes: int, float, str. Notes ----- - The plot will be returned as a Plot object, which can then be shown, saved, etc. and will display automatically in a Jupyter Notebook. Parameters ---------- x : SArray The data to plot on the X axis of a 2d visualization. y : SArray The data to plot on the Y axis of a 2d visualization. Must be the same length as `x`. xlabel : str (optional) The text label for the X axis. Defaults to "X". ylabel : str (optional) The text label for the Y axis. Defaults to "Y". title : str (optional) The title of the plot. Defaults to LABEL_DEFAULT. If the value is LABEL_DEFAULT, the title will be "<xlabel> vs. <ylabel>". If the value is None, the title will be omitted. Otherwise, the string passed in as the title will be used as the plot title. Examples -------- Show a categorical heat map of pets and their feelings. >>> x = turicreate.SArray(['dog', 'cat', 'dog', 'dog', 'cat']) >>> y = turicreate.SArray(['happy', 'grumpy', 'grumpy', 'happy', 'grumpy']) >>> turicreate.show(x, y) Show a scatter plot of the function y = 2x, for x from 0 through 9, labeling the axes and plot title with custom strings. >>> x = turicreate.SArray(range(10)) >>> y = x * 2 >>> turicreate.show(x, y, ... xlabel="Custom X label", ... ylabel="Custom Y label", ... title="Custom title")
[ "Plots", "the", "data", "in", "x", "on", "the", "X", "axis", "and", "the", "data", "in", "y", "on", "the", "Y", "axis", "in", "a", "2d", "visualization", "and", "shows", "the", "resulting", "visualization", ".", "Uses", "the", "following", "heuristic", "to", "choose", "the", "visualization", ":" ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/visualization/show.py#L20-L81
train
apple/turicreate
src/unity/python/turicreate/visualization/show.py
show
def show(x, y, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT, title=LABEL_DEFAULT): """ Plots the data in `x` on the X axis and the data in `y` on the Y axis in a 2d visualization, and shows the resulting visualization. Uses the following heuristic to choose the visualization: * If `x` and `y` are both numeric (SArray of int or float), and they contain fewer than or equal to 5,000 values, show a scatter plot. * If `x` and `y` are both numeric (SArray of int or float), and they contain more than 5,000 values, show a heat map. * If `x` is numeric and `y` is an SArray of string, show a box and whisker plot for the distribution of numeric values for each categorical (string) value. * If `x` and `y` are both SArrays of string, show a categorical heat map. This show method supports SArrays of dtypes: int, float, str. Notes ----- - The plot will render either inline in a Jupyter Notebook, or in a native GUI window, depending on the value provided in `turicreate.visualization.set_target` (defaults to 'auto'). Parameters ---------- x : SArray The data to plot on the X axis of a 2d visualization. y : SArray The data to plot on the Y axis of a 2d visualization. Must be the same length as `x`. xlabel : str (optional) The text label for the X axis. Defaults to "X". ylabel : str (optional) The text label for the Y axis. Defaults to "Y". title : str (optional) The title of the plot. Defaults to LABEL_DEFAULT. If the value is LABEL_DEFAULT, the title will be "<xlabel> vs. <ylabel>". If the value is None, the title will be omitted. Otherwise, the string passed in as the title will be used as the plot title. Examples -------- Show a categorical heat map of pets and their feelings. >>> x = turicreate.SArray(['dog', 'cat', 'dog', 'dog', 'cat']) >>> y = turicreate.SArray(['happy', 'grumpy', 'grumpy', 'happy', 'grumpy']) >>> turicreate.show(x, y) Show a scatter plot of the function y = 2x, for x from 0 through 9, labeling the axes and plot title with custom strings. >>> x = turicreate.SArray(range(10)) >>> y = x * 2 >>> turicreate.show(x, y, ... xlabel="Custom X label", ... ylabel="Custom Y label", ... title="Custom title") """ plot(x, y, xlabel, ylabel, title).show()
python
def show(x, y, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT, title=LABEL_DEFAULT): """ Plots the data in `x` on the X axis and the data in `y` on the Y axis in a 2d visualization, and shows the resulting visualization. Uses the following heuristic to choose the visualization: * If `x` and `y` are both numeric (SArray of int or float), and they contain fewer than or equal to 5,000 values, show a scatter plot. * If `x` and `y` are both numeric (SArray of int or float), and they contain more than 5,000 values, show a heat map. * If `x` is numeric and `y` is an SArray of string, show a box and whisker plot for the distribution of numeric values for each categorical (string) value. * If `x` and `y` are both SArrays of string, show a categorical heat map. This show method supports SArrays of dtypes: int, float, str. Notes ----- - The plot will render either inline in a Jupyter Notebook, or in a native GUI window, depending on the value provided in `turicreate.visualization.set_target` (defaults to 'auto'). Parameters ---------- x : SArray The data to plot on the X axis of a 2d visualization. y : SArray The data to plot on the Y axis of a 2d visualization. Must be the same length as `x`. xlabel : str (optional) The text label for the X axis. Defaults to "X". ylabel : str (optional) The text label for the Y axis. Defaults to "Y". title : str (optional) The title of the plot. Defaults to LABEL_DEFAULT. If the value is LABEL_DEFAULT, the title will be "<xlabel> vs. <ylabel>". If the value is None, the title will be omitted. Otherwise, the string passed in as the title will be used as the plot title. Examples -------- Show a categorical heat map of pets and their feelings. >>> x = turicreate.SArray(['dog', 'cat', 'dog', 'dog', 'cat']) >>> y = turicreate.SArray(['happy', 'grumpy', 'grumpy', 'happy', 'grumpy']) >>> turicreate.show(x, y) Show a scatter plot of the function y = 2x, for x from 0 through 9, labeling the axes and plot title with custom strings. >>> x = turicreate.SArray(range(10)) >>> y = x * 2 >>> turicreate.show(x, y, ... xlabel="Custom X label", ... ylabel="Custom Y label", ... title="Custom title") """ plot(x, y, xlabel, ylabel, title).show()
[ "def", "show", "(", "x", ",", "y", ",", "xlabel", "=", "LABEL_DEFAULT", ",", "ylabel", "=", "LABEL_DEFAULT", ",", "title", "=", "LABEL_DEFAULT", ")", ":", "plot", "(", "x", ",", "y", ",", "xlabel", ",", "ylabel", ",", "title", ")", ".", "show", "(", ")" ]
Plots the data in `x` on the X axis and the data in `y` on the Y axis in a 2d visualization, and shows the resulting visualization. Uses the following heuristic to choose the visualization: * If `x` and `y` are both numeric (SArray of int or float), and they contain fewer than or equal to 5,000 values, show a scatter plot. * If `x` and `y` are both numeric (SArray of int or float), and they contain more than 5,000 values, show a heat map. * If `x` is numeric and `y` is an SArray of string, show a box and whisker plot for the distribution of numeric values for each categorical (string) value. * If `x` and `y` are both SArrays of string, show a categorical heat map. This show method supports SArrays of dtypes: int, float, str. Notes ----- - The plot will render either inline in a Jupyter Notebook, or in a native GUI window, depending on the value provided in `turicreate.visualization.set_target` (defaults to 'auto'). Parameters ---------- x : SArray The data to plot on the X axis of a 2d visualization. y : SArray The data to plot on the Y axis of a 2d visualization. Must be the same length as `x`. xlabel : str (optional) The text label for the X axis. Defaults to "X". ylabel : str (optional) The text label for the Y axis. Defaults to "Y". title : str (optional) The title of the plot. Defaults to LABEL_DEFAULT. If the value is LABEL_DEFAULT, the title will be "<xlabel> vs. <ylabel>". If the value is None, the title will be omitted. Otherwise, the string passed in as the title will be used as the plot title. Examples -------- Show a categorical heat map of pets and their feelings. >>> x = turicreate.SArray(['dog', 'cat', 'dog', 'dog', 'cat']) >>> y = turicreate.SArray(['happy', 'grumpy', 'grumpy', 'happy', 'grumpy']) >>> turicreate.show(x, y) Show a scatter plot of the function y = 2x, for x from 0 through 9, labeling the axes and plot title with custom strings. >>> x = turicreate.SArray(range(10)) >>> y = x * 2 >>> turicreate.show(x, y, ... xlabel="Custom X label", ... ylabel="Custom Y label", ... title="Custom title")
[ "Plots", "the", "data", "in", "x", "on", "the", "X", "axis", "and", "the", "data", "in", "y", "on", "the", "Y", "axis", "in", "a", "2d", "visualization", "and", "shows", "the", "resulting", "visualization", ".", "Uses", "the", "following", "heuristic", "to", "choose", "the", "visualization", ":" ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/visualization/show.py#L83-L143
train
apple/turicreate
src/unity/python/turicreate/visualization/show.py
scatter
def scatter(x, y, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT, title=LABEL_DEFAULT): """ Plots the data in `x` on the X axis and the data in `y` on the Y axis in a 2d scatter plot, and returns the resulting Plot object. The function supports SArrays of dtypes: int, float. Parameters ---------- x : SArray The data to plot on the X axis of the scatter plot. Must be numeric (int/float). y : SArray The data to plot on the Y axis of the scatter plot. Must be the same length as `x`. Must be numeric (int/float). xlabel : str (optional) The text label for the X axis. Defaults to "X". ylabel : str (optional) The text label for the Y axis. Defaults to "Y". title : str (optional) The title of the plot. Defaults to LABEL_DEFAULT. If the value is LABEL_DEFAULT, the title will be "<xlabel> vs. <ylabel>". If the value is None, the title will be omitted. Otherwise, the string passed in as the title will be used as the plot title. Returns ------- out : Plot A :class: Plot object that is the scatter plot. Examples -------- Make a scatter plot. >>> x = turicreate.SArray([1,2,3,4,5]) >>> y = x * 2 >>> scplt = turicreate.visualization.scatter(x, y) """ if (not isinstance(x, tc.data_structures.sarray.SArray) or not isinstance(y, tc.data_structures.sarray.SArray) or x.dtype not in [int, float] or y.dtype not in [int, float]): raise ValueError("turicreate.visualization.scatter supports " + "SArrays of dtypes: int, float") # legit input title = _get_title(title) plt_ref = tc.extensions.plot_scatter(x, y, xlabel, ylabel,title) return Plot(plt_ref)
python
def scatter(x, y, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT, title=LABEL_DEFAULT): """ Plots the data in `x` on the X axis and the data in `y` on the Y axis in a 2d scatter plot, and returns the resulting Plot object. The function supports SArrays of dtypes: int, float. Parameters ---------- x : SArray The data to plot on the X axis of the scatter plot. Must be numeric (int/float). y : SArray The data to plot on the Y axis of the scatter plot. Must be the same length as `x`. Must be numeric (int/float). xlabel : str (optional) The text label for the X axis. Defaults to "X". ylabel : str (optional) The text label for the Y axis. Defaults to "Y". title : str (optional) The title of the plot. Defaults to LABEL_DEFAULT. If the value is LABEL_DEFAULT, the title will be "<xlabel> vs. <ylabel>". If the value is None, the title will be omitted. Otherwise, the string passed in as the title will be used as the plot title. Returns ------- out : Plot A :class: Plot object that is the scatter plot. Examples -------- Make a scatter plot. >>> x = turicreate.SArray([1,2,3,4,5]) >>> y = x * 2 >>> scplt = turicreate.visualization.scatter(x, y) """ if (not isinstance(x, tc.data_structures.sarray.SArray) or not isinstance(y, tc.data_structures.sarray.SArray) or x.dtype not in [int, float] or y.dtype not in [int, float]): raise ValueError("turicreate.visualization.scatter supports " + "SArrays of dtypes: int, float") # legit input title = _get_title(title) plt_ref = tc.extensions.plot_scatter(x, y, xlabel, ylabel,title) return Plot(plt_ref)
[ "def", "scatter", "(", "x", ",", "y", ",", "xlabel", "=", "LABEL_DEFAULT", ",", "ylabel", "=", "LABEL_DEFAULT", ",", "title", "=", "LABEL_DEFAULT", ")", ":", "if", "(", "not", "isinstance", "(", "x", ",", "tc", ".", "data_structures", ".", "sarray", ".", "SArray", ")", "or", "not", "isinstance", "(", "y", ",", "tc", ".", "data_structures", ".", "sarray", ".", "SArray", ")", "or", "x", ".", "dtype", "not", "in", "[", "int", ",", "float", "]", "or", "y", ".", "dtype", "not", "in", "[", "int", ",", "float", "]", ")", ":", "raise", "ValueError", "(", "\"turicreate.visualization.scatter supports \"", "+", "\"SArrays of dtypes: int, float\"", ")", "# legit input", "title", "=", "_get_title", "(", "title", ")", "plt_ref", "=", "tc", ".", "extensions", ".", "plot_scatter", "(", "x", ",", "y", ",", "xlabel", ",", "ylabel", ",", "title", ")", "return", "Plot", "(", "plt_ref", ")" ]
Plots the data in `x` on the X axis and the data in `y` on the Y axis in a 2d scatter plot, and returns the resulting Plot object. The function supports SArrays of dtypes: int, float. Parameters ---------- x : SArray The data to plot on the X axis of the scatter plot. Must be numeric (int/float). y : SArray The data to plot on the Y axis of the scatter plot. Must be the same length as `x`. Must be numeric (int/float). xlabel : str (optional) The text label for the X axis. Defaults to "X". ylabel : str (optional) The text label for the Y axis. Defaults to "Y". title : str (optional) The title of the plot. Defaults to LABEL_DEFAULT. If the value is LABEL_DEFAULT, the title will be "<xlabel> vs. <ylabel>". If the value is None, the title will be omitted. Otherwise, the string passed in as the title will be used as the plot title. Returns ------- out : Plot A :class: Plot object that is the scatter plot. Examples -------- Make a scatter plot. >>> x = turicreate.SArray([1,2,3,4,5]) >>> y = x * 2 >>> scplt = turicreate.visualization.scatter(x, y)
[ "Plots", "the", "data", "in", "x", "on", "the", "X", "axis", "and", "the", "data", "in", "y", "on", "the", "Y", "axis", "in", "a", "2d", "scatter", "plot", "and", "returns", "the", "resulting", "Plot", "object", ".", "The", "function", "supports", "SArrays", "of", "dtypes", ":", "int", "float", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/visualization/show.py#L145-L193
train
apple/turicreate
src/unity/python/turicreate/visualization/show.py
categorical_heatmap
def categorical_heatmap(x, y, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT, title=LABEL_DEFAULT): """ Plots the data in `x` on the X axis and the data in `y` on the Y axis in a 2d categorical heatmap, and returns the resulting Plot object. The function supports SArrays of dtypes str. Parameters ---------- x : SArray The data to plot on the X axis of the categorical heatmap. Must be string SArray y : SArray The data to plot on the Y axis of the categorical heatmap. Must be string SArray and must be the same length as `x`. xlabel : str (optional) The text label for the X axis. Defaults to "X". ylabel : str (optional) The text label for the Y axis. Defaults to "Y". title : str (optional) The title of the plot. Defaults to LABEL_DEFAULT. If the value is LABEL_DEFAULT, the title will be "<xlabel> vs. <ylabel>". If the value is None, the title will be omitted. Otherwise, the string passed in as the title will be used as the plot title. Returns ------- out : Plot A :class: Plot object that is the categorical heatmap. Examples -------- Make a categorical heatmap. >>> x = turicreate.SArray(['1','2','3','4','5']) >>> y = turicreate.SArray(['a','b','c','d','e']) >>> catheat = turicreate.visualization.categorical_heatmap(x, y) """ if (not isinstance(x, tc.data_structures.sarray.SArray) or not isinstance(y, tc.data_structures.sarray.SArray) or x.dtype != str or y.dtype != str): raise ValueError("turicreate.visualization.categorical_heatmap supports " + "SArrays of dtype: str") # legit input title = _get_title(title) plt_ref = tc.extensions.plot_categorical_heatmap(x, y, xlabel, ylabel, title) return Plot(plt_ref)
python
def categorical_heatmap(x, y, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT, title=LABEL_DEFAULT): """ Plots the data in `x` on the X axis and the data in `y` on the Y axis in a 2d categorical heatmap, and returns the resulting Plot object. The function supports SArrays of dtypes str. Parameters ---------- x : SArray The data to plot on the X axis of the categorical heatmap. Must be string SArray y : SArray The data to plot on the Y axis of the categorical heatmap. Must be string SArray and must be the same length as `x`. xlabel : str (optional) The text label for the X axis. Defaults to "X". ylabel : str (optional) The text label for the Y axis. Defaults to "Y". title : str (optional) The title of the plot. Defaults to LABEL_DEFAULT. If the value is LABEL_DEFAULT, the title will be "<xlabel> vs. <ylabel>". If the value is None, the title will be omitted. Otherwise, the string passed in as the title will be used as the plot title. Returns ------- out : Plot A :class: Plot object that is the categorical heatmap. Examples -------- Make a categorical heatmap. >>> x = turicreate.SArray(['1','2','3','4','5']) >>> y = turicreate.SArray(['a','b','c','d','e']) >>> catheat = turicreate.visualization.categorical_heatmap(x, y) """ if (not isinstance(x, tc.data_structures.sarray.SArray) or not isinstance(y, tc.data_structures.sarray.SArray) or x.dtype != str or y.dtype != str): raise ValueError("turicreate.visualization.categorical_heatmap supports " + "SArrays of dtype: str") # legit input title = _get_title(title) plt_ref = tc.extensions.plot_categorical_heatmap(x, y, xlabel, ylabel, title) return Plot(plt_ref)
[ "def", "categorical_heatmap", "(", "x", ",", "y", ",", "xlabel", "=", "LABEL_DEFAULT", ",", "ylabel", "=", "LABEL_DEFAULT", ",", "title", "=", "LABEL_DEFAULT", ")", ":", "if", "(", "not", "isinstance", "(", "x", ",", "tc", ".", "data_structures", ".", "sarray", ".", "SArray", ")", "or", "not", "isinstance", "(", "y", ",", "tc", ".", "data_structures", ".", "sarray", ".", "SArray", ")", "or", "x", ".", "dtype", "!=", "str", "or", "y", ".", "dtype", "!=", "str", ")", ":", "raise", "ValueError", "(", "\"turicreate.visualization.categorical_heatmap supports \"", "+", "\"SArrays of dtype: str\"", ")", "# legit input", "title", "=", "_get_title", "(", "title", ")", "plt_ref", "=", "tc", ".", "extensions", ".", "plot_categorical_heatmap", "(", "x", ",", "y", ",", "xlabel", ",", "ylabel", ",", "title", ")", "return", "Plot", "(", "plt_ref", ")" ]
Plots the data in `x` on the X axis and the data in `y` on the Y axis in a 2d categorical heatmap, and returns the resulting Plot object. The function supports SArrays of dtypes str. Parameters ---------- x : SArray The data to plot on the X axis of the categorical heatmap. Must be string SArray y : SArray The data to plot on the Y axis of the categorical heatmap. Must be string SArray and must be the same length as `x`. xlabel : str (optional) The text label for the X axis. Defaults to "X". ylabel : str (optional) The text label for the Y axis. Defaults to "Y". title : str (optional) The title of the plot. Defaults to LABEL_DEFAULT. If the value is LABEL_DEFAULT, the title will be "<xlabel> vs. <ylabel>". If the value is None, the title will be omitted. Otherwise, the string passed in as the title will be used as the plot title. Returns ------- out : Plot A :class: Plot object that is the categorical heatmap. Examples -------- Make a categorical heatmap. >>> x = turicreate.SArray(['1','2','3','4','5']) >>> y = turicreate.SArray(['a','b','c','d','e']) >>> catheat = turicreate.visualization.categorical_heatmap(x, y)
[ "Plots", "the", "data", "in", "x", "on", "the", "X", "axis", "and", "the", "data", "in", "y", "on", "the", "Y", "axis", "in", "a", "2d", "categorical", "heatmap", "and", "returns", "the", "resulting", "Plot", "object", ".", "The", "function", "supports", "SArrays", "of", "dtypes", "str", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/visualization/show.py#L195-L242
train