text:
CodeGeneration Options - Maple Help

CodeGeneration Options

 This help page describes the options used by the language translation commands in the CodeGeneration package.

Options

 coercetypes=value
 Specifies whether type coercion is to be performed.  Permissible values are true and false.  The default value is true.  When the option coercetypes=true (or simply coercetypes) is given, then an explicit coercion from one data type to another is generated wherever appropriate.  Constants are automatically converted to the required type.
 declare=[declaration(s)]
 Specifies the types of variables.  Each declaration has the form $\mathrm{varname}::\mathrm{vartype}$ where varname is a variable name and vartype is one of the Maple type names recognized by CodeGeneration, as described in TranslationDetails. Declarations specified using this option override any other type declarations within the input code.  The declare option is designed to be used with procedures and computation sequences only.
 deducereturn=value
 Specifies whether deduction of explicit returns should be attempted. Permissible values are true and false.  The default value is true. When the option deducereturn=true (or simply deducereturn) is given, the translator looks for an implicit return and if one is found, converts it to an explicit return.
 deducetypes=value
 Specifies whether automatic type deduction is to be performed.  Permissible values are true and false.  The default value is true. When the option deducetypes=true (or simply deducetypes) is given, the translator attempts to deduce the type of a variable based on the context in which it is found; otherwise, the variable is assigned a default type. If the option deducetypes=false is given, then all untyped variables are assigned the default type.
 defaulttype=value
 Specifies the default type. Any Maple type is accepted as a default type. It is mapped to the more limited set of types accepted by CodeGeneration, choosing the minimal type of which the given is a subtype if possible. Otherwise, if a type is not recognized by CodeGeneration, as described in TranslationDetails, then the default type is assumed. For example, float goes to numeric, posint goes to integer, and symbol goes to double.
 digits=value
 Specifies the number of digits used in the floating-point evaluation of known constants.  The value must be a positive integer and the default is the current setting of Digits. For some target languages, a symbolic constant is used in place of a literal float, and the digits option does not affect the accuracy of the symbols definition in that target.
 expandarrays=value
 Specifies how to translate the assignment of arrays.  (Here, array is used to mean a variety of Maple data structures, as described in TranslationDetails.) Permissible values are true and false.  The default value is true. This option applies to languages that do not have built-in support for array copying.  When the option expandarrays=true (or simply expandarrays) is given, element-wise assignments are generated from the input statement $x:=y\text{'}\text{'}$, where $x$ and $y$ are both arrays.  If the option expandarrays=false is given, then a simple assignment of y to x is generated, and the user must replace this statement with the appropriate code for array assignments in the target language, if necessary.
 functionprecision=value
 Specifies the numeric precision of expressions that appear as arguments and return values of functions in the input. Permissible values are single and double. The CodeGeneration[Fortran] function also accepts generic.  The default value is generic for Fortran and double for all other CodeGeneration functions. This option affects only the translation of function names and not the precision of variables.
 libraryorder=value
 Specifies how conflicts are to be resolved when the target language defines multiple function translations for a particular type signature.  The value for libraryorder is a list of strings, each string corresponding to a library.  If there are multiple available function translations available, CodeGeneration will choose the translation associated with the library appearing first in the libraryorder list.
 limitvariablelength=value
 Specifies whether variable names longer than 6 characters will be replaced. Permissible values are true and false.  The default value is true.  This option is available for the CodeGeneration[Fortran] command only.  The Fortran 77 standard requires that all variable names be no longer than 6 characters.  Use the limitvariablelength=false option to prevent the automatic replacement of long names.
 optimize=value
 Specifies whether optimization should be performed.  Permissible values are true,false, and tryhard.  The default value is false. When the option optimize=true (or simply optimize) is given, the Maple input is optimized using codegen[optimize] before it is translated. When the option optimize=tryhard is given, the Maple input is optimized using a stronger internal optimizer. For more information about how the optimization is performed, see TranslationDetails. The optimize option is designed to be used with procedures and computation sequences only.
 output=value
 Specifies the form of the output.  The value can be one of the symbols embed, string, terminal, or any Maple string.  The default value is terminal, which results in formatted output being printed to the terminal.  The option output=embed displays the formatted output in the document inside a text field.  If the option output=string is provided, then a string containing the result is returned.  This string may then be assigned and manipulated. If a string is given as the value, then the result is appended to a file having that name.
 precision=value
 Specifies the precision used for floating-point variables and constants. Permissible values are single and double. The default value is double.
 reduceanalysis=value
 Specifies whether a reduced form of analysis should be performed.  Permissible values are true and false.  The default value is false. This option is applicable only when the Maple code to be translated is a list of equations representing a computation sequence; the option cannot be used with modules and procedures. When the option reduceanalysis=true (or simply reduceanalysis) is given, the computation sequence is analyzed and translated one line at a time.  In contrast, the default behavior is to analyze the entire computation sequence as a whole, so that any type information collected during analysis of one assignment is applied to analysis of subsequent assignments.  Applying a full analysis means that the translated code is less likely to contain type mismatches; however, using the reduceanalysis=true option can significantly reduce the time and memory required for translation.
 resultname=value
 Specifies the name of the result (that is, the generated procedure or the left-hand-side variable in the generated assignment) when the input is unnamed.  The value can be any string.  When no result name is specified or deduced, an automatically generated name is used.
 returnvariablename=value
 Specifies the name of the return variable used in translated procedures. It is used only when it is necessary to generate a new variable to hold the return value.  The value can be any string.  When no return variable name is specified, an automatically generated name is used.
 strict=value
 Specifies the tolerance for errors encountered during translation. The default value of 0 specifies that when there is no translation available for a intermediate code expression or a named function, CodeGeneration should issue a warning and insert a placeholder in the generated code.  Setting strict=1 causes CodeGeneration to instead issue an error and abort the translation in this case.

Examples

Most of the following examples use the CodeGeneration[C] function, but the options are available with all the other CodeGeneration functions, unless it is stated otherwise in the Options section above.

 > $\mathrm{with}\left(\mathrm{CodeGeneration}\right):$

The 'coercetypes' Option

In the first call below, the variable y is coerced to a floating-point type.  This coercion is not generated in the second call.

 > $C\left(\left[z=x+y\right],\mathrm{declare}=\left[x::\mathrm{numeric},y::'\mathrm{integer}'\right]\right)$
 z = x + (double) y;
 > $C\left(\left[z=x+y\right],\mathrm{declare}=\left[x::\mathrm{numeric},y::'\mathrm{integer}'\right],\mathrm{coercetypes}=\mathrm{false}\right)$
 z = x + y;

