diff --git a/doc/pub/DimRed/html/._DimRed-bs000.html b/doc/pub/DimRed/html/._DimRed-bs000.html index 706f14ce8..5c37a9358 100644 --- a/doc/pub/DimRed/html/._DimRed-bs000.html +++ b/doc/pub/DimRed/html/._DimRed-bs000.html @@ -59,14 +59,19 @@ Automatically generated HTML file from DocOnce source 2, None, '___sec4'), - ('Principal Component Analysis', 2, None, '___sec5'), - ('PCA and scikit-learn', 2, None, '___sec6'), - ('More on the PCA', 2, None, '___sec7'), - ('Incremental PCA', 2, None, '___sec8'), - ('Randomized PCA', 2, None, '___sec9'), - ('Kernel PCA', 2, None, '___sec10'), - ('LLE', 2, None, '___sec11'), - ('Other techniques', 2, None, '___sec12')]} + ('Why should we think of reducing the dimensionality', + 2, + None, + '___sec5'), + ('Getting started with PCA', 2, None, '___sec6'), + ('Principal Component Analysis', 2, None, '___sec7'), + ('PCA and scikit-learn', 2, None, '___sec8'), + ('More on the PCA', 2, None, '___sec9'), + ('Incremental PCA', 2, None, '___sec10'), + ('Randomized PCA', 2, None, '___sec11'), + ('Kernel PCA', 2, None, '___sec12'), + ('LLE', 2, None, '___sec13'), + ('Other techniques', 2, None, '___sec14')]} end of tocinfo -->
@@ -109,14 +114,16 @@ MathJax.Hub.Config({-
@@ -175,7 +182,7 @@ MathJax.Hub.Config({
@@ -199,6 +205,8 @@ svm.fit(X_train_scaled, y_train)
+ +
@@ -143,23 +154,6 @@ MathJax.Hub.Config({ from sklearn.linear_model import LogisticRegression cancer = load_breast_cancer() -fig, axes = plt.subplots(15,2,figsize=(10,20)) -male = cancer.data[cancer.target == 0] -bene = cancer.data[cancer.target == 1] -ax = axes.ravel() - -for i in range(30): - _, bins = np.histogram(cancer.data[:,i], bins =50) - ax[i].hist(male[:,i], bins = bins, alpha = 0.5) - ax[i].hist(bene[:,i], bins = bins, alpha = 0.5) - ax[i].set_title(cancer.feature_names[i]) - ax[i].set_yticks(()) -ax[0].set_xlabel("Feature magnitude") -ax[0].set_ylabel("Frequency") -ax[0].legend(["Male", "Bene"], loc ="best") -fig.tight_layout() -plt.show() - # Set up training data X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0) # Perform Logistic Regression (replace with own code) @@ -176,13 +170,6 @@ X_test_scaled = scaler.fit(X_train_scaled, y_train) #svm.fit(X_train_scaled, y_train) print("Test set accuracy scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test))) - -# Now add PCA -from sklearn.decomposition import PCA -pca = PCA(n_components = 2) -pca.fit(X_train_scaled) - -X_pca = pca.transform(X_train_scaled)
@@ -203,6 +190,9 @@ X_pca = pca.12
-Principal Component Analysis (PCA) is by far the most popular dimensionality reduction algorithm.
-First it identifies the hyperplane that lies closest to the data, and then it projects the data onto it.
+
-The following Python code uses NumPy’s svd() function to obtain all the principal components of the
-training set, then extracts the first two principal components
-
-PCA assumes that the dataset is centered around the origin. Scikit-Learn’s PCA classes take care of centering
-the data for you. However, if you implement PCA yourself (as in the preceding example), or if you use other libraries, don’t
-forget to center the data first.
+
-Once you have identified all the principal components, you can reduce the dimensionality of the dataset
-down to \( d \) dimensions by projecting it onto the hyperplane defined by the first \( d \) principal components.
-Selecting this hyperplane ensures that the projection will preserve as much variance as possible.
-
+fig, axes = plt.subplots(15,2,figsize=(10,20))
+male = cancer.data[cancer.target == 0]
+bene = cancer.data[cancer.target == 1]
+ax = axes.ravel()
-
-
@@ -184,6 +203,8 @@ X2D = X_centered12
-Scikit-Learn’s PCA class implements PCA using SVD decomposition just like we did before. The
-following code applies PCA to reduce the dimensionality of the dataset down to two dimensions (note
-that it automatically takes care of centering the data):
-
-After fitting the PCA transformer to the dataset, you can access the principal components using the
-components variable (note that it contains the PCs as horizontal vectors, so, for example, the first
-principal component is equal to
-
+pca.fit(X_train_scaled)
-
-
-Another very useful piece of information is the explained variance ratio of each principal component,
-available via the \( explained\_variance\_ratio \) variable. It indicates the proportion of the dataset’s
-variance that lies along the axis of each principal component.
-More material to come here.
-
@@ -179,6 +170,8 @@ More material to come here.
+Principal Component Analysis (PCA) is by far the most popular dimensionality reduction algorithm.
+First it identifies the hyperplane that lies closest to the data, and then it projects the data onto it.
+
+
+The following Python code uses NumPy’s svd() function to obtain all the principal components of the
+training set, then extracts the first two principal components
-
-You could then set \( n\_components=d \) and run PCA again. However, there is a much better option: instead
-of specifying the number of principal components you want to preserve, you can set \( n\_components \) to be
-a float between 0.0 and 1.0, indicating the ratio of variance you wish to preserve:
+PCA assumes that the dataset is centered around the origin. Scikit-Learn’s PCA classes take care of centering
+the data for you. However, if you implement PCA yourself (as in the preceding example), or if you use other libraries, don’t
+forget to center the data first.
+
+
+Once you have identified all the principal components, you can reduce the dimensionality of the dataset
+down to \( d \) dimensions by projecting it onto the hyperplane defined by the first \( d \) principal components.
+Selecting this hyperplane ensures that the projection will preserve as much variance as possible.
-
@@ -176,6 +191,8 @@ X_reduced = pca
+Scikit-Learn’s PCA class implements PCA using SVD decomposition just like we did before. The
+following code applies PCA to reduce the dimensionality of the dataset down to two dimensions (note
+that it automatically takes care of centering the data):
+
+
+
+
+After fitting the PCA transformer to the dataset, you can access the principal components using the
+components variable (note that it contains the PCs as horizontal vectors, so, for example, the first
+principal component is equal to
+
+
+
+
+Another very useful piece of information is the explained variance ratio of each principal component,
+available via the \( explained\_variance\_ratio \) variable. It indicates the proportion of the dataset’s
+variance that lies along the axis of each principal component.
+More material to come here.
@@ -158,6 +186,8 @@ instances arrive).
-
@@ -175,7 +182,7 @@ MathJax.Hub.Config({
@@ -328,7 +328,6 @@ svm.fit(X_train, y_train)
print("Test set accuracy: {:.2f}".format(svm.score(X_test,y_test)))
from sklearn.preprocessing import MinMaxScaler, StandardScaler
-
scaler = MinMaxScaler()
scaler.fit(X_train)
X_train_scaled = scaler.transform(X_train)
@@ -342,7 +341,7 @@ X_test_scaled = scaler.transform(X_test)
svm.fit(X_train_scaled, y_train)
-print("Test set accuracy scaled data: {:.2f}".format(svm.score(X_test_scaled,y_test)))
+print("Test set accuracy scaled data with Min-Max scaling: {:.2f}".format(svm.score(X_test_scaled,y_test)))
scaler = StandardScaler()
scaler.fit(X_train)
@@ -350,13 +349,50 @@ X_train_scaled = scaler.transform(X_train)
X_test_scaled = scaler.transform(X_test)
svm.fit(X_train_scaled, y_train)
-print("Test set accuracy scaled data: {:.2f}".format(svm.score(X_test_scaled,y_test)))
+print("Test set accuracy scaled data with Standar Scaler: {:.2f}".format(svm.score(X_test_scaled,y_test)))
+
+
+
+
+
+
@@ -398,10 +434,18 @@ scaler.fit(X_train)
X_train_scaled = scaler.transform(X_train)
X_test_scaled = scaler.transform(X_test)
logreg.fit(X_train_scaled, y_train)
-#svm.fit(X_train_scaled, y_train)
print("Test set accuracy scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
+
+
+
+
@@ -449,7 +493,7 @@ X2D = X_centered.dot(W2)
Scikit-Learn’s PCA class implements PCA using SVD decomposition just like we did before. The
@@ -480,7 +524,7 @@ More material to come here.
Scikit-Learn offers yet another option to perform PCA, called Randomized PCA. This is a stochastic
@@ -533,7 +577,7 @@ previous algorithms when \( d \) is much smaller than \( n \).
@@ -559,7 +603,7 @@ X_reduced = rbf_pca.fit_transform(X)
Locally Linear Embedding (LLE) is another very powerful nonlinear dimensionality reduction
@@ -571,7 +615,7 @@ these local relationships are best preserved (more details shortly).
There are many other dimensionality reduction techniques, several of which are available in Scikit-Learn.
diff --git a/doc/pub/DimRed/html/DimRed-solarized.html b/doc/pub/DimRed/html/DimRed-solarized.html
index f18a7b72b..5bb7b5861 100644
--- a/doc/pub/DimRed/html/DimRed-solarized.html
+++ b/doc/pub/DimRed/html/DimRed-solarized.html
@@ -79,14 +79,19 @@ div { text-align: justify; text-justify: inter-word; }
2,
None,
'___sec4'),
- ('Principal Component Analysis', 2, None, '___sec5'),
- ('PCA and scikit-learn', 2, None, '___sec6'),
- ('More on the PCA', 2, None, '___sec7'),
- ('Incremental PCA', 2, None, '___sec8'),
- ('Randomized PCA', 2, None, '___sec9'),
- ('Kernel PCA', 2, None, '___sec10'),
- ('LLE', 2, None, '___sec11'),
- ('Other techniques', 2, None, '___sec12')]}
+ ('Why should we think of reducing the dimensionality',
+ 2,
+ None,
+ '___sec5'),
+ ('Getting started with PCA', 2, None, '___sec6'),
+ ('Principal Component Analysis', 2, None, '___sec7'),
+ ('PCA and scikit-learn', 2, None, '___sec8'),
+ ('More on the PCA', 2, None, '___sec9'),
+ ('Incremental PCA', 2, None, '___sec10'),
+ ('Randomized PCA', 2, None, '___sec11'),
+ ('Kernel PCA', 2, None, '___sec12'),
+ ('LLE', 2, None, '___sec13'),
+ ('Other techniques', 2, None, '___sec14')]}
end of tocinfo -->
-
+
+
+
+
+
+
+
@@ -376,10 +416,17 @@ scaler.fit(X_train)
X_train_scaled = scaler.transform(X_train)
X_test_scaled = scaler.transform(X_test)
logreg.fit(X_train_scaled, y_train)
-#svm.fit(X_train_scaled, y_train)
print("Test set accuracy scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
+
+
+
+
+
@@ -425,7 +472,7 @@ X2D = X_centered.dot(W2)
-
Scikit-Learn’s PCA class implements PCA using SVD decomposition just like we did before. The
@@ -456,7 +503,7 @@ More material to come here.
Scikit-Learn offers yet another option to perform PCA, called Randomized PCA. This is a stochastic
@@ -509,7 +556,7 @@ previous algorithms when \( d \) is much smaller than \( n \).
@@ -538,7 +585,7 @@ X_reduced = rbf_pca.fit_transform(X)
Locally Linear Embedding (LLE) is another very powerful nonlinear dimensionality reduction
@@ -550,7 +597,7 @@ these local relationships are best preserved (more details shortly).
There are many other dimensionality reduction techniques, several of which are available in Scikit-Learn.
diff --git a/doc/pub/DimRed/html/DimRed.html b/doc/pub/DimRed/html/DimRed.html
index b339bc54e..7bfd42be7 100644
--- a/doc/pub/DimRed/html/DimRed.html
+++ b/doc/pub/DimRed/html/DimRed.html
@@ -84,14 +84,19 @@ div { text-align: justify; text-justify: inter-word; }
2,
None,
'___sec4'),
- ('Principal Component Analysis', 2, None, '___sec5'),
- ('PCA and scikit-learn', 2, None, '___sec6'),
- ('More on the PCA', 2, None, '___sec7'),
- ('Incremental PCA', 2, None, '___sec8'),
- ('Randomized PCA', 2, None, '___sec9'),
- ('Kernel PCA', 2, None, '___sec10'),
- ('LLE', 2, None, '___sec11'),
- ('Other techniques', 2, None, '___sec12')]}
+ ('Why should we think of reducing the dimensionality',
+ 2,
+ None,
+ '___sec5'),
+ ('Getting started with PCA', 2, None, '___sec6'),
+ ('Principal Component Analysis', 2, None, '___sec7'),
+ ('PCA and scikit-learn', 2, None, '___sec8'),
+ ('More on the PCA', 2, None, '___sec9'),
+ ('Incremental PCA', 2, None, '___sec10'),
+ ('Randomized PCA', 2, None, '___sec11'),
+ ('Kernel PCA', 2, None, '___sec12'),
+ ('LLE', 2, None, '___sec13'),
+ ('Other techniques', 2, None, '___sec14')]}
end of tocinfo -->
-
+
+
+
+
+
+
+
@@ -381,10 +421,17 @@ scaler.fit(X_train)
X_train_scaled = scaler.transform(X_train)
X_test_scaled = scaler.transform(X_test)
logreg.fit(X_train_scaled, y_train)
-#svm.fit(X_train_scaled, y_train)
print("Test set accuracy scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
+
+
+
+
+
@@ -430,7 +477,7 @@ X2D = X_centered
-
Scikit-Learn’s PCA class implements PCA using SVD decomposition just like we did before. The
@@ -461,7 +508,7 @@ More material to come here.
Scikit-Learn offers yet another option to perform PCA, called Randomized PCA. This is a stochastic
@@ -514,7 +561,7 @@ previous algorithms when \( d \) is much smaller than \( n \).
@@ -543,7 +590,7 @@ X_reduced = rbf_pcaLLE
+
Locally Linear Embedding (LLE) is another very powerful nonlinear dimensionality reduction
@@ -555,7 +602,7 @@ these local relationships are best preserved (more details shortly).
There are many other dimensionality reduction techniques, several of which are available in Scikit-Learn.
diff --git a/doc/pub/DimRed/ipynb/DimRed.ipynb b/doc/pub/DimRed/ipynb/DimRed.ipynb
index eec995584..9f8d03afc 100644
--- a/doc/pub/DimRed/ipynb/DimRed.ipynb
+++ b/doc/pub/DimRed/ipynb/DimRed.ipynb
@@ -10,7 +10,7 @@
" \n",
"**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n",
"\n",
- "Date: **Oct 14, 2019**\n",
+ "Date: **Oct 15, 2019**\n",
"\n",
"Copyright 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n",
"\n",
@@ -187,7 +187,6 @@
"print(\"Test set accuracy: {:.2f}\".format(svm.score(X_test,y_test)))\n",
"\n",
"from sklearn.preprocessing import MinMaxScaler, StandardScaler\n",
- "\n",
"scaler = MinMaxScaler()\n",
"scaler.fit(X_train)\n",
"X_train_scaled = scaler.transform(X_train)\n",
@@ -201,7 +200,7 @@
"\n",
"\n",
"svm.fit(X_train_scaled, y_train)\n",
- "print(\"Test set accuracy scaled data: {:.2f}\".format(svm.score(X_test_scaled,y_test)))\n",
+ "print(\"Test set accuracy scaled data with Min-Max scaling: {:.2f}\".format(svm.score(X_test_scaled,y_test)))\n",
"\n",
"scaler = StandardScaler()\n",
"scaler.fit(X_train)\n",
@@ -209,14 +208,16 @@
"X_test_scaled = scaler.transform(X_test)\n",
"\n",
"svm.fit(X_train_scaled, y_train)\n",
- "print(\"Test set accuracy scaled data: {:.2f}\".format(svm.score(X_test_scaled,y_test)))"
+ "print(\"Test set accuracy scaled data with Standar Scaler: {:.2f}\".format(svm.score(X_test_scaled,y_test)))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "## More on Cancer Data, now with Logistic Regression"
+ "## More on Cancer Data, now with Logistic Regression\n",
+ "\n",
+ ""
]
},
{
@@ -226,6 +227,46 @@
"collapsed": false
},
"outputs": [],
+ "source": [
+ "import matplotlib.pyplot as plt\n",
+ "import numpy as np\n",
+ "from sklearn.model_selection import train_test_split \n",
+ "from sklearn.datasets import load_breast_cancer\n",
+ "from sklearn.linear_model import LogisticRegression\n",
+ "cancer = load_breast_cancer()\n",
+ "\n",
+ "# Set up training data\n",
+ "X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)\n",
+ "# Perform Logistic Regression (replace with own code) \n",
+ "logreg = LogisticRegression()\n",
+ "logreg.fit(X_train, y_train)\n",
+ "print(\"Test set accuracy: {:.2f}\".format(logreg.score(X_test,y_test)))\n",
+ "\n",
+ "# Scale data\n",
+ "from sklearn.preprocessing import StandardScaler\n",
+ "scaler = StandardScaler()\n",
+ "scaler.fit(X_train)\n",
+ "X_train_scaled = scaler.transform(X_train)\n",
+ "X_test_scaled = scaler.transform(X_test)\n",
+ "logreg.fit(X_train_scaled, y_train)\n",
+ "#svm.fit(X_train_scaled, y_train)\n",
+ "print(\"Test set accuracy scaled data: {:.2f}\".format(logreg.score(X_test_scaled,y_test)))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Why should we think of reducing the dimensionality"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
"source": [
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
@@ -265,9 +306,24 @@
"X_train_scaled = scaler.transform(X_train)\n",
"X_test_scaled = scaler.transform(X_test)\n",
"logreg.fit(X_train_scaled, y_train)\n",
- "#svm.fit(X_train_scaled, y_train)\n",
- "print(\"Test set accuracy scaled data: {:.2f}\".format(logreg.score(X_test_scaled,y_test)))\n",
- "\n",
+ "print(\"Test set accuracy scaled data: {:.2f}\".format(logreg.score(X_test_scaled,y_test)))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Getting started with PCA"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
"# Now add PCA\n",
"from sklearn.decomposition import PCA\n",
"pca = PCA(n_components = 2)\n",
@@ -290,7 +346,7 @@
},
{
"cell_type": "code",
- "execution_count": 4,
+ "execution_count": 6,
"metadata": {
"collapsed": false
},
@@ -317,7 +373,7 @@
},
{
"cell_type": "code",
- "execution_count": 5,
+ "execution_count": 7,
"metadata": {
"collapsed": false
},
@@ -341,7 +397,7 @@
},
{
"cell_type": "code",
- "execution_count": 6,
+ "execution_count": 8,
"metadata": {
"collapsed": false
},
@@ -363,7 +419,7 @@
},
{
"cell_type": "code",
- "execution_count": 7,
+ "execution_count": 9,
"metadata": {
"collapsed": false
},
@@ -392,7 +448,7 @@
},
{
"cell_type": "code",
- "execution_count": 8,
+ "execution_count": 10,
"metadata": {
"collapsed": false
},
@@ -415,7 +471,7 @@
},
{
"cell_type": "code",
- "execution_count": 9,
+ "execution_count": 11,
"metadata": {
"collapsed": false
},
@@ -461,7 +517,7 @@
},
{
"cell_type": "code",
- "execution_count": 10,
+ "execution_count": 12,
"metadata": {
"collapsed": false
},
diff --git a/doc/pub/DimRed/ipynb/ipynb-DimRed-src.tar.gz b/doc/pub/DimRed/ipynb/ipynb-DimRed-src.tar.gz
index 9db24fa25..0fc79a31e 100644
Binary files a/doc/pub/DimRed/ipynb/ipynb-DimRed-src.tar.gz and b/doc/pub/DimRed/ipynb/ipynb-DimRed-src.tar.gz differ
diff --git a/doc/pub/DimRed/pdf/DimRed-minted.pdf b/doc/pub/DimRed/pdf/DimRed-minted.pdf
index 0beed3110..c8dc1ee66 100644
Binary files a/doc/pub/DimRed/pdf/DimRed-minted.pdf and b/doc/pub/DimRed/pdf/DimRed-minted.pdf differ
diff --git a/doc/src/DimRed/DimRed.do.txt b/doc/src/DimRed/DimRed.do.txt
index 6f5848873..00a467753 100644
--- a/doc/src/DimRed/DimRed.do.txt
+++ b/doc/src/DimRed/DimRed.do.txt
@@ -161,7 +161,6 @@ svm.fit(X_train, y_train)
print("Test set accuracy: {:.2f}".format(svm.score(X_test,y_test)))
from sklearn.preprocessing import MinMaxScaler, StandardScaler
-
scaler = MinMaxScaler()
scaler.fit(X_train)
X_train_scaled = scaler.transform(X_train)
@@ -175,7 +174,7 @@ print("Feature max values before scaling:\n {}".format(X_train_scaled.max(axis=0
svm.fit(X_train_scaled, y_train)
-print("Test set accuracy scaled data: {:.2f}".format(svm.score(X_test_scaled,y_test)))
+print("Test set accuracy scaled data with Min-Max scaling: {:.2f}".format(svm.score(X_test_scaled,y_test)))
scaler = StandardScaler()
scaler.fit(X_train)
@@ -183,13 +182,48 @@ X_train_scaled = scaler.transform(X_train)
X_test_scaled = scaler.transform(X_test)
svm.fit(X_train_scaled, y_train)
-print("Test set accuracy scaled data: {:.2f}".format(svm.score(X_test_scaled,y_test)))
+print("Test set accuracy scaled data with Standar Scaler: {:.2f}".format(svm.score(X_test_scaled,y_test)))
+
+!ec
+
+!split
+===== More on Cancer Data, now with Logistic Regression =====
+
+# rewrite with own Logistic Regression code
+
+!bc pycod
+import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+from sklearn.datasets import load_breast_cancer
+from sklearn.linear_model import LogisticRegression
+cancer = load_breast_cancer()
+
+# Set up training data
+X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
+# Perform Logistic Regression (replace with own code)
+logreg = LogisticRegression()
+logreg.fit(X_train, y_train)
+print("Test set accuracy: {:.2f}".format(logreg.score(X_test,y_test)))
+
+# Scale data
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+logreg.fit(X_train_scaled, y_train)
+#svm.fit(X_train_scaled, y_train)
+print("Test set accuracy scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
!ec
+
+
!split
-===== More on Cancer Data, now with Logistic Regression =====
+===== Why should we think of reducing the dimensionality =====
+
!bc pycod
import matplotlib.pyplot as plt
import numpy as np
@@ -229,19 +263,28 @@ scaler.fit(X_train)
X_train_scaled = scaler.transform(X_train)
X_test_scaled = scaler.transform(X_test)
logreg.fit(X_train_scaled, y_train)
-#svm.fit(X_train_scaled, y_train)
print("Test set accuracy scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
+
+
+!ec
+
+
+
+!split
+===== Getting started with PCA =====
+
+!bc pycod
# Now add PCA
from sklearn.decomposition import PCA
pca = PCA(n_components = 2)
pca.fit(X_train_scaled)
X_pca = pca.transform(X_train_scaled)
-
-
!ec
+
+
!split
===== Principal Component Analysis =====
!bblock
diff --git a/doc/src/DimRed/cancerownlogreg.py b/doc/src/DimRed/cancerownlogreg.py
new file mode 100644
index 000000000..45f03f36a
--- /dev/null
+++ b/doc/src/DimRed/cancerownlogreg.py
@@ -0,0 +1,40 @@
+import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+from sklearn.datasets import load_breast_cancer
+from sklearn.linear_model import LogisticRegression
+cancer = load_breast_cancer()
+
+fig, axes = plt.subplots(15,2,figsize=(10,20))
+malignant = cancer.data[cancer.target == 0]
+benign = cancer.data[cancer.target == 1]
+ax = axes.ravel()
+
+for i in range(30):
+ _, bins = np.histogram(cancer.data[:,i], bins =50)
+ ax[i].hist(malignant[:,i], bins = bins, alpha = 0.5)
+ ax[i].hist(benign[:,i], bins = bins, alpha = 0.5)
+ ax[i].set_title(cancer.feature_names[i])
+ ax[i].set_yticks(())
+ax[0].set_xlabel("Feature magnitude")
+ax[0].set_ylabel("Frequency")
+ax[0].legend(["Malignant", "Benign"], loc ="best")
+fig.tight_layout()
+plt.show()
+
+X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
+print(X_train.shape)
+print(X_test.shape)
+
+logreg = LogisticRegression()
+logreg.fit(X_train, y_train)
+print("Test set accuracy from Logistic Regression: {:.2f}".format(logreg.score(X_test,y_test)))
+
+from sklearn.preprocessing import MinMaxScaler, StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+
+logreg.fit(X_train_scaled, y_train)
+print("Test set accuracy scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
Principal Component Analysis
-Why should we think of reducing the dimensionality
-X_centered = X - X.mean(axis=0)
-U, s, V = np.linalg.svd(X_centered)
-c1 = V.T[:, 0]
-c2 = V.T[:, 1]
-
import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+from sklearn.datasets import load_breast_cancer
+from sklearn.linear_model import LogisticRegression
+cancer = load_breast_cancer()
-
W2 = V.T[:, :2]
-X2D = X_centered.dot(W2)
+for i in range(30):
+ _, bins = np.histogram(cancer.data[:,i], bins =50)
+ ax[i].hist(male[:,i], bins = bins, alpha = 0.5)
+ ax[i].hist(bene[:,i], bins = bins, alpha = 0.5)
+ ax[i].set_title(cancer.feature_names[i])
+ ax[i].set_yticks(())
+ax[0].set_xlabel("Feature magnitude")
+ax[0].set_ylabel("Frequency")
+ax[0].legend(["Male", "Bene"], loc ="best")
+fig.tight_layout()
+plt.show()
+
+# Set up training data
+X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
+# Perform Logistic Regression (replace with own code)
+logreg = LogisticRegression()
+logreg.fit(X_train, y_train)
+print("Test set accuracy: {:.2f}".format(logreg.score(X_test,y_test)))
+
+# Scale data
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+logreg.fit(X_train_scaled, y_train)
+print("Test set accuracy scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
PCA and scikit-learn
+Getting started with PCA
-from sklearn.decomposition import PCA
+
# Now add PCA
+from sklearn.decomposition import PCA
pca = PCA(n_components = 2)
-X2D = pca.fit_transform(X)
-
pca.components_.T[:, 0]).
+X_pca = pca.transform(X_train_scaled)
More on the PCA
-Instead of arbitrarily choosing the number of dimensions to reduce down to, it is generally preferable to
-choose the number of dimensions that add up to a sufficiently large portion of the variance (e.g., 95%).
-Unless, of course, you are reducing dimensionality for data visualization — in that case you will
-generally want to reduce the dimensionality down to 2 or 3.
-The following code computes PCA without reducing dimensionality, then computes the minimum number
-of dimensions required to preserve 95% of the training set’s variance:
+Principal Component Analysis
+pca = PCA()
-pca.fit(X)
-cumsum = np.cumsum(pca.explained_variance_ratio_)
-d = np.argmax(cumsum >= 0.95) + 1
+
X_centered = X - X.mean(axis=0)
+U, s, V = np.linalg.svd(X_centered)
+c1 = V.T[:, 0]
+c2 = V.T[:, 1]
pca = PCA(n_components=0.95)
-X_reduced = pca.fit_transform(X)
+
W2 = V.T[:, :2]
+X2D = X_centered.dot(W2)
Incremental PCA
-One problem with the preceding implementation of PCA is that it requires the whole training set to fit in
-memory in order for the SVD algorithm to run. Fortunately, Incremental PCA (IPCA) algorithms have
-been developed: you can split the training set into mini-batches and feed an IPCA algorithm one minibatch
-at a time. This is useful for large training sets, and also to apply PCA online (i.e., on the fly, as new
-instances arrive).
+PCA and scikit-learn
+
+from sklearn.decomposition import PCA
+pca = PCA(n_components = 2)
+X2D = pca.fit_transform(X)
+
pca.components_.T[:, 0]).
+
Oct 14, 2019
Oct 15, 2019
-Oct 14, 2019
Oct 15, 2019
More on Cancer Data, now with Logistic Regression
+
+import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+from sklearn.datasets import load_breast_cancer
+from sklearn.linear_model import LogisticRegression
+cancer = load_breast_cancer()
+
+# Set up training data
+X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
+# Perform Logistic Regression (replace with own code)
+logreg = LogisticRegression()
+logreg.fit(X_train, y_train)
+print("Test set accuracy: {:.2f}".format(logreg.score(X_test,y_test)))
+
+# Scale data
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+logreg.fit(X_train_scaled, y_train)
+#svm.fit(X_train_scaled, y_train)
+print("Test set accuracy scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
+
Why should we think of reducing the dimensionality
+
Getting started with PCA
+
+# Now add PCA
from sklearn.decomposition import PCA
pca = PCA(n_components = 2)
pca.fit(X_train_scaled)
@@ -412,7 +456,7 @@ X_pca = pca.transform(X_train_scaled)
Principal Component Analysis
+Principal Component Analysis
PCA and scikit-learn
+PCA and scikit-learn
More on the PCA
+More on the PCA
Instead of arbitrarily choosing the number of dimensions to reduce down to, it is generally preferable to
choose the number of dimensions that add up to a sufficiently large portion of the variance (e.g., 95%).
Unless, of course, you are reducing dimensionality for data visualization — in that case you will
@@ -509,7 +553,7 @@ X_reduced = pca.fit_transform(X)
Incremental PCA
+Incremental PCA
One problem with the preceding implementation of PCA is that it requires the whole training set to fit in
memory in order for the SVD algorithm to run. Fortunately, Incremental PCA (IPCA) algorithms have
been developed: you can split the training set into mini-batches and feed an IPCA algorithm one minibatch
@@ -519,7 +563,7 @@ instances arrive).
Randomized PCA
+Randomized PCA
Kernel PCA
+Kernel PCA
LLE
+LLE
Other techniques
+Other techniques
Oct 14, 2019
Oct 15, 2019
@@ -307,7 +312,6 @@ svm.fit(X_train, y_train)
print("Test set accuracy: {:.2f}".format(svm.score(X_test,y_test)))
from sklearn.preprocessing import MinMaxScaler, StandardScaler
-
scaler = MinMaxScaler()
scaler.fit(X_train)
X_train_scaled = scaler.transform(X_train)
@@ -321,7 +325,7 @@ X_test_scaled = scaler.transform(X_test)
svm.fit(X_train_scaled, y_train)
-print("Test set accuracy scaled data: {:.2f}".format(svm.score(X_test_scaled,y_test)))
+print("Test set accuracy scaled data with Min-Max scaling: {:.2f}".format(svm.score(X_test_scaled,y_test)))
scaler = StandardScaler()
scaler.fit(X_train)
@@ -329,12 +333,48 @@ X_train_scaled = scaler.transform(X_train)
X_test_scaled = scaler.transform(X_test)
svm.fit(X_train_scaled, y_train)
-print("Test set accuracy scaled data: {:.2f}".format(svm.score(X_test_scaled,y_test)))
+print("Test set accuracy scaled data with Standar Scaler: {:.2f}".format(svm.score(X_test_scaled,y_test)))
More on Cancer Data, now with Logistic Regression
+
+import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+from sklearn.datasets import load_breast_cancer
+from sklearn.linear_model import LogisticRegression
+cancer = load_breast_cancer()
+
+# Set up training data
+X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
+# Perform Logistic Regression (replace with own code)
+logreg = LogisticRegression()
+logreg.fit(X_train, y_train)
+print("Test set accuracy: {:.2f}".format(logreg.score(X_test,y_test)))
+
+# Scale data
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+logreg.fit(X_train_scaled, y_train)
+#svm.fit(X_train_scaled, y_train)
+print("Test set accuracy scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
+
+
+Why should we think of reducing the dimensionality
+
-# Now add PCA
+Getting started with PCA
+
+# Now add PCA
from sklearn.decomposition import PCA
pca = PCA(n_components = 2)
pca.fit(X_train_scaled)
@@ -389,7 +436,7 @@ X_pca = pca.transform(X_train_scaled)
-Principal Component Analysis
+Principal Component Analysis
PCA and scikit-learn
+PCA and scikit-learn
-More on the PCA
+More on the PCA
Instead of arbitrarily choosing the number of dimensions to reduce down to, it is generally preferable to
choose the number of dimensions that add up to a sufficiently large portion of the variance (e.g., 95%).
Unless, of course, you are reducing dimensionality for data visualization — in that case you will
@@ -484,7 +531,7 @@ X_reduced = pca.fit_transform(X)
-Incremental PCA
+Incremental PCA
One problem with the preceding implementation of PCA is that it requires the whole training set to fit in
memory in order for the SVD algorithm to run. Fortunately, Incremental PCA (IPCA) algorithms have
been developed: you can split the training set into mini-batches and feed an IPCA algorithm one minibatch
@@ -494,7 +541,7 @@ instances arrive).
-Randomized PCA
+Randomized PCA
-Kernel PCA
+Kernel PCA
-LLE
+LLE
-Other techniques
+Other techniques
Oct 14, 2019
Oct 15, 2019
@@ -312,7 +317,6 @@ svm.fit(X_train, y_train)
print("Test set accuracy: {:.2f}".format(svm.score(X_test,y_test)))
from sklearn.preprocessing import MinMaxScaler, StandardScaler
-
scaler = MinMaxScaler()
scaler.fit(X_train)
X_train_scaled = scaler.transform(X_train)
@@ -326,7 +330,7 @@ X_test_scaled = scaler.fit(X_train_scaled, y_train)
-print("Test set accuracy scaled data: {:.2f}".format(svm.score(X_test_scaled,y_test)))
+print("Test set accuracy scaled data with Min-Max scaling: {:.2f}".format(svm.score(X_test_scaled,y_test)))
scaler = StandardScaler()
scaler.fit(X_train)
@@ -334,12 +338,48 @@ X_train_scaled = scaler= scaler.transform(X_test)
svm.fit(X_train_scaled, y_train)
-print("Test set accuracy scaled data: {:.2f}".format(svm.score(X_test_scaled,y_test)))
+print("Test set accuracy scaled data with Standar Scaler: {:.2f}".format(svm.score(X_test_scaled,y_test)))
More on Cancer Data, now with Logistic Regression
+
+import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+from sklearn.datasets import load_breast_cancer
+from sklearn.linear_model import LogisticRegression
+cancer = load_breast_cancer()
+
+# Set up training data
+X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
+# Perform Logistic Regression (replace with own code)
+logreg = LogisticRegression()
+logreg.fit(X_train, y_train)
+print("Test set accuracy: {:.2f}".format(logreg.score(X_test,y_test)))
+
+# Scale data
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+logreg.fit(X_train_scaled, y_train)
+#svm.fit(X_train_scaled, y_train)
+print("Test set accuracy scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
+
+
+Why should we think of reducing the dimensionality
+
-# Now add PCA
+Getting started with PCA
+
+# Now add PCA
from sklearn.decomposition import PCA
pca = PCA(n_components = 2)
pca.fit(X_train_scaled)
@@ -394,7 +441,7 @@ X_pca = pca.
-Principal Component Analysis
+Principal Component Analysis
PCA and scikit-learn
+PCA and scikit-learn
-More on the PCA
+More on the PCA
Instead of arbitrarily choosing the number of dimensions to reduce down to, it is generally preferable to
choose the number of dimensions that add up to a sufficiently large portion of the variance (e.g., 95%).
Unless, of course, you are reducing dimensionality for data visualization — in that case you will
@@ -489,7 +536,7 @@ X_reduced = pca
-Incremental PCA
+Incremental PCA
One problem with the preceding implementation of PCA is that it requires the whole training set to fit in
memory in order for the SVD algorithm to run. Fortunately, Incremental PCA (IPCA) algorithms have
been developed: you can split the training set into mini-batches and feed an IPCA algorithm one minibatch
@@ -499,7 +546,7 @@ instances arrive).
-Randomized PCA
+Randomized PCA
-Kernel PCA
+Kernel PCA
LLE
-Other techniques
+Other techniques