The 'declare' Option

In the following example, $x$ is assigned a floating-point number because it is declared to have type float.  Otherwise, the translator would have deduced that it has type integer and generated an assignment to the integer 1.

 > $C\left(\left[x=1\right],\mathrm{declare}=\left[x::\mathrm{float}\right]\right)$
 x = 0.1e1;

The 'deducereturn' Option

The following Maple procedure returns the value 10 when invoked, but translation with the option deducereturn=false creates a C function with a void return type.

 > f := proc(x::Vector(4), n::integer) local i; for i to 4 do x[i] := 10 end do; end proc:
 > $C\left(f,\mathrm{deducereturn}=\mathrm{false}\right)$
 void f (int x[4], int n) {   int i;   for (i = 1; i <= 4; i++)     x[i - 1] = 10; }

The 'deducetypes' Option

In the following example, $x$ is given the default type, numeric, and so it is assigned a floating-point number.  Otherwise, the translator would have deduced that it has type integer and generated an assignment to the integer 1.

 > $C\left(\left[x=1\right],\mathrm{deducetypes}=\mathrm{false}\right)$
 x = 0.1e1;

The 'defaulttype' Option

In the following example, the untyped variables are given the type integer instead of numeric.  Thus the translation produces C declarations with type int rather than double.

 > f := proc(x) return x; end proc:
 > $C\left(f,\mathrm{defaulttype}=\mathrm{integer}\right)$
 int f (int x) {   return(x); }

The 'digits' Option

The following call shows how the digits option affects the translation of known constants.

 > $C\left(\mathrm{\pi },\mathrm{digits}=20\right)$
 cg = 0.31415926535897932385e1;

The 'expandarrays' Option

In the following example, the variable $\mathrm{cgret}$ is automatically created to hold the return values.  In the first call, statements to perform element-wise copying are generated.  In the second call, the assignment involves only the array names.  In this case, you must replace the assignments $\mathrm{cgret}=x\text{'}\text{'}$ and $\mathrm{cgret}=y\text{'}\text{'}$ in the output with appropriate C statements (for example, calls to a user-defined C function).

 > f := proc(x::Vector(2), y::Vector(2), z) if z > 0 then x else y end if; end proc:
 > $C\left(f\right)$
 void f (   double x[2],   double y[2],   int z,   double cgret[2]) {   if (0 < z)   {     cgret[0] = x[0];     cgret[1] = x[1];   }   else   {     cgret[0] = y[0];     cgret[1] = y[1];   } }
 > $C\left(f,\mathrm{expandarrays}=\mathrm{false}\right)$
 void f (   double x[2],   double y[2],   int z,   double cgret[2]) {   if (0 < z)     cgret = x;   else     cgret = y; }

The 'functionprecision' Option

The following example specifies that double precision Fortran function names are to be used instead of generic function names.

 > $\mathrm{Fortran}\left(\mathrm{sin}\left(x\right),\mathrm{functionprecision}=\mathrm{double},\mathrm{resultname}=w\right)$
 w = dsin(x)

The 'optimize' Option

In the following example, the computation sequence is optimized before it is translated.

 > $C\left(\left[x=yz,w=5.0yz\right],\mathrm{optimize}\right)$
 x = y * z; w = 0.50e1 * x;

The 'output' Option

In the following example, the result is put into a string and returned.

 > $s≔C\left(\left[y=\mathrm{sin}\left(x\right)\right],\mathrm{output}=\mathrm{string}\right)$
 ${s}{≔}{"y = sin\left(x\right);"}$ (1)

The 'precision' Option

The following example specifies that single precision variables and constants are to be generated.

 > f := proc(x) return x+2.0; end proc:
 > $C\left(f,\mathrm{precision}=\mathrm{single}\right)$
 float f (float x) {   return(x + 0.20e1f); }

The 'reduceanalysis' Option

In the first call below, full analysis is applied. The translator recognizes, in analyzing the second assignment, that the variable $x$ has been given an integer type and includes the necessary type coercion. In the second call, each assignment is analyzed and translated on its own, with no knowledge retained from analysis of previous assignments.

 > $s≔\left[x=1,y=x+2.0\right]:$
 > $\mathrm{CodeGeneration}\left[C\right]\left(s\right)$
 x = 1; y = (double) x + 0.20e1;
 > $\mathrm{CodeGeneration}\left[C\right]\left(s,\mathrm{reduceanalysis}\right)$
 x = 1; y = x + 0.20e1;

The 'resultname' Option

In the following example, the result is assigned to a variable with the specified name instead of an automatically generated name.

 > $C\left({x}^{y},\mathrm{resultname}="myresult"\right)$
 myresult = pow(x, y);

The 'returnvariablename' Option

In the following example, the return variable is given the specified name instead of an automatically generated name.

 > f := proc(n) local i; for i to n do i*n end do end proc:
 > $C\left(f,\mathrm{returnvariablename}="myreturn"\right)$
 int f (int n) {   int i;   int myreturn;   for (i = 1; i <= n; i++)     myreturn = i * n;   return(myreturn); }

The 'strict' Option

The following example illustrates the use of the strict setting.

 > $\mathrm{CodeGeneration}\left[C\right]\left(\mathrm{unknownFunction}\left(x\right)\right)$
 cg0 = unknownFunction(x);
 > $\mathrm{CodeGeneration}\left[C\right]\left(\mathrm{unknownFunction}\left(x\right),\mathrm{strict}=1\right)$

Compatibility

 • The optimize option was updated in Maple 15.
 • The libraryorder option was introduced in Maple 18.


text:
# Manuals/calci/IMCOSH

IMCOSH(ComplexNumber)

• where is any complex number of the form x+iy.

## Description

• This function gives the hyperbolic cosine (cosh) value of a complex number.
• Consider the complex number in the form of .
• x & y are the real numbers.
• 'i' is the imaginary unit
• Also x is called the real part & y is the imaginary part of a complex number.
• COMPLEX is the function used to convert Real & Imaginary numbers in to a complex number.
• is defined by

## Examples

IMCOSH(ComplexNumber)

• ComplexNumber is any complex number.
 IMCOSH(ComplexNumber) Value IMCOSH("7+4i") -358.4039322400531-i414.9670103107624 IMCOSH("7-8i") -79.78014715292208-i542.481078316949 IMCOSH("3") 10.067661995777764+i0

## Related Videos

Trigonometric Form of Complex Numbers

format: plain


text:
1 like 0 dislike
91 views
For real $c>0, c \neq 1$, and distinct points $\vec{p}$ and $\vec{q}$ in $\mathbb{R}^{k}$, consider the points $\vec{x} \in \mathbb{R}^{k}$ that satisfy
$\|\vec{x}-\vec{p}\|=c\|\vec{x}-\vec{q}\| .$
Show that these points lie on a sphere, say $\left\|\vec{x}-\vec{x}_{0}\right\|=r$, so the center is at $\vec{x}_{0}$ and the radius is $r$. Thus, find center and radius of this sphere in terms of $\vec{p}, \vec{q}$ and $c$. What if $c=1 ?$
| 91 views

0 like 0 dislike
0 like 0 dislike
1 like 0 dislike
1 like 0 dislike
1 like 0 dislike
0 like 0 dislike
1 like 0 dislike
1 like 0 dislike
1 like 0 dislike


text:
# 7.2. Real world datasets¶

They can be loaded using the following functions:

 fetch_olivetti_faces(*[, data_home, ...]) Load the Olivetti faces data-set from AT&T (classification). fetch_20newsgroups(*[, data_home, subset, ...]) Load the filenames and data from the 20 newsgroups dataset (classification). fetch_20newsgroups_vectorized(*[, subset, ...]) Load and vectorize the 20 newsgroups dataset (classification). fetch_lfw_people(*[, data_home, funneled, ...]) Load the Labeled Faces in the Wild (LFW) people dataset (classification). fetch_lfw_pairs(*[, subset, data_home, ...]) Load the Labeled Faces in the Wild (LFW) pairs dataset (classification). fetch_covtype(*[, data_home, ...]) Load the covertype dataset (classification). fetch_rcv1(*[, data_home, subset, ...]) Load the RCV1 multilabel dataset (classification). fetch_kddcup99(*[, subset, data_home, ...]) Load the kddcup99 dataset (classification). fetch_california_housing(*[, data_home, ...]) Load the California housing dataset (regression).

## 7.2.1. The Olivetti faces dataset¶

This dataset contains a set of face images taken between April 1992 and April 1994 at AT&T Laboratories Cambridge. The sklearn.datasets.fetch_olivetti_faces function is the data fetching / caching function that downloads the data archive from AT&T.

As described on the original website:

There are ten different images of each of 40 distinct subjects. For some subjects, the images were taken at different times, varying the lighting, facial expressions (open / closed eyes, smiling / not smiling) and facial details (glasses / no glasses). All the images were taken against a dark homogeneous background with the subjects in an upright, frontal position (with tolerance for some side movement).

Data Set Characteristics:

 Classes 40 Samples total 400 Dimensionality 4096 Features real, between 0 and 1

The image is quantized to 256 grey levels and stored as unsigned 8-bit integers; the loader will convert these to floating point values on the interval [0, 1], which are easier to work with for many algorithms.

The “target” for this database is an integer from 0 to 39 indicating the identity of the person pictured; however, with only 10 examples per class, this relatively small dataset is more interesting from an unsupervised or semi-supervised perspective.

The original dataset consisted of 92 x 112, while the version available here consists of 64x64 images.

When using these images, please give credit to AT&T Laboratories Cambridge.

## 7.2.2. The 20 newsgroups text dataset¶

The 20 newsgroups dataset comprises around 18000 newsgroups posts on 20 topics split in two subsets: one for training (or development) and the other one for testing (or for performance evaluation). The split between the train and test set is based upon a messages posted before and after a specific date.

This module contains two loaders. The first one, sklearn.datasets.fetch_20newsgroups, returns a list of the raw texts that can be fed to text feature extractors such as CountVectorizer with custom parameters so as to extract feature vectors. The second one, sklearn.datasets.fetch_20newsgroups_vectorized, returns ready-to-use features, i.e., it is not necessary to use a feature extractor.

Data Set Characteristics:

 Classes 20 Samples total 18846 Dimensionality 1 Features text

### 7.2.2.1. Usage¶

The sklearn.datasets.fetch_20newsgroups function is a data fetching / caching functions that downloads the data archive from the original 20 newsgroups website, extracts the archive contents in the ~/scikit_learn_data/20news_home folder and calls the sklearn.datasets.load_files on either the training or testing set folder, or both of them:

>>> from sklearn.datasets import fetch_20newsgroups
>>> newsgroups_train = fetch_20newsgroups(subset='train')

>>> from pprint import pprint
>>> pprint(list(newsgroups_train.target_names))
['alt.atheism',
'comp.graphics',
'comp.os.ms-windows.misc',
'comp.sys.ibm.pc.hardware',
'comp.sys.mac.hardware',
'comp.windows.x',
'misc.forsale',
'rec.autos',
'rec.motorcycles',
'rec.sport.baseball',
'rec.sport.hockey',
'sci.crypt',
'sci.electronics',
'sci.med',
'sci.space',
'soc.religion.christian',
'talk.politics.guns',
'talk.politics.mideast',
'talk.politics.misc',
'talk.religion.misc']

The real data lies in the filenames and target attributes. The target attribute is the integer index of the category:

>>> newsgroups_train.filenames.shape
(11314,)
>>> newsgroups_train.target.shape
(11314,)
>>> newsgroups_train.target[:10]
array([ 7,  4,  4,  1, 14, 16, 13,  3,  2,  4])

It is possible to load only a sub-selection of the categories by passing the list of the categories to load to the sklearn.datasets.fetch_20newsgroups function:

>>> cats = ['alt.atheism', 'sci.space']
>>> newsgroups_train = fetch_20newsgroups(subset='train', categories=cats)

>>> list(newsgroups_train.target_names)
['alt.atheism', 'sci.space']
>>> newsgroups_train.filenames.shape
(1073,)
>>> newsgroups_train.target.shape
(1073,)
>>> newsgroups_train.target[:10]
array([0, 1, 1, 1, 0, 1, 1, 0, 0, 0])

### 7.2.2.2. Converting text to vectors¶

In order to feed predictive or clustering models with the text data, one first need to turn the text into vectors of numerical values suitable for statistical analysis. This can be achieved with the utilities of the sklearn.feature_extraction.text as demonstrated in the following example that extract TF-IDF vectors of unigram tokens from a subset of 20news:

>>> from sklearn.feature_extraction.text import TfidfVectorizer
>>> categories = ['alt.atheism', 'talk.religion.misc',
...               'comp.graphics', 'sci.space']
>>> newsgroups_train = fetch_20newsgroups(subset='train',
...                                       categories=categories)
>>> vectorizer = TfidfVectorizer()
>>> vectors = vectorizer.fit_transform(newsgroups_train.data)
>>> vectors.shape
(2034, 34118)

The extracted TF-IDF vectors are very sparse, with an average of 159 non-zero components by sample in a more than 30000-dimensional space (less than .5% non-zero features):

>>> vectors.nnz / float(vectors.shape[0])
159.01327...

sklearn.datasets.fetch_20newsgroups_vectorized is a function which returns ready-to-use token counts features instead of file names.

### 7.2.2.3. Filtering text for more realistic training¶

It is easy for a classifier to overfit on particular things that appear in the 20 Newsgroups data, such as newsgroup headers. Many classifiers achieve very high F-scores, but their results would not generalize to other documents that aren’t from this window of time.

For example, let’s look at the results of a multinomial Naive Bayes classifier, which is fast to train and achieves a decent F-score:

>>> from sklearn.naive_bayes import MultinomialNB
>>> from sklearn import metrics
>>> newsgroups_test = fetch_20newsgroups(subset='test',
...                                      categories=categories)
>>> vectors_test = vectorizer.transform(newsgroups_test.data)
>>> clf = MultinomialNB(alpha=.01)
>>> clf.fit(vectors, newsgroups_train.target)
MultinomialNB(alpha=0.01, class_prior=None, fit_prior=True)

>>> pred = clf.predict(vectors_test)
>>> metrics.f1_score(newsgroups_test.target, pred, average='macro')
0.88213...

(The example Classification of text documents using sparse features shuffles the training and test data, instead of segmenting by time, and in that case multinomial Naive Bayes gets a much higher F-score of 0.88. Are you suspicious yet of what’s going on inside this classifier?)

Let’s take a look at what the most informative features are:

>>> import numpy as np
>>> def show_top10(classifier, vectorizer, categories):
...     feature_names = vectorizer.get_feature_names_out()
...     for i, category in enumerate(categories):
...         top10 = np.argsort(classifier.coef_[i])[-10:]
...         print("%s: %s" % (category, " ".join(feature_names[top10])))
...
>>> show_top10(clf, vectorizer, newsgroups_train.target_names)
alt.atheism: edu it and in you that is of to the
comp.graphics: edu in graphics it is for and of to the
sci.space: edu it that is in and space to of the
talk.religion.misc: not it you in is that and to of the

You can now see many things that these features have overfit to:

• Almost every group is distinguished by whether headers such as NNTP-Posting-Host: and Distribution: appear more or less often.

• Another significant feature involves whether the sender is affiliated with a university, as indicated either by their headers or their signature.

• The word “article” is a significant feature, based on how often people quote previous posts like this: “In article [article ID], [name] <[e-mail address]> wrote:”

• Other features match the names and e-mail addresses of particular people who were posting at the time.

With such an abundance of clues that distinguish newsgroups, the classifiers barely have to identify topics from text at all, and they all perform at the same high level.

For this reason, the functions that load 20 Newsgroups data provide a parameter called remove, telling it what kinds of information to strip out of each file. remove should be a tuple containing any subset of ('headers', 'footers', 'quotes'), telling it to remove headers, signature blocks, and quotation blocks respectively.

>>> newsgroups_test = fetch_20newsgroups(subset='test',
...                                      categories=categories)
>>> vectors_test = vectorizer.transform(newsgroups_test.data)
>>> pred = clf.predict(vectors_test)
>>> metrics.f1_score(pred, newsgroups_test.target, average='macro')
0.77310...

This classifier lost over a lot of its F-score, just because we removed metadata that has little to do with topic classification. It loses even more if we also strip this metadata from the training data:

>>> newsgroups_train = fetch_20newsgroups(subset='train',
...                                       categories=categories)
>>> vectors = vectorizer.fit_transform(newsgroups_train.data)
>>> clf = MultinomialNB(alpha=.01)
>>> clf.fit(vectors, newsgroups_train.target)
MultinomialNB(alpha=0.01, class_prior=None, fit_prior=True)

>>> vectors_test = vectorizer.transform(newsgroups_test.data)
>>> pred = clf.predict(vectors_test)
>>> metrics.f1_score(newsgroups_test.target, pred, average='macro')
0.76995...

Some other classifiers cope better with this harder version of the task. Try the Sample pipeline for text feature extraction and evaluation example with and without the remove option to compare the results.

## 7.2.3. The Labeled Faces in the Wild face recognition dataset¶

This dataset is a collection of JPEG pictures of famous people collected over the internet, all details are available on the official website:

Each picture is centered on a single face. The typical task is called Face Verification: given a pair of two pictures, a binary classifier must predict whether the two images are from the same person.

An alternative task, Face Recognition or Face Identification is: given the picture of the face of an unknown person, identify the name of the person by referring to a gallery of previously seen pictures of identified persons.

Both Face Verification and Face Recognition are tasks that are typically performed on the output of a model trained to perform Face Detection. The most popular model for Face Detection is called Viola-Jones and is implemented in the OpenCV library. The LFW faces were extracted by this face detector from various online websites.

Data Set Characteristics:

 Classes 5749 Samples total 13233 Dimensionality 5828 Features real, between 0 and 255

### 7.2.3.1. Usage¶

scikit-learn provides two loaders that will automatically download, cache, parse the metadata files, decode the jpeg and convert the interesting slices into memmapped numpy arrays. This dataset size is more than 200 MB. The first load typically takes more than a couple of minutes to fully decode the relevant part of the JPEG files into numpy arrays. If the dataset has been loaded once, the following times the loading times less than 200ms by using a memmapped version memoized on the disk in the ~/scikit_learn_data/lfw_home/ folder using joblib.

The first loader is used for the Face Identification task: a multi-class classification task (hence supervised learning):

>>> from sklearn.datasets import fetch_lfw_people
>>> lfw_people = fetch_lfw_people(min_faces_per_person=70, resize=0.4)

>>> for name in lfw_people.target_names:
...     print(name)
...
Ariel Sharon
Colin Powell
Donald Rumsfeld
George W Bush
Gerhard Schroeder
Hugo Chavez
Tony Blair

The default slice is a rectangular shape around the face, removing most of the background:

>>> lfw_people.data.dtype
dtype('float32')

>>> lfw_people.data.shape
(1288, 1850)

>>> lfw_people.images.shape
(1288, 50, 37)

Each of the 1140 faces is assigned to a single person id in the target array:

>>> lfw_people.target.shape
(1288,)

>>> list(lfw_people.target[:10])
[5, 6, 3, 1, 0, 1, 3, 4, 3, 0]

The second loader is typically used for the face verification task: each sample is a pair of two picture belonging or not to the same person:

>>> from sklearn.datasets import fetch_lfw_pairs
>>> lfw_pairs_train = fetch_lfw_pairs(subset='train')

>>> list(lfw_pairs_train.target_names)
['Different persons', 'Same person']

>>> lfw_pairs_train.pairs.shape
(2200, 2, 62, 47)

>>> lfw_pairs_train.data.shape
(2200, 5828)

>>> lfw_pairs_train.target.shape
(2200,)

Both for the sklearn.datasets.fetch_lfw_people and sklearn.datasets.fetch_lfw_pairs function it is possible to get an additional dimension with the RGB color channels by passing color=True, in that case the shape will be (2200, 2, 62, 47, 3).

The sklearn.datasets.fetch_lfw_pairs datasets is subdivided into 3 subsets: the development train set, the development test set and an evaluation 10_folds set meant to compute performance metrics using a 10-folds cross validation scheme.

### 7.2.3.2. Examples¶

Faces recognition example using eigenfaces and SVMs

## 7.2.4. Forest covertypes¶

The samples in this dataset correspond to 30×30m patches of forest in the US, collected for the task of predicting each patch’s cover type, i.e. the dominant species of tree. There are seven covertypes, making this a multiclass classification problem. Each sample has 54 features, described on the dataset’s homepage. Some of the features are boolean indicators, while others are discrete or continuous measurements.

Data Set Characteristics:

 Classes 7 Samples total 581012 Dimensionality 54 Features int

sklearn.datasets.fetch_covtype will load the covertype dataset; it returns a dictionary-like ‘Bunch’ object with the feature matrix in the data member and the target values in target. If optional argument ‘as_frame’ is set to ‘True’, it will return data and target as pandas data frame, and there will be an additional member frame as well. The dataset will be downloaded from the web if necessary.

## 7.2.5. RCV1 dataset¶

Reuters Corpus Volume I (RCV1) is an archive of over 800,000 manually categorized newswire stories made available by Reuters, Ltd. for research purposes. The dataset is extensively described in [1].

Data Set Characteristics:

 Classes 103 Samples total 804414 Dimensionality 47236 Features real, between 0 and 1

sklearn.datasets.fetch_rcv1 will load the following version: RCV1-v2, vectors, full sets, topics multilabels:

>>> from sklearn.datasets import fetch_rcv1
>>> rcv1 = fetch_rcv1()

It returns a dictionary-like object, with the following attributes:

data: The feature matrix is a scipy CSR sparse matrix, with 804414 samples and 47236 features. Non-zero values contains cosine-normalized, log TF-IDF vectors. A nearly chronological split is proposed in [1]: The first 23149 samples are the training set. The last 781265 samples are the testing set. This follows the official LYRL2004 chronological split. The array has 0.16% of non zero values:

>>> rcv1.data.shape
(804414, 47236)

target: The target values are stored in a scipy CSR sparse matrix, with 804414 samples and 103 categories. Each sample has a value of 1 in its categories, and 0 in others. The array has 3.15% of non zero values:

>>> rcv1.target.shape
(804414, 103)

sample_id: Each sample can be identified by its ID, ranging (with gaps) from 2286 to 810596:

>>> rcv1.sample_id[:3]
array([2286, 2287, 2288], dtype=uint32)

target_names: The target values are the topics of each sample. Each sample belongs to at least one topic, and to up to 17 topics. There are 103 topics, each represented by a string. Their corpus frequencies span five orders of magnitude, from 5 occurrences for ‘GMIL’, to 381327 for ‘CCAT’:

>>> rcv1.target_names[:3].tolist()
['E11', 'ECAT', 'M11']

The dataset will be downloaded from the rcv1 homepage if necessary. The compressed size is about 656 MB.

## 7.2.6. Kddcup 99 dataset¶

The KDD Cup ‘99 dataset was created by processing the tcpdump portions of the 1998 DARPA Intrusion Detection System (IDS) Evaluation dataset, created by MIT Lincoln Lab [2]. The artificial data (described on the dataset’s homepage) was generated using a closed network and hand-injected attacks to produce a large number of different types of attack with normal activity in the background. As the initial goal was to produce a large training set for supervised learning algorithms, there is a large proportion (80.1%) of abnormal data which is unrealistic in real world, and inappropriate for unsupervised anomaly detection which aims at detecting ‘abnormal’ data, i.e.:

• qualitatively different from normal data

• in large minority among the observations.

We thus transform the KDD Data set into two different data sets: SA and SF.

• SA is obtained by simply selecting all the normal data, and a small proportion of abnormal data to gives an anomaly proportion of 1%.

• SF is obtained as in [3] by simply picking up the data whose attribute logged_in is positive, thus focusing on the intrusion attack, which gives a proportion of 0.3% of attack.

• http and smtp are two subsets of SF corresponding with third feature equal to ‘http’ (resp. to ‘smtp’).

General KDD structure :

 Samples total 4898431 Dimensionality 41 Features discrete (int) or continuous (float) Targets str, ‘normal.’ or name of the anomaly type

SA structure :

 Samples total 976158 Dimensionality 41 Features discrete (int) or continuous (float) Targets str, ‘normal.’ or name of the anomaly type

SF structure :

 Samples total 699691 Dimensionality 4 Features discrete (int) or continuous (float) Targets str, ‘normal.’ or name of the anomaly type

http structure :

 Samples total 619052 Dimensionality 3 Features discrete (int) or continuous (float) Targets str, ‘normal.’ or name of the anomaly type

smtp structure :

 Samples total 95373 Dimensionality 3 Features discrete (int) or continuous (float) Targets str, ‘normal.’ or name of the anomaly type

sklearn.datasets.fetch_kddcup99 will load the kddcup99 dataset; it returns a dictionary-like object with the feature matrix in the data member and the target values in target. The “as_frame” optional argument converts data into a pandas DataFrame and target into a pandas Series. The dataset will be downloaded from the web if necessary.

## 7.2.7. California Housing dataset¶

Data Set Characteristics:

Number of Instances:

20640

Number of Attributes:

8 numeric, predictive attributes and the target

Attribute Information:
• MedInc median income in block group

• HouseAge median house age in block group

• AveRooms average number of rooms per household

• AveBedrms average number of bedrooms per household

• Population block group population

• AveOccup average number of household members

• Latitude block group latitude

• Longitude block group longitude

Missing Attribute Values:

None

This dataset was obtained from the StatLib repository. https://www.dcc.fc.up.pt/~ltorgo/Regression/cal_housing.html

The target variable is the median house value for California districts, expressed in hundreds of thousands of dollars (\$100,000).

This dataset was derived from the 1990 U.S. census, using one row per census block group. A block group is the smallest geographical unit for which the U.S. Census Bureau publishes sample data (a block group typically has a population of 600 to 3,000 people).

An household is a group of people residing within a home. Since the average number of rooms and bedrooms in this dataset are provided per household, these columns may take surpinsingly large values for block groups with few households and many empty houses, such as vacation resorts.

It can be downloaded/loaded using the sklearn.datasets.fetch_california_housing function.


text:
anonymous one year ago integrate dx/(4+x^2)^2 using trig substituition. im confused i thought it had to be a square root to be used no squared can some explain how toset these up?

1. zepdrix

$\large\rm \int\limits \frac{dx}{(4+x^2)^2}$Ummm trig sub? Yah that'll be fun :)

2. zepdrix

If you factor a 4 out of each term in the denominator you get$\large\rm \int\limits\limits \frac{dx}{(4+x^2)^2}=\frac{1}{4^2}\int\limits\frac{dx}{\left(1+\frac{1}{4}x^2\right)}$Let's bring the 1/4 into the square with the x,$\large\rm =\frac{1}{16}\int\limits\limits\frac{dx}{\left(1+\left[\frac{x}{2}\right]^2\right)}$Now we have that thing in the form: $$\large\rm 1+stuff^2$$ So we can make the substitution: $$\large\rm stuff=\tan\theta$$

3. zepdrix

$\large\rm \frac{x}{2}=\tan\theta$From there, find your $$\large\rm d\theta$$. Plug in all the stuff. Then we'll use some cool trig rules to simplify everything down, and hopefully, be able to integrate easily.

4. zepdrix

From there, find your $$\large\rm dx$$* is what I meant to say. Any trouble finding it? :o

5. zepdrix

Or were my steps confusing?

6. anonymous

Im sorry I just did not understand the find dtheta part. I converted (1+tan0) to sec^20 can i take the derivative of that to dnd d0?

7. zepdrix

$\large\rm =\frac{1}{16}\int\limits\limits\limits\limits\frac{dx}{\left(1+\left[\color{orangered}{\frac{x}{2}}\right]^2\right)^{2}}=\frac{1}{16}\int\limits\limits\limits\limits\frac{dx}{\left(1+\color{orangered}{\tan^2\theta}\right)^{2}}=\frac{1}{16}\int\limits\frac{dx}{\sec^4\theta}$So you've got that much figured out so far? To find dx, you need to go back to your original substitution. $$\large\rm \frac{x}{2}=\tan\theta$$ Take derivative of that thing.

8. anonymous

so it would turn do x=2tantheta and the derivative is sec^2theta do it would be dtheta over sec^2theta

9. zepdrix

Mmm are you missing a 2 in your dx maybe? Should look like this.$\large\rm x=2\tan theat\qquad\to\qquad \color{royalblue}{dx=2\sec^2\theta~d\theta}$ $\large\rm \frac{1}{16}\int\limits\limits\frac{\color{royalblue}{dx}}{\sec^4\theta}=\frac{1}{16}\int\limits\limits\frac{\color{royalblue}{2\sec^2\theta~d\theta}}{\sec^4\theta}$

10. zepdrix

Ah I made a typo in my x :) lol

11. zepdrix

$\large\rm =\frac{2}{16}\int\limits\frac{d \theta}{\sec^2\theta}$So something like this? Ya you have the right idea.

12. zepdrix

Recall that $\large\rm \cos\theta=\frac{1}{\sec\theta}$

13. anonymous

yeah i have that! and i would just u sub right?!

14. zepdrix

$\large\rm =\frac{1}{8}\int\limits \cos^2\theta~d \theta$ Hmm no. Looks like you'll have to use your Half-Angle Formula at this point. :)

15. anonymous

i got 1/8 * integral of cos^2theta

16. anonymous

$=\frac{ 1 }{ 16 }\int\limits \left( 2\cos ^2 \theta \right)d \theta=\frac{ 1 }{ 16 }\int\limits \left( 1+\cos 2\theta \right) d \theta =?$

17. anonymous

its going to be theta -sin2theta/2 but that would make the denominator for sin 32 and it is wrong @surhithayer

18. zepdrix

No, that sounds fine :) You just need your final answer in terms of $$\large\rm x$$, not $$\large\rm \theta$$. So you need to undo your substitution, perhaps with the use of a triangle.

19. anonymous

$\int\limits \cos 2\theta d \theta =\frac{ \sin 2\theta }{ 2}$

20. anonymous

$=\frac{ 1 }{ 2 }*\frac{ 2 \tan \theta }{ 1-\tan ^2 \theta }=\frac{ \tan \theta }{ 1-\tan ^2 \theta }$


text:
# natural log and trig function question

#### DeusAbscondus

##### Active member
when I differentiate:
$$ln4x+sin(x)$$
I get:
$$\frac{1}{x}+cos(x)$$
and Wolfgram agrees

But then when i test this by calculating indefinite integral, I get:
$$ln(x)+cos(x)$$
Which leaves me with three questions:
1. what happened to the 4?
2. why isn't it integrating back to (at least) ln(x)+sin(x)?
3. why doesn't wolfram add $+C$ to the end of an indefinite integral,
seemingly defying a principle over which I've had my knuckles wrapped severely (and liked it) ?

Thanks,

Deus Abscondus or:
"God has absconded from the scene .... again!"

Last edited:

#### MarkFL

Staff member
Hint: $\displaystyle \ln|4x|=\ln|x|+2\ln(2)$

The constant $\displaystyle 2\ln(2)$ gets lumped in with the constant of integration since it is just a constant itself.

I believe Wolfram states + constant on the end of indefinite integrals.

#### MarkFL

Staff member
...
You have differentiated $$\ln(4x)$$ incorrectly.
Perhaps he applied the chain rule and simplified...he does have the correct result.

#### Sudharaka

##### Well-known member
MHB Math Helper
when I differentiate:
$$ln4x+sin(x)$$
I get:
$$\frac{1}{x}+cos(x)$$
and Wolfgram agrees

But then when i test this by calculating indefinite integral, I get:
$$ln(x)+cos(x)$$
Which leaves me with three questions:
1. what happened to the 4?
2. why isn't it integrating back to (at least) ln(x)+sin(x)?
3. why doesn't wolfram add $+C$ to the end of an indefinite integral,
seemingly defying a principle over which I've had my knuckles wrapped severely (and liked it) ?

Thanks,

Deus Abscondus or:
"God has absconded from the scene .... again!"
Hi DeusAbscondus,

Sorry about the obvious error in my last post, I have deleted to avoid any confusion. >>Here<< is what Wolfram gives me. Note that there is the constant term and also the answer is $$\ln(x)+\sin(x)$$.

Kind Regards,
Sudharaka.

#### DeusAbscondus

##### Active member
Thanks Sudharaka,

Well that would be:
$$\frac{d}{dx}ln(4x)+sin(x)=4*\frac{1}{x}+cos(x)$$ I suppose

But then, when you integrate this: you get $$4ln(x)-sin(x)+C$$
don't you? Which is patently not the original $$f(x)=ln4x+sin(x)$$

#### Sudharaka

##### Well-known member
MHB Math Helper
Thanks Sudharaka,

Well that would be:
$$\frac{d}{dx}ln(4x)+sin(x)=4*\frac{1}{x}+cos(x)$$ I suppose

But then, when you integrate this: you get $$4ln(x)-sin(x)+C$$
don't you? Which is patently not the original $$f(x)=ln4x+sin(x)$$
I am sorry about this but the answer you have obtained after differentiating $$\ln(4x)+\sin(x)$$ in post #1 is correct and I was wrong in my post #2 and hence deleted it.

$\frac{d}{dx}ln(4x)+sin(x)=\frac{1}{x}+cos(x)$

as you have correctly stated in your original post. Refer post #4 and follow the link to see what Wolfram gives after integrating. Then look at Mark's post #2 to clarify more about what happens to the $$4$$ as you have asked in your original post. If you have any more questions please don't hesitate to ask.

#### DeusAbscondus

##### Active member
Hint: $\displaystyle \ln|4x|=\ln|x|+2\ln(2)$The constant $\displaystyle 2\ln(2)$ gets lumped in with the constant of integration since it is just a constant itself.I believe Wolfram states + constant on the end of indefinite integrals.
Forgive my obtuseness: but I still can't see why the integration seems to lose the constant 4.Though I understand and appreciate the nice:: $$\displaystyle \ln|4x|=\ln|x|+2\ln(2)$$Btw, remind me again: what does the command: \displaystyle do?

#### Sudharaka

##### Well-known member
MHB Math Helper
Forgive my obtuseness: but I still can't see why the integration seems to lose the constant 4.Though I understand and appreciate the nice:: $$\displaystyle \ln|4x|=\ln|x|+2\ln(2)$$
$\int\left(\frac{1}{x}+cos(x)\right)\,dx=\ln(x)+ \sin(x)+A$

where $$A$$ is the arbitrary constant.

As Mark had pointed out you can write,

$\ln(4x)=\ln(x)+2\ln(2)\Rightarrow \ln(x)=\ln(4x)-2\ln(2)$

Substitute this in the above equation and we get,

$\int\left(\frac{1}{x}+cos(x)\right)\,dx=\ln(4x)+ \sin(x)+(A-2\ln(2))$

Now $$A-2\ln(2)$$ is also an arbitrary constant and we label it as $$C$$.

$\int\left(\frac{1}{x}+cos(x)\right)\,dx=\ln(4x)+ \sin(x)+C$

So you see it is irrelevant whether you write $$\ln(x)+\sin(x)+A$$ or $$\ln(4x)+\sin(x)+C$$ because both answers are the same and one can be obtained from the other.

#### Sudharaka

##### Well-known member
MHB Math Helper
Btw, remind me again: what does the command: \displaystyle do?
It is a size command. See >>this<< thread for some uses of \displaystyle.

#### DeusAbscondus

##### Active member
$\int\left(\frac{1}{x}+cos(x)\right)\,dx=\ln(x)+ \sin(x)+A$

where $$A$$ is the arbitrary constant.

As Mark had pointed out you can write,

$\ln(4x)=\ln(x)+2\ln(2)\Rightarrow \ln(x)=\ln(4x)-2\ln(2)$

Substitute this in the above equation and we get,

$\int\left(\frac{1}{x}+cos(x)\right)\,dx=\ln(4x)+ \sin(x)+(A-2\ln(2))$

Now $$A-2\ln(2)$$ is also an arbitrary constant and we label it as $$C$$.

$\int\left(\frac{1}{x}+cos(x)\right)\,dx=\ln(4x)+ \sin(x)+C$

So you see it is irrelevant whether you write $$\ln(x)+\sin(x)+A$$ or $$\ln(4x)+\sin(x)+C$$ because both answers are the same and one can be obtained from the other.
I love it!
Thanks Sudharaka; now I can relax, take a break, go eat, and digest properly having cleared that up.
Deus Abs

#### Sudharaka

##### Well-known member
MHB Math Helper
I love it!
Thanks Sudharaka; now I can relax, take a break, go eat, and digest properly having cleared that up.
Deus Abs


text:
3 added 8 characters in body

The two most elementary ways to prove an N x N matrix's determinant = 0 are:

A) Find a row or column that equals the 0 vector.

B) Find a linear combination of rows or columns that equals the 0 vector.

A can be generalized to

C) Find a j x k submatrix, with j + k > N, all of whose entries are 0.

My minor question is: Is C a named theorem that one can easily reference?

My major question is: Are there are other canonical ways of proving a determinant = 0?

The context is that I'm trying to solve the generalized form of what was, as stated, a very easy Putnam Exam problem, and I last took a linear algebra class in 1974.

In response to comments below, let me say: - Thanks! - This isn't about computational efficiency. More later as I work through them- Frobenius-Koenig looks very helpful.

2 added 148 characters in body

The two most elementary ways to prove an N x N matrix's determinant = 0 are:

A) Find a row or column that equals the 0 vector.

B) Find a linear combination of rows or columns that equals the 0 vector.

A can be generalized to

C) Find a j x k submatrix, with j + k > N, all of whose entries are 0.

My minor question is: Is C a named theorem that one can easily reference?

My major question is: Are there are other canonical ways of proving a determinant = 0?

The context is that I'm trying to solve the generalized form of what was, as stated, a very easy Putnam Exam problem, and I last took a linear algebra class in 1974.

In response to comments below, let me say: - Thanks! - This isn't about computational efficiency. More later as I work through them.

1

# Proving a determinant = 0

The two most elementary ways to prove an N x N matrix's determinant = 0 are:

A) Find a row or column that equals the 0 vector.

B) Find a linear combination of rows or columns that equals the 0 vector.

A can be generalized to

C) Find a j x k submatrix, with j + k > N, all of whose entries are 0.

My minor question is: Is C a named theorem that one can easily reference?

My major question is: Are there are other canonical ways of proving a determinant = 0?

The context is that I'm trying to solve the generalized form of what was, as stated, a very easy Putnam Exam problem, and I last took a linear algebra class in 1974.


text:
# What are the frequencies of the fundamental and first two overtones?

1. Apr 12, 2009

### jlwood13

1. The problem statement, all variables and given/known data
A guitar string is 90.0 cm long and has a mass of 3.17 g. From the bridge to the support post is 60.0 cm and the string is under a tension of 506 N. What are the frequencies of the fundamental and first two overtones? (f1,f2,f3)

2. Relevant equations
v=sqrt(FT/m/l)
v=$$\lambda*f$$

3. The attempt at a solution
I checked in my text and found that for f1, l=1/2$$\lambda$$1; for f2, l=$$\lambda$$2; and for f3, l=3/2$$\lambda$$3. I tried using 60.0 cm (and converted to meters) and 90.0 cm (converted to meters) and 30.0 cm (converted to meters) for l, but nothing worked. I also converted 3.17 g into kilograms so that's not an issue. I'm not sure what to do now..

2. Apr 13, 2009

### Ofey

The fundamental tone is heard when the lenght of the guitar sting equals half the wavelenght (corresponding to the fundamental tone).

Due to the construction of the guitar, you will get a node in both ends, and the distance between 2 adjacent nodes is lamda/2.

EDIT:

My error, I didn't read the assignment carefully. You have to use 60 cm and not 90 cm.

Last edited: Apr 13, 2009
3. Apr 13, 2009

### Chewy0087

Yeah for the fundamental 60cm is only 1/2 of it. - Wavelegnth for the fundemental = 120cm.

I'm struggling to see what you've done wrong, I think it might just be a case on number crunching wrong. Bear in mind the wavelegnth figure you'd use is 2x 60cm, however the mass per unit legnth you'd use is 90cm.... What do you mean "nothing worked" what sort of answers were you getting? Bear in mind that if it's 506N the speed would have to be damn fast :P, I get a very high speed

edit; welcome to pforums ;p

4. Apr 13, 2009

### Ofey

I am not totally sure on this, but since it states that the whole string has a mass of 3.17 gram, doesn't that mean that the 60 cm has a smaller mass? If the answer is wrong it might be because of the wrong value on mass.

EDIT:

I didn't notice that this was exactly what Chewy said, I am sorry.

Last edited: Apr 13, 2009
5. Apr 13, 2009

### Chewy0087

That makes no difference, you're trying to work out the mass per unit legnth, since the whole string weighs 3.17 grams, & the whole string is 60cm long your calculation must be

0.00317 / 0.9 to work out m0, but again, what sort of answers are you churning out?

Last edited: Apr 13, 2009
6. Apr 13, 2009

### Ofey

Isn't it 0.00317/0.9 since it says that the whole string has the mass 3.17 grams?

7. Apr 13, 2009

### Chewy0087

Yah, that's what i meant sorry

8. Apr 13, 2009

### jlwood13

When dividing my the unit mass I used .6 instead of .9. It was an error in number crunching. Thanks for your help! Sorry that I didn't respond sooner. Also, thanks for the welcome!


text:
Evaluate: 10x-3(x^2-16)=0

Expression: $10x-3\left( {x}^{2}-16 \right)=0$

Distribute $-3$ through the parentheses

$10x-3{x}^{2}+48=0$

Move the constant to the right-hand side and change its sign

$10x-3{x}^{2}=-48$

Use the commutative property to reorder the terms

$-3{x}^{2}+10x=-48$

Divide both sides of the equation by $-3$

${x}^{2}-\frac{ 10 }{ 3 }x=16$

To complete the square, the same value needs to be added to both sides

${x}^{2}-\frac{ 10 }{ 3 }x+?=16+?$

To complete the square ${x}^{2}-\frac{ 10 }{ 3 }x+\frac{ 25 }{ 9 }={\left( x-\frac{ 5 }{ 3 } \right)}^{2}$ add $\frac{ 25 }{ 9 }$ to the expression

${x}^{2}-\frac{ 10 }{ 3 }x+\frac{ 25 }{ 9 }=16+?$

Since $\frac{ 25 }{ 9 }$ was added to the left-hand side, also add $\frac{ 25 }{ 9 }$ to the right-hand side

${x}^{2}-\frac{ 10 }{ 3 }x+\frac{ 25 }{ 9 }=16+\frac{ 25 }{ 9 }$

Use ${a}^{2}-2ab+{b}^{2}={\left( a-b \right)}^{2}$ to factor the expression

${\left( x-\frac{ 5 }{ 3 } \right)}^{2}=16+\frac{ 25 }{ 9 }$

Calculate the sum

${\left( x-\frac{ 5 }{ 3 } \right)}^{2}=\frac{ 169 }{ 9 }$

Solve the equation for $x$

$\begin{array} { l }x=-\frac{ 8 }{ 3 },\\x=6\end{array}$

The equation has $2$ solutions

\begin{align*}&\begin{array} { l }x_1=-\frac{ 8 }{ 3 },& x_2=6\end{array} \\&\begin{array} { l }x_1\approx-2.66667,& x_2=6\end{array}\end{align*}

Random Posts
Random Articles