commit
No files matched your search
@@ -3,7 +3,7 @@ Sebastian Raschka, 2017
|
||||
Python Machine Learning - Code Examples
|
||||
|
||||
|
||||
## Chapter 1 - Giving Computers the Ability to Learn from Data
|
||||
## Chapter 1: Giving Computers the Ability to Learn from Data
|
||||
|
||||
|
||||
---
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
Python Machine Learning - Code Examples
|
||||
|
||||
|
||||
## Chapter 2: Training Simple Machine Learning Algorithms for Classification
|
||||
|
||||
### Chapter Outline
|
||||
|
||||
- Artificial neurons – a brief glimpse into the early history of machine learning
|
||||
- The formal definition of an artificial neuron
|
||||
- The perceptron learning rule
|
||||
- Implementing a perceptron learning algorithm in Python
|
||||
- An object-oriented perceptron API
|
||||
- Training a perceptron model on the Iris dataset
|
||||
- Adaptive linear neurons and the convergence of learning
|
||||
- Minimizing cost functions with gradient descent
|
||||
- Implementing an Adaptive Linear Neuron in Python
|
||||
- Improving gradient descent through feature scaling
|
||||
- Large scale machine learning and stochastic gradient descent
|
||||
- Summary
|
||||
|
||||
### A note on using the code examples
|
||||
|
||||
The recommended way to interact with the code examples in this book is via Jupyter Notebook (the `.ipynb` files). Using Jupyter Notebook, you will be able to execute the code step by step and have all the resulting outputs (including plots and images) all in one convenient document.
|
||||
|
||||

|
||||
|
||||
|
||||
|
||||
Setting up Jupyter Notebook is really easy: if you are using the Anaconda Python distribution, all you need to install jupyter notebook is to execute the following command in your terminal:
|
||||
|
||||
conda install jupyter notebook
|
||||
|
||||
Then you can launch jupyter notebook by executing
|
||||
|
||||
jupyter notebook
|
||||
|
||||
A window will open up in your browser, which you can then use to navigate to the target directory that contains the `.ipynb` file you wish to open.
|
||||
|
||||
**More installation and setup instructions can be found in the [README.md file of Chapter 1](../ch01/README.md)**.
|
||||
|
||||
**(Even if you decide not to install Jupyter Notebook, note that you can also view the notebook files on GitHub by simply clicking on them: [`ch02.ipynb`](ch02.ipynb))**
|
||||
|
||||
In addition to the code examples, I added a table of contents to each Jupyter notebook as well as section headers that are consistent with the content of the book. Also, I included the original images and figures in hope that these make it easier to navigate and work with the code interactively as you are reading the book.
|
||||
|
||||

|
||||
|
||||
|
||||
When I was creating these notebooks, I was hoping to make your reading (and coding) experience as convenient as possible! However, if you don't wish to use Jupyter Notebooks, I also converted these notebooks to regular Python script files (`.py` files) that can be viewed and edited in any plaintext editor.
|
||||
@@ -1363,145 +1363,21 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 9,
|
||||
"execution_count": 1,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"[NbConvertApp] WARNING | pattern 'input_path' matched no files\n",
|
||||
"This application is used to convert notebook files (*.ipynb) to various other\n",
|
||||
"formats.\n",
|
||||
"\n",
|
||||
"WARNING: THE COMMANDLINE INTERFACE MAY CHANGE IN FUTURE RELEASES.\n",
|
||||
"\n",
|
||||
"Options\n",
|
||||
"-------\n",
|
||||
"\n",
|
||||
"Arguments that take values are actually convenience aliases to full\n",
|
||||
"Configurables, whose aliases are listed on the help line. For more information\n",
|
||||
"on full configurables, see '--help-all'.\n",
|
||||
"\n",
|
||||
"--debug\n",
|
||||
" set log level to logging.DEBUG (maximize logging output)\n",
|
||||
"--generate-config\n",
|
||||
" generate default config file\n",
|
||||
"-y\n",
|
||||
" Answer yes to any questions instead of prompting.\n",
|
||||
"--execute\n",
|
||||
" Execute the notebook prior to export.\n",
|
||||
"--allow-errors\n",
|
||||
" Continue notebook execution even if one of the cells throws an error and include the error message in the cell output (the default behaviour is to abort conversion). This flag is only relevant if '--execute' was specified, too.\n",
|
||||
"--stdin\n",
|
||||
" read a single notebook file from stdin. Write the resulting notebook with default basename 'notebook.*'\n",
|
||||
"--stdout\n",
|
||||
" Write notebook output to stdout instead of files.\n",
|
||||
"--inplace\n",
|
||||
" Run nbconvert in place, overwriting the existing notebook (only \n",
|
||||
" relevant when converting to notebook format)\n",
|
||||
"--no-prompt\n",
|
||||
" Exclude input and output prompts from converted document.\n",
|
||||
"--log-level=<Enum> (Application.log_level)\n",
|
||||
" Default: 30\n",
|
||||
" Choices: (0, 10, 20, 30, 40, 50, 'DEBUG', 'INFO', 'WARN', 'ERROR', 'CRITICAL')\n",
|
||||
" Set the log level by value or name.\n",
|
||||
"--config=<Unicode> (JupyterApp.config_file)\n",
|
||||
" Default: ''\n",
|
||||
" Full path of a config file.\n",
|
||||
"--to=<Unicode> (NbConvertApp.export_format)\n",
|
||||
" Default: 'html'\n",
|
||||
" The export format to be used, either one of the built-in formats, or a\n",
|
||||
" dotted object name that represents the import path for an `Exporter` class\n",
|
||||
"--template=<Unicode> (TemplateExporter.template_file)\n",
|
||||
" Default: ''\n",
|
||||
" Name of the template file to use\n",
|
||||
"--writer=<DottedObjectName> (NbConvertApp.writer_class)\n",
|
||||
" Default: 'FilesWriter'\n",
|
||||
" Writer class used to write the results of the conversion\n",
|
||||
"--post=<DottedOrNone> (NbConvertApp.postprocessor_class)\n",
|
||||
" Default: ''\n",
|
||||
" PostProcessor class used to write the results of the conversion\n",
|
||||
"--output=<Unicode> (NbConvertApp.output_base)\n",
|
||||
" Default: ''\n",
|
||||
" overwrite base name use for output files. can only be used when converting\n",
|
||||
" one notebook at a time.\n",
|
||||
"--output-dir=<Unicode> (FilesWriter.build_directory)\n",
|
||||
" Default: ''\n",
|
||||
" Directory to write output(s) to. Defaults to output to the directory of each\n",
|
||||
" notebook. To recover previous default behaviour (outputting to the current\n",
|
||||
" working directory) use . as the flag value.\n",
|
||||
"--reveal-prefix=<Unicode> (SlidesExporter.reveal_url_prefix)\n",
|
||||
" Default: ''\n",
|
||||
" The URL prefix for reveal.js. This can be a a relative URL for a local copy\n",
|
||||
" of reveal.js, or point to a CDN.\n",
|
||||
" For speaker notes to work, a local reveal.js prefix must be used.\n",
|
||||
"--nbformat=<Enum> (NotebookExporter.nbformat_version)\n",
|
||||
" Default: 4\n",
|
||||
" Choices: [1, 2, 3, 4]\n",
|
||||
" The nbformat version to write. Use this to downgrade notebooks.\n",
|
||||
"\n",
|
||||
"To see all available configurables, use `--help-all`\n",
|
||||
"\n",
|
||||
"Examples\n",
|
||||
"--------\n",
|
||||
"\n",
|
||||
" The simplest way to use nbconvert is\n",
|
||||
" \n",
|
||||
" > jupyter nbconvert mynotebook.ipynb\n",
|
||||
" \n",
|
||||
" which will convert mynotebook.ipynb to the default format (probably HTML).\n",
|
||||
" \n",
|
||||
" You can specify the export format with `--to`.\n",
|
||||
" Options include ['asciidoc', 'custom', 'html', 'latex', 'markdown', 'notebook', 'pdf', 'python', 'rst', 'script', 'slides']\n",
|
||||
" \n",
|
||||
" > jupyter nbconvert --to latex mynotebook.ipynb\n",
|
||||
" \n",
|
||||
" Both HTML and LaTeX support multiple output templates. LaTeX includes\n",
|
||||
" 'base', 'article' and 'report'. HTML includes 'basic' and 'full'. You\n",
|
||||
" can specify the flavor of the format used.\n",
|
||||
" \n",
|
||||
" > jupyter nbconvert --to html --template basic mynotebook.ipynb\n",
|
||||
" \n",
|
||||
" You can also pipe the output to stdout, rather than a file\n",
|
||||
" \n",
|
||||
" > jupyter nbconvert mynotebook.ipynb --stdout\n",
|
||||
" \n",
|
||||
" PDF is generated via latex\n",
|
||||
" \n",
|
||||
" > jupyter nbconvert mynotebook.ipynb --to pdf\n",
|
||||
" \n",
|
||||
" You can get (and serve) a Reveal.js-powered slideshow\n",
|
||||
" \n",
|
||||
" > jupyter nbconvert myslides.ipynb --to slides --post serve\n",
|
||||
" \n",
|
||||
" Multiple notebooks can be given at the command line in a couple of \n",
|
||||
" different ways:\n",
|
||||
" \n",
|
||||
" > jupyter nbconvert notebook*.ipynb\n",
|
||||
" > jupyter nbconvert notebook1.ipynb notebook2.ipynb\n",
|
||||
" \n",
|
||||
" or you can specify the notebooks list in a config file, containing::\n",
|
||||
" \n",
|
||||
" c.NbConvertApp.notebooks = [\"my_notebook.ipynb\"]\n",
|
||||
" \n",
|
||||
" > jupyter nbconvert --config mycfg.py\n",
|
||||
"\n"
|
||||
"[NbConvertApp] Converting notebook ch02.ipynb to script\n",
|
||||
"[NbConvertApp] Writing 16456 bytes to ch02.py\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"! python ../.convert_notebook_to_script.py --input ch02.ipynb --output ch02.py"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"collapsed": true
|
||||
},
|
||||
"outputs": [],
|
||||
"source": []
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
|
||||
# coding: utf-8
|
||||
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import matplotlib.pyplot as plt
|
||||
from matplotlib.colors import ListedColormap
|
||||
|
||||
# *Python Machine Learning 2nd Edition* by [Sebastian Raschka](https://sebastianraschka.com), Packt Publishing Ltd. 2017
|
||||
#
|
||||
# Code Repository: https://github.com/rasbt/python-machine-learning-book-2nd-edition
|
||||
@@ -13,7 +18,6 @@
|
||||
|
||||
# Note that the optional watermark extension is a small IPython notebook plugin that I developed to make the code reproducible. You can just skip the following line(s).
|
||||
|
||||
# In[1]:
|
||||
|
||||
|
||||
|
||||
@@ -37,34 +41,28 @@
|
||||
# - [Summary](#Summary)
|
||||
|
||||
|
||||
# In[2]:
|
||||
|
||||
|
||||
from IPython.display import Image
|
||||
|
||||
|
||||
# # Artificial neurons - a brief glimpse into the early history of machine learning
|
||||
|
||||
# In[3]:
|
||||
|
||||
|
||||
|
||||
|
||||
# ## The formal definition of an artificial neuron
|
||||
|
||||
# In[4]:
|
||||
|
||||
|
||||
|
||||
|
||||
# ## The perceptron learning rule
|
||||
|
||||
# In[5]:
|
||||
|
||||
|
||||
|
||||
|
||||
# In[6]:
|
||||
|
||||
|
||||
|
||||
@@ -74,10 +72,8 @@ from IPython.display import Image
|
||||
|
||||
# ## An object-oriented perceptron API
|
||||
|
||||
# In[7]:
|
||||
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
class Perceptron(object):
|
||||
@@ -145,7 +141,6 @@ class Perceptron(object):
|
||||
return np.where(self.net_input(X) >= 0.0, 1, -1)
|
||||
|
||||
|
||||
# In[8]:
|
||||
|
||||
|
||||
v1 = np.array([1, 2, 3])
|
||||
@@ -160,17 +155,14 @@ np.arccos(v1.dot(v2) / (np.linalg.norm(v1) * np.linalg.norm(v2)))
|
||||
|
||||
# ### Reading-in the Iris data
|
||||
|
||||
# In[9]:
|
||||
|
||||
|
||||
import pandas as pd
|
||||
|
||||
df = pd.read_csv('https://archive.ics.uci.edu/ml/'
|
||||
'machine-learning-databases/iris/iris.data', header=None)
|
||||
df.tail()
|
||||
|
||||
|
||||
# <hr>
|
||||
#
|
||||
# ### Note:
|
||||
#
|
||||
@@ -185,23 +177,18 @@ df.tail()
|
||||
# df = pd.read_csv('your/local/path/to/iris.data', header=None)
|
||||
#
|
||||
|
||||
# In[10]:
|
||||
|
||||
|
||||
df = pd.read_csv('iris.data', header=None)
|
||||
df.tail()
|
||||
|
||||
|
||||
# <hr>
|
||||
|
||||
|
||||
# ### Plotting the Iris data
|
||||
|
||||
# In[11]:
|
||||
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
|
||||
# select setosa and versicolor
|
||||
y = df.iloc[0:100, 4].values
|
||||
@@ -227,7 +214,6 @@ plt.show()
|
||||
|
||||
# ### Training the perceptron model
|
||||
|
||||
# In[12]:
|
||||
|
||||
|
||||
ppn = Perceptron(eta=0.1, n_iter=10)
|
||||
@@ -245,10 +231,8 @@ plt.show()
|
||||
|
||||
# ### A function for plotting decision regions
|
||||
|
||||
# In[13]:
|
||||
|
||||
|
||||
from matplotlib.colors import ListedColormap
|
||||
|
||||
|
||||
def plot_decision_regions(X, y, classifier, resolution=0.02):
|
||||
@@ -280,7 +264,6 @@ def plot_decision_regions(X, y, classifier, resolution=0.02):
|
||||
edgecolor='black')
|
||||
|
||||
|
||||
# In[14]:
|
||||
|
||||
|
||||
plot_decision_regions(X, y, classifier=ppn)
|
||||
@@ -300,12 +283,10 @@ plt.show()
|
||||
|
||||
# ## Minimizing cost functions with gradient descent
|
||||
|
||||
# In[15]:
|
||||
|
||||
|
||||
|
||||
|
||||
# In[16]:
|
||||
|
||||
|
||||
|
||||
@@ -313,7 +294,6 @@ plt.show()
|
||||
|
||||
# ## Implementing an adaptive linear neuron in Python
|
||||
|
||||
# In[17]:
|
||||
|
||||
|
||||
class AdalineGD(object):
|
||||
@@ -393,7 +373,6 @@ class AdalineGD(object):
|
||||
return np.where(self.activation(self.net_input(X)) >= 0.0, 1, -1)
|
||||
|
||||
|
||||
# In[18]:
|
||||
|
||||
|
||||
fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(10, 4))
|
||||
@@ -415,7 +394,6 @@ plt.show()
|
||||
|
||||
|
||||
|
||||
# In[19]:
|
||||
|
||||
|
||||
|
||||
@@ -423,12 +401,10 @@ plt.show()
|
||||
|
||||
# ## Improving gradient descent through feature scaling
|
||||
|
||||
# In[20]:
|
||||
|
||||
|
||||
|
||||
|
||||
# In[21]:
|
||||
|
||||
|
||||
# standardize features
|
||||
@@ -437,7 +413,6 @@ X_std[:, 0] = (X[:, 0] - X[:, 0].mean()) / X[:, 0].std()
|
||||
X_std[:, 1] = (X[:, 1] - X[:, 1].mean()) / X[:, 1].std()
|
||||
|
||||
|
||||
# In[22]:
|
||||
|
||||
|
||||
ada = AdalineGD(n_iter=15, eta=0.01)
|
||||
@@ -464,7 +439,6 @@ plt.show()
|
||||
|
||||
# ## Large scale machine learning and stochastic gradient descent
|
||||
|
||||
# In[23]:
|
||||
|
||||
|
||||
class AdalineSGD(object):
|
||||
@@ -572,7 +546,6 @@ class AdalineSGD(object):
|
||||
return np.where(self.activation(self.net_input(X)) >= 0.0, 1, -1)
|
||||
|
||||
|
||||
# In[24]:
|
||||
|
||||
|
||||
ada = AdalineSGD(n_iter=15, eta=0.01, random_state=1)
|
||||
@@ -597,7 +570,6 @@ plt.tight_layout()
|
||||
plt.show()
|
||||
|
||||
|
||||
# In[25]:
|
||||
|
||||
|
||||
ada.partial_fit(X_std[0, :], y[0])
|
||||
@@ -612,12 +584,10 @@ ada.partial_fit(X_std[0, :], y[0])
|
||||
#
|
||||
# Readers may ignore the following cell
|
||||
|
||||
# In[9]:
|
||||
|
||||
|
||||
|
||||
|
||||
# In[ ]:
|
||||
|
||||
|
||||
|
||||
|
||||
|
After Width: | Height: | Size: 93 KiB |
|
After Width: | Height: | Size: 124 KiB |
@@ -0,0 +1,57 @@
|
||||
Python Machine Learning - Code Examples
|
||||
|
||||
|
||||
## Chapter 3: A Tour of Machine Learning Classifiers Using scikit-learn
|
||||
|
||||
### Chapter Outline
|
||||
|
||||
- Choosing a classi cation algorithm
|
||||
- First steps with scikit-learn – training a perceptron
|
||||
- Modeling class probabilities via logistic regression
|
||||
- Logistic regression intuition and conditional probabilities
|
||||
- Learning the weights of the logistic cost function
|
||||
- Converting an Adaline implementation into an algorithm for logistic regression
|
||||
- Training a logistic regression model with scikit-learn
|
||||
- Tackling over tting via regularization
|
||||
- Maximum margin classification with support vector machines
|
||||
- Maximum margin intuition
|
||||
- Dealing with a nonlinearly separable case using slack variables
|
||||
- Alternative implementations in scikit-learn
|
||||
- Solving nonlinear problems using a kernel SVM
|
||||
- Kernel methods for linearly inseparable data
|
||||
- Using the kernel trick to find separating hyperplanes in high-dimensional space
|
||||
- Decision tree learning
|
||||
- Maximizing information gain – getting the most bang for your buck
|
||||
- Building a decision tree
|
||||
- Combining multiple decision trees via random forests
|
||||
- K-nearest neighbors – a lazy learning algorithm
|
||||
- Summary
|
||||
|
||||
### A note on using the code examples
|
||||
|
||||
The recommended way to interact with the code examples in this book is via Jupyter Notebook (the `.ipynb` files). Using Jupyter Notebook, you will be able to execute the code step by step and have all the resulting outputs (including plots and images) all in one convenient document.
|
||||
|
||||

|
||||
|
||||
|
||||
|
||||
Setting up Jupyter Notebook is really easy: if you are using the Anaconda Python distribution, all you need to install jupyter notebook is to execute the following command in your terminal:
|
||||
|
||||
conda install jupyter notebook
|
||||
|
||||
Then you can launch jupyter notebook by executing
|
||||
|
||||
jupyter notebook
|
||||
|
||||
A window will open up in your browser, which you can then use to navigate to the target directory that contains the `.ipynb` file you wish to open.
|
||||
|
||||
**More installation and setup instructions can be found in the [README.md file of Chapter 1](../ch01/README.md)**.
|
||||
|
||||
**(Even if you decide not to install Jupyter Notebook, note that you can also view the notebook files on GitHub by simply clicking on them: [`ch03.ipynb`](ch03.ipynb))**
|
||||
|
||||
In addition to the code examples, I added a table of contents to each Jupyter notebook as well as section headers that are consistent with the content of the book. Also, I included the original images and figures in hope that these make it easier to navigate and work with the code interactively as you are reading the book.
|
||||
|
||||

|
||||
|
||||
|
||||
When I was creating these notebooks, I was hoping to make your reading (and coding) experience as convenient as possible! However, if you don't wish to use Jupyter Notebooks, I also converted these notebooks to regular Python script files (`.py` files) that can be viewed and edited in any plaintext editor.
|
||||
@@ -1743,7 +1743,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 1,
|
||||
"execution_count": 4,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
@@ -1751,13 +1751,22 @@
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"[NbConvertApp] Converting notebook ch03.ipynb to script\n",
|
||||
"[NbConvertApp] Writing 20288 bytes to ch03.py\n"
|
||||
"[NbConvertApp] Writing 20274 bytes to ch03.py\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"! python ../.convert_notebook_to_script.py --input ch03.ipynb --output ch03.py"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"collapsed": true
|
||||
},
|
||||
"outputs": [],
|
||||
"source": []
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
|
||||
@@ -1,6 +1,25 @@
|
||||
|
||||
# coding: utf-8
|
||||
|
||||
|
||||
from sklearn import __version__ as sklearn_version
|
||||
from distutils.version import LooseVersion
|
||||
from sklearn import datasets
|
||||
import numpy as np
|
||||
from sklearn.model_selection import train_test_split
|
||||
from sklearn.preprocessing import StandardScaler
|
||||
from sklearn.linear_model import Perceptron
|
||||
from sklearn.metrics import accuracy_score
|
||||
from matplotlib.colors import ListedColormap
|
||||
import matplotlib.pyplot as plt
|
||||
from sklearn.linear_model import LogisticRegression
|
||||
from sklearn.svm import SVC
|
||||
from sklearn.linear_model import SGDClassifier
|
||||
from sklearn.tree import DecisionTreeClassifier
|
||||
from pydotplus import graph_from_dot_data
|
||||
from sklearn.tree import export_graphviz
|
||||
from sklearn.ensemble import RandomForestClassifier
|
||||
from sklearn.neighbors import KNeighborsClassifier
|
||||
|
||||
# *Python Machine Learning 2nd Edition* by [Sebastian Raschka](https://sebastianraschka.com), Packt Publishing Ltd. 2017
|
||||
#
|
||||
# Code Repository: https://github.com/rasbt/python-machine-learning-book-2nd-edition
|
||||
@@ -13,16 +32,12 @@
|
||||
|
||||
# Note that the optional watermark extension is a small IPython notebook plugin that I developed to make the code reproducible. You can just skip the following line(s).
|
||||
|
||||
# In[1]:
|
||||
|
||||
|
||||
|
||||
|
||||
# In[2]:
|
||||
|
||||
|
||||
from sklearn import __version__ as sklearn_version
|
||||
from distutils.version import LooseVersion
|
||||
|
||||
if LooseVersion(sklearn_version) < LooseVersion('0.18'):
|
||||
raise ValueError('Please use scikit-learn 0.18 or newer')
|
||||
@@ -55,10 +70,8 @@ if LooseVersion(sklearn_version) < LooseVersion('0.18'):
|
||||
|
||||
|
||||
|
||||
# In[3]:
|
||||
|
||||
|
||||
from IPython.display import Image
|
||||
|
||||
|
||||
# # Choosing a classification algorithm
|
||||
@@ -69,11 +82,8 @@ from IPython.display import Image
|
||||
|
||||
# Loading the Iris dataset from scikit-learn. Here, the third column represents the petal length, and the fourth column the petal width of the flower samples. The classes are already converted to integer labels where 0=Iris-Setosa, 1=Iris-Versicolor, 2=Iris-Virginica.
|
||||
|
||||
# In[4]:
|
||||
|
||||
|
||||
from sklearn import datasets
|
||||
import numpy as np
|
||||
|
||||
iris = datasets.load_iris()
|
||||
X = iris.data[:, [2, 3]]
|
||||
@@ -84,16 +94,13 @@ print('Class labels:', np.unique(y))
|
||||
|
||||
# Splitting data into 70% training and 30% test data:
|
||||
|
||||
# In[5]:
|
||||
|
||||
|
||||
from sklearn.model_selection import train_test_split
|
||||
|
||||
X_train, X_test, y_train, y_test = train_test_split(
|
||||
X, y, test_size=0.3, random_state=1, stratify=y)
|
||||
|
||||
|
||||
# In[6]:
|
||||
|
||||
|
||||
print('Labels counts in y:', np.bincount(y))
|
||||
@@ -103,10 +110,8 @@ print('Labels counts in y_test:', np.bincount(y_test))
|
||||
|
||||
# Standardizing the features:
|
||||
|
||||
# In[7]:
|
||||
|
||||
|
||||
from sklearn.preprocessing import StandardScaler
|
||||
|
||||
sc = StandardScaler()
|
||||
sc.fit(X_train)
|
||||
@@ -119,10 +124,8 @@ X_test_std = sc.transform(X_test)
|
||||
|
||||
# Redefining the `plot_decision_region` function from chapter 2:
|
||||
|
||||
# In[8]:
|
||||
|
||||
|
||||
from sklearn.linear_model import Perceptron
|
||||
|
||||
ppn = Perceptron(n_iter=40, eta0=0.1, random_state=1)
|
||||
ppn.fit(X_train_std, y_train)
|
||||
@@ -132,32 +135,25 @@ ppn.fit(X_train_std, y_train)
|
||||
#
|
||||
# - You can replace `Perceptron(n_iter, ...)` by `Perceptron(max_iter, ...)` in scikit-learn >= 0.19. The `n_iter` parameter is used here deriberately, because some people still use scikit-learn 0.18.
|
||||
|
||||
# In[9]:
|
||||
|
||||
|
||||
y_pred = ppn.predict(X_test_std)
|
||||
print('Misclassified samples: %d' % (y_test != y_pred).sum())
|
||||
|
||||
|
||||
# In[10]:
|
||||
|
||||
|
||||
from sklearn.metrics import accuracy_score
|
||||
|
||||
print('Accuracy: %.2f' % accuracy_score(y_test, y_pred))
|
||||
|
||||
|
||||
# In[11]:
|
||||
|
||||
|
||||
print('Accuracy: %.2f' % ppn.score(X_test_std, y_test))
|
||||
|
||||
|
||||
# In[12]:
|
||||
|
||||
|
||||
from matplotlib.colors import ListedColormap
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
|
||||
def plot_decision_regions(X, y, classifier, test_idx=None, resolution=0.02):
|
||||
@@ -205,7 +201,6 @@ def plot_decision_regions(X, y, classifier, test_idx=None, resolution=0.02):
|
||||
|
||||
# Training a perceptron model using the standardized training data:
|
||||
|
||||
# In[13]:
|
||||
|
||||
|
||||
X_combined_std = np.vstack((X_train_std, X_test_std))
|
||||
@@ -229,11 +224,8 @@ plt.show()
|
||||
|
||||
# ### Logistic regression intuition and conditional probabilities
|
||||
|
||||
# In[14]:
|
||||
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
|
||||
|
||||
def sigmoid(z):
|
||||
@@ -258,7 +250,6 @@ plt.tight_layout()
|
||||
plt.show()
|
||||
|
||||
|
||||
# In[15]:
|
||||
|
||||
|
||||
|
||||
@@ -266,7 +257,6 @@ plt.show()
|
||||
|
||||
# ### Learning the weights of the logistic cost function
|
||||
|
||||
# In[16]:
|
||||
|
||||
|
||||
def cost_1(z):
|
||||
@@ -295,7 +285,6 @@ plt.tight_layout()
|
||||
plt.show()
|
||||
|
||||
|
||||
# In[17]:
|
||||
|
||||
|
||||
class LogisticRegressionGD(object):
|
||||
@@ -374,7 +363,6 @@ class LogisticRegressionGD(object):
|
||||
|
||||
|
||||
|
||||
# In[18]:
|
||||
|
||||
|
||||
X_train_01_subset = X_train[(y_train == 0) | (y_train == 1)]
|
||||
@@ -399,10 +387,8 @@ plt.show()
|
||||
|
||||
# ### Training a logistic regression model with scikit-learn
|
||||
|
||||
# In[19]:
|
||||
|
||||
|
||||
from sklearn.linear_model import LogisticRegression
|
||||
|
||||
lr = LogisticRegression(C=100.0, random_state=1)
|
||||
lr.fit(X_train_std, y_train)
|
||||
@@ -417,31 +403,26 @@ plt.tight_layout()
|
||||
plt.show()
|
||||
|
||||
|
||||
# In[20]:
|
||||
|
||||
|
||||
lr.predict_proba(X_test_std[:3, :])
|
||||
|
||||
|
||||
# In[21]:
|
||||
|
||||
|
||||
lr.predict_proba(X_test_std[:3, :]).sum(axis=1)
|
||||
|
||||
|
||||
# In[22]:
|
||||
|
||||
|
||||
lr.predict_proba(X_test_std[:3, :]).argmax(axis=1)
|
||||
|
||||
|
||||
# In[23]:
|
||||
|
||||
|
||||
lr.predict(X_test_std[:3, :])
|
||||
|
||||
|
||||
# In[24]:
|
||||
|
||||
|
||||
lr.predict(X_test_std[0, :].reshape(1, -1))
|
||||
@@ -450,12 +431,10 @@ lr.predict(X_test_std[0, :].reshape(1, -1))
|
||||
|
||||
# ### Tackling overfitting via regularization
|
||||
|
||||
# In[25]:
|
||||
|
||||
|
||||
|
||||
|
||||
# In[26]:
|
||||
|
||||
|
||||
weights, params = [], []
|
||||
@@ -481,7 +460,6 @@ plt.show()
|
||||
|
||||
# # Maximum margin classification with support vector machines
|
||||
|
||||
# In[27]:
|
||||
|
||||
|
||||
|
||||
@@ -492,15 +470,12 @@ plt.show()
|
||||
|
||||
# ## Dealing with the nonlinearly separable case using slack variables
|
||||
|
||||
# In[28]:
|
||||
|
||||
|
||||
|
||||
|
||||
# In[29]:
|
||||
|
||||
|
||||
from sklearn.svm import SVC
|
||||
|
||||
svm = SVC(kernel='linear', C=1.0, random_state=1)
|
||||
svm.fit(X_train_std, y_train)
|
||||
@@ -519,10 +494,8 @@ plt.show()
|
||||
|
||||
# ## Alternative implementations in scikit-learn
|
||||
|
||||
# In[30]:
|
||||
|
||||
|
||||
from sklearn.linear_model import SGDClassifier
|
||||
|
||||
ppn = SGDClassifier(loss='perceptron', n_iter=1000)
|
||||
lr = SGDClassifier(loss='log', n_iter=1000)
|
||||
@@ -536,11 +509,8 @@ svm = SGDClassifier(loss='hinge', n_iter=1000)
|
||||
|
||||
# # Solving non-linear problems using a kernel SVM
|
||||
|
||||
# In[31]:
|
||||
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
|
||||
np.random.seed(1)
|
||||
X_xor = np.random.randn(200, 2)
|
||||
@@ -566,7 +536,6 @@ plt.tight_layout()
|
||||
plt.show()
|
||||
|
||||
|
||||
# In[32]:
|
||||
|
||||
|
||||
|
||||
@@ -574,7 +543,6 @@ plt.show()
|
||||
|
||||
# ## Using the kernel trick to find separating hyperplanes in higher dimensional space
|
||||
|
||||
# In[33]:
|
||||
|
||||
|
||||
svm = SVC(kernel='rbf', random_state=1, gamma=0.10, C=10.0)
|
||||
@@ -588,10 +556,8 @@ plt.tight_layout()
|
||||
plt.show()
|
||||
|
||||
|
||||
# In[34]:
|
||||
|
||||
|
||||
from sklearn.svm import SVC
|
||||
|
||||
svm = SVC(kernel='rbf', random_state=1, gamma=0.2, C=1.0)
|
||||
svm.fit(X_train_std, y_train)
|
||||
@@ -606,7 +572,6 @@ plt.tight_layout()
|
||||
plt.show()
|
||||
|
||||
|
||||
# In[35]:
|
||||
|
||||
|
||||
svm = SVC(kernel='rbf', random_state=1, gamma=100.0, C=1.0)
|
||||
@@ -625,12 +590,10 @@ plt.show()
|
||||
|
||||
# # Decision tree learning
|
||||
|
||||
# In[36]:
|
||||
|
||||
|
||||
|
||||
|
||||
# In[37]:
|
||||
|
||||
|
||||
|
||||
@@ -638,11 +601,8 @@ plt.show()
|
||||
|
||||
# ## Maximizing information gain - getting the most bang for the buck
|
||||
|
||||
# In[38]:
|
||||
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
|
||||
|
||||
def gini(p):
|
||||
@@ -686,10 +646,8 @@ plt.show()
|
||||
|
||||
# ## Building a decision tree
|
||||
|
||||
# In[39]:
|
||||
|
||||
|
||||
from sklearn.tree import DecisionTreeClassifier
|
||||
|
||||
tree = DecisionTreeClassifier(criterion='gini',
|
||||
max_depth=4,
|
||||
@@ -710,11 +668,8 @@ plt.show()
|
||||
|
||||
|
||||
|
||||
# In[40]:
|
||||
|
||||
|
||||
from pydotplus import graph_from_dot_data
|
||||
from sklearn.tree import export_graphviz
|
||||
|
||||
dot_data = export_graphviz(tree,
|
||||
filled=True,
|
||||
@@ -729,7 +684,6 @@ graph = graph_from_dot_data(dot_data)
|
||||
graph.write_png('tree.png')
|
||||
|
||||
|
||||
# In[41]:
|
||||
|
||||
|
||||
|
||||
@@ -737,10 +691,8 @@ graph.write_png('tree.png')
|
||||
|
||||
# ## Combining weak to strong learners via random forests
|
||||
|
||||
# In[42]:
|
||||
|
||||
|
||||
from sklearn.ensemble import RandomForestClassifier
|
||||
|
||||
forest = RandomForestClassifier(criterion='gini',
|
||||
n_estimators=25,
|
||||
@@ -762,15 +714,12 @@ plt.show()
|
||||
|
||||
# # K-nearest neighbors - a lazy learning algorithm
|
||||
|
||||
# In[43]:
|
||||
|
||||
|
||||
|
||||
|
||||
# In[44]:
|
||||
|
||||
|
||||
from sklearn.neighbors import KNeighborsClassifier
|
||||
|
||||
knn = KNeighborsClassifier(n_neighbors=5,
|
||||
p=2,
|
||||
@@ -797,13 +746,6 @@ plt.show()
|
||||
#
|
||||
# Readers may ignore the next cell.
|
||||
|
||||
# In[ ]:
|
||||
|
||||
|
||||
|
||||
|
||||
# In[ ]:
|
||||
|
||||
|
||||
|
||||
|
||||
|
After Width: | Height: | Size: 141 KiB |
@@ -0,0 +1,56 @@
|
||||
Python Machine Learning - Code Examples
|
||||
|
||||
|
||||
## Chapter 4: Building Good Training Sets – Data Preprocessing
|
||||
|
||||
### Chapter Outline
|
||||
|
||||
- Dealing with missing data
|
||||
- Identifying missing values in tabular data
|
||||
- Eliminating samples or features with missing values
|
||||
- Imputing missing values
|
||||
- Understanding the scikit-learn estimator API
|
||||
- Handling categorical data
|
||||
- Nominal and ordinal features
|
||||
- Creating an example dataset
|
||||
- Mapping ordinal features
|
||||
- Encoding class labels
|
||||
- Performing one-hot encoding on nominal features
|
||||
- Partitioning a dataset into separate training and test sets
|
||||
- Bringing features onto the same scale
|
||||
- Selecting meaningful features
|
||||
- L1 and L2 regularization as penalties against model complexity
|
||||
- A geometric interpretation of L2 regularization
|
||||
- Sparse solutions with L1 regularization
|
||||
- Sequential feature selection algorithms
|
||||
- Assessing feature importance with random forests
|
||||
- Summary
|
||||
|
||||
### A note on using the code examples
|
||||
|
||||
The recommended way to interact with the code examples in this book is via Jupyter Notebook (the `.ipynb` files). Using Jupyter Notebook, you will be able to execute the code step by step and have all the resulting outputs (including plots and images) all in one convenient document.
|
||||
|
||||

|
||||
|
||||
|
||||
|
||||
Setting up Jupyter Notebook is really easy: if you are using the Anaconda Python distribution, all you need to install jupyter notebook is to execute the following command in your terminal:
|
||||
|
||||
conda install jupyter notebook
|
||||
|
||||
Then you can launch jupyter notebook by executing
|
||||
|
||||
jupyter notebook
|
||||
|
||||
A window will open up in your browser, which you can then use to navigate to the target directory that contains the `.ipynb` file you wish to open.
|
||||
|
||||
**More installation and setup instructions can be found in the [README.md file of Chapter 1](../ch01/README.md)**.
|
||||
|
||||
**(Even if you decide not to install Jupyter Notebook, note that you can also view the notebook files on GitHub by simply clicking on them: [`ch04.ipynb`](ch04.ipynb))**
|
||||
|
||||
In addition to the code examples, I added a table of contents to each Jupyter notebook as well as section headers that are consistent with the content of the book. Also, I included the original images and figures in hope that these make it easier to navigate and work with the code interactively as you are reading the book.
|
||||
|
||||

|
||||
|
||||
|
||||
When I was creating these notebooks, I was hoping to make your reading (and coding) experience as convenient as possible! However, if you don't wish to use Jupyter Notebooks, I also converted these notebooks to regular Python script files (`.py` files) that can be viewed and edited in any plaintext editor.
|
||||
@@ -2522,7 +2522,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 1,
|
||||
"execution_count": 2,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
@@ -2530,7 +2530,7 @@
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"[NbConvertApp] Converting notebook ch04.ipynb to script\n",
|
||||
"[NbConvertApp] Writing 15145 bytes to ch04.py\n"
|
||||
"[NbConvertApp] Writing 15306 bytes to ch04.py\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
|
||||
@@ -1,6 +1,25 @@
|
||||
|
||||
# coding: utf-8
|
||||
|
||||
|
||||
import pandas as pd
|
||||
from io import StringIO
|
||||
import sys
|
||||
from sklearn.preprocessing import Imputer
|
||||
import numpy as np
|
||||
from sklearn.preprocessing import LabelEncoder
|
||||
from sklearn.preprocessing import OneHotEncoder
|
||||
from sklearn.model_selection import train_test_split
|
||||
from sklearn.preprocessing import MinMaxScaler
|
||||
from sklearn.preprocessing import StandardScaler
|
||||
from sklearn.linear_model import LogisticRegression
|
||||
import matplotlib.pyplot as plt
|
||||
from sklearn.base import clone
|
||||
from itertools import combinations
|
||||
from sklearn.metrics import accuracy_score
|
||||
from sklearn.neighbors import KNeighborsClassifier
|
||||
from sklearn.ensemble import RandomForestClassifier
|
||||
from sklearn.feature_selection import SelectFromModel
|
||||
|
||||
# *Python Machine Learning 2nd Edition* by [Sebastian Raschka](https://sebastianraschka.com), Packt Publishing Ltd. 2017
|
||||
#
|
||||
# Code Repository: https://github.com/rasbt/python-machine-learning-book-2nd-edition
|
||||
@@ -13,7 +32,6 @@
|
||||
|
||||
# Note that the optional watermark extension is a small IPython notebook plugin that I developed to make the code reproducible. You can just skip the following line(s).
|
||||
|
||||
# In[1]:
|
||||
|
||||
|
||||
|
||||
@@ -44,22 +62,16 @@
|
||||
# - [Summary](#Summary)
|
||||
|
||||
|
||||
# In[2]:
|
||||
|
||||
|
||||
from IPython.display import Image
|
||||
|
||||
|
||||
# # Dealing with missing data
|
||||
|
||||
# ## Identifying missing values in tabular data
|
||||
|
||||
# In[3]:
|
||||
|
||||
|
||||
import pandas as pd
|
||||
from io import StringIO
|
||||
import sys
|
||||
|
||||
csv_data = '''A,B,C,D
|
||||
1.0,2.0,3.0,4.0
|
||||
@@ -76,13 +88,11 @@ df = pd.read_csv(StringIO(csv_data))
|
||||
df
|
||||
|
||||
|
||||
# In[4]:
|
||||
|
||||
|
||||
df.isnull().sum()
|
||||
|
||||
|
||||
# In[5]:
|
||||
|
||||
|
||||
# access the underlying NumPy array
|
||||
@@ -93,7 +103,6 @@ df.values
|
||||
|
||||
# ## Eliminating samples or features with missing values
|
||||
|
||||
# In[6]:
|
||||
|
||||
|
||||
# remove rows that contain missing values
|
||||
@@ -101,7 +110,6 @@ df.values
|
||||
df.dropna(axis=0)
|
||||
|
||||
|
||||
# In[7]:
|
||||
|
||||
|
||||
# remove columns that contain missing values
|
||||
@@ -109,7 +117,6 @@ df.dropna(axis=0)
|
||||
df.dropna(axis=1)
|
||||
|
||||
|
||||
# In[8]:
|
||||
|
||||
|
||||
# remove columns that contain missing values
|
||||
@@ -117,7 +124,6 @@ df.dropna(axis=1)
|
||||
df.dropna(axis=1)
|
||||
|
||||
|
||||
# In[9]:
|
||||
|
||||
|
||||
# only drop rows where all columns are NaN
|
||||
@@ -125,7 +131,6 @@ df.dropna(axis=1)
|
||||
df.dropna(how='all')
|
||||
|
||||
|
||||
# In[10]:
|
||||
|
||||
|
||||
# drop rows that have less than 3 real values
|
||||
@@ -133,7 +138,6 @@ df.dropna(how='all')
|
||||
df.dropna(thresh=4)
|
||||
|
||||
|
||||
# In[11]:
|
||||
|
||||
|
||||
# only drop rows where NaN appear in specific columns (here: 'C')
|
||||
@@ -144,19 +148,16 @@ df.dropna(subset=['C'])
|
||||
|
||||
# ## Imputing missing values
|
||||
|
||||
# In[12]:
|
||||
|
||||
|
||||
# again: our original array
|
||||
df.values
|
||||
|
||||
|
||||
# In[13]:
|
||||
|
||||
|
||||
# impute missing values via the column mean
|
||||
|
||||
from sklearn.preprocessing import Imputer
|
||||
|
||||
imr = Imputer(missing_values='NaN', strategy='mean', axis=0)
|
||||
imr = imr.fit(df.values)
|
||||
@@ -167,12 +168,10 @@ imputed_data
|
||||
|
||||
# ## Understanding the scikit-learn estimator API
|
||||
|
||||
# In[14]:
|
||||
|
||||
|
||||
|
||||
|
||||
# In[15]:
|
||||
|
||||
|
||||
|
||||
@@ -182,10 +181,8 @@ imputed_data
|
||||
|
||||
# ## Nominal and ordinal features
|
||||
|
||||
# In[16]:
|
||||
|
||||
|
||||
import pandas as pd
|
||||
|
||||
df = pd.DataFrame([['green', 'M', 10.1, 'class1'],
|
||||
['red', 'L', 13.5, 'class2'],
|
||||
@@ -198,7 +195,6 @@ df
|
||||
|
||||
# ## Mapping ordinal features
|
||||
|
||||
# In[17]:
|
||||
|
||||
|
||||
size_mapping = {'XL': 3,
|
||||
@@ -209,7 +205,6 @@ df['size'] = df['size'].map(size_mapping)
|
||||
df
|
||||
|
||||
|
||||
# In[18]:
|
||||
|
||||
|
||||
inv_size_mapping = {v: k for k, v in size_mapping.items()}
|
||||
@@ -219,10 +214,8 @@ df['size'].map(inv_size_mapping)
|
||||
|
||||
# ## Encoding class labels
|
||||
|
||||
# In[19]:
|
||||
|
||||
|
||||
import numpy as np
|
||||
|
||||
# create a mapping dict
|
||||
# to convert class labels from strings to integers
|
||||
@@ -230,7 +223,6 @@ class_mapping = {label: idx for idx, label in enumerate(np.unique(df['classlabel
|
||||
class_mapping
|
||||
|
||||
|
||||
# In[20]:
|
||||
|
||||
|
||||
# to convert class labels from strings to integers
|
||||
@@ -238,7 +230,6 @@ df['classlabel'] = df['classlabel'].map(class_mapping)
|
||||
df
|
||||
|
||||
|
||||
# In[21]:
|
||||
|
||||
|
||||
# reverse the class label mapping
|
||||
@@ -247,10 +238,8 @@ df['classlabel'] = df['classlabel'].map(inv_class_mapping)
|
||||
df
|
||||
|
||||
|
||||
# In[22]:
|
||||
|
||||
|
||||
from sklearn.preprocessing import LabelEncoder
|
||||
|
||||
# Label encoding with sklearn's LabelEncoder
|
||||
class_le = LabelEncoder()
|
||||
@@ -258,7 +247,6 @@ y = class_le.fit_transform(df['classlabel'].values)
|
||||
y
|
||||
|
||||
|
||||
# In[23]:
|
||||
|
||||
|
||||
# reverse mapping
|
||||
@@ -268,7 +256,6 @@ class_le.inverse_transform(y)
|
||||
|
||||
# ## Performing one-hot encoding on nominal features
|
||||
|
||||
# In[24]:
|
||||
|
||||
|
||||
X = df[['color', 'size', 'price']].values
|
||||
@@ -278,16 +265,13 @@ X[:, 0] = color_le.fit_transform(X[:, 0])
|
||||
X
|
||||
|
||||
|
||||
# In[25]:
|
||||
|
||||
|
||||
from sklearn.preprocessing import OneHotEncoder
|
||||
|
||||
ohe = OneHotEncoder(categorical_features=[0])
|
||||
ohe.fit_transform(X).toarray()
|
||||
|
||||
|
||||
# In[26]:
|
||||
|
||||
|
||||
# return dense array so that we can skip
|
||||
@@ -297,7 +281,6 @@ ohe = OneHotEncoder(categorical_features=[0], sparse=False)
|
||||
ohe.fit_transform(X)
|
||||
|
||||
|
||||
# In[27]:
|
||||
|
||||
|
||||
# one-hot encoding via pandas
|
||||
@@ -305,7 +288,6 @@ ohe.fit_transform(X)
|
||||
pd.get_dummies(df[['price', 'color', 'size']])
|
||||
|
||||
|
||||
# In[28]:
|
||||
|
||||
|
||||
# multicollinearity guard in get_dummies
|
||||
@@ -313,7 +295,6 @@ pd.get_dummies(df[['price', 'color', 'size']])
|
||||
pd.get_dummies(df[['price', 'color', 'size']], drop_first=True)
|
||||
|
||||
|
||||
# In[29]:
|
||||
|
||||
|
||||
# multicollinearity guard for the OneHotEncoder
|
||||
@@ -325,7 +306,6 @@ ohe.fit_transform(X).toarray()[:, 1:]
|
||||
|
||||
# # Partitioning a dataset into a seperate training and test set
|
||||
|
||||
# In[30]:
|
||||
|
||||
|
||||
df_wine = pd.read_csv('https://archive.ics.uci.edu/'
|
||||
@@ -349,10 +329,8 @@ print('Class labels', np.unique(df_wine['Class label']))
|
||||
df_wine.head()
|
||||
|
||||
|
||||
# In[31]:
|
||||
|
||||
|
||||
from sklearn.model_selection import train_test_split
|
||||
|
||||
X, y = df_wine.iloc[:, 1:].values, df_wine.iloc[:, 0].values
|
||||
|
||||
@@ -365,20 +343,16 @@ X_train, X_test, y_train, y_test = train_test_split(X, y,
|
||||
|
||||
# # Bringing features onto the same scale
|
||||
|
||||
# In[32]:
|
||||
|
||||
|
||||
from sklearn.preprocessing import MinMaxScaler
|
||||
|
||||
mms = MinMaxScaler()
|
||||
X_train_norm = mms.fit_transform(X_train)
|
||||
X_test_norm = mms.transform(X_test)
|
||||
|
||||
|
||||
# In[33]:
|
||||
|
||||
|
||||
from sklearn.preprocessing import StandardScaler
|
||||
|
||||
stdsc = StandardScaler()
|
||||
X_train_std = stdsc.fit_transform(X_train)
|
||||
@@ -387,7 +361,6 @@ X_test_std = stdsc.transform(X_test)
|
||||
|
||||
# A visual example:
|
||||
|
||||
# In[34]:
|
||||
|
||||
|
||||
ex = np.array([0, 1, 2, 3, 4, 5])
|
||||
@@ -411,38 +384,31 @@ print('normalized:', (ex - ex.min()) / (ex.max() - ex.min()))
|
||||
|
||||
# ## A geometric interpretation of L2 regularization
|
||||
|
||||
# In[35]:
|
||||
|
||||
|
||||
|
||||
|
||||
# In[36]:
|
||||
|
||||
|
||||
|
||||
|
||||
# ## Sparse solutions with L1-regularization
|
||||
|
||||
# In[37]:
|
||||
|
||||
|
||||
|
||||
|
||||
# For regularized models in scikit-learn that support L1 regularization, we can simply set the `penalty` parameter to `'l1'` to obtain a sparse solution:
|
||||
|
||||
# In[38]:
|
||||
|
||||
|
||||
from sklearn.linear_model import LogisticRegression
|
||||
LogisticRegression(penalty='l1')
|
||||
|
||||
|
||||
# Applied to the standardized Wine data ...
|
||||
|
||||
# In[39]:
|
||||
|
||||
|
||||
from sklearn.linear_model import LogisticRegression
|
||||
|
||||
lr = LogisticRegression(penalty='l1', C=1.0)
|
||||
lr.fit(X_train_std, y_train)
|
||||
@@ -450,34 +416,28 @@ print('Training accuracy:', lr.score(X_train_std, y_train))
|
||||
print('Test accuracy:', lr.score(X_test_std, y_test))
|
||||
|
||||
|
||||
# In[40]:
|
||||
|
||||
|
||||
lr.intercept_
|
||||
|
||||
|
||||
# In[41]:
|
||||
|
||||
|
||||
np.set_printoptions(8)
|
||||
|
||||
|
||||
# In[42]:
|
||||
|
||||
|
||||
lr.coef_[lr.coef_!=0].shape
|
||||
|
||||
|
||||
# In[43]:
|
||||
|
||||
|
||||
lr.coef_
|
||||
|
||||
|
||||
# In[44]:
|
||||
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
fig = plt.figure()
|
||||
ax = plt.subplot(111)
|
||||
@@ -517,14 +477,8 @@ plt.show()
|
||||
|
||||
# ## Sequential feature selection algorithms
|
||||
|
||||
# In[45]:
|
||||
|
||||
|
||||
from sklearn.base import clone
|
||||
from itertools import combinations
|
||||
import numpy as np
|
||||
from sklearn.metrics import accuracy_score
|
||||
from sklearn.model_selection import train_test_split
|
||||
|
||||
|
||||
class SBS():
|
||||
@@ -578,11 +532,8 @@ class SBS():
|
||||
return score
|
||||
|
||||
|
||||
# In[46]:
|
||||
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
from sklearn.neighbors import KNeighborsClassifier
|
||||
|
||||
knn = KNeighborsClassifier(n_neighbors=5)
|
||||
|
||||
@@ -603,14 +554,12 @@ plt.tight_layout()
|
||||
plt.show()
|
||||
|
||||
|
||||
# In[47]:
|
||||
|
||||
|
||||
k3 = list(sbs.subsets_[10])
|
||||
print(df_wine.columns[1:][k3])
|
||||
|
||||
|
||||
# In[48]:
|
||||
|
||||
|
||||
knn.fit(X_train_std, y_train)
|
||||
@@ -618,7 +567,6 @@ print('Training accuracy:', knn.score(X_train_std, y_train))
|
||||
print('Test accuracy:', knn.score(X_test_std, y_test))
|
||||
|
||||
|
||||
# In[49]:
|
||||
|
||||
|
||||
knn.fit(X_train_std[:, k3], y_train)
|
||||
@@ -629,10 +577,8 @@ print('Test accuracy:', knn.score(X_test_std[:, k3], y_test))
|
||||
|
||||
# # Assessing feature importance with Random Forests
|
||||
|
||||
# In[50]:
|
||||
|
||||
|
||||
from sklearn.ensemble import RandomForestClassifier
|
||||
|
||||
feat_labels = df_wine.columns[1:]
|
||||
|
||||
@@ -662,10 +608,8 @@ plt.tight_layout()
|
||||
plt.show()
|
||||
|
||||
|
||||
# In[51]:
|
||||
|
||||
|
||||
from sklearn.feature_selection import SelectFromModel
|
||||
|
||||
sfm = SelectFromModel(forest, threshold=0.1, prefit=True)
|
||||
X_selected = sfm.transform(X_train)
|
||||
@@ -675,7 +619,6 @@ print('Number of samples that meet this criterion:',
|
||||
|
||||
# Now, let's print the 3 features that met the threshold criterion for feature selection that we set earlier (note that this code snippet does not appear in the actual book but was added to this notebook later for illustrative purposes):
|
||||
|
||||
# In[52]:
|
||||
|
||||
|
||||
for f in range(X_selected.shape[1]):
|
||||
@@ -688,3 +631,11 @@ for f in range(X_selected.shape[1]):
|
||||
# # Summary
|
||||
|
||||
# ...
|
||||
|
||||
# ---
|
||||
#
|
||||
# Readers may ignore the next cell.
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
Python Machine Learning - Code Examples
|
||||
|
||||
|
||||
## Chapter 5: Compressing Data via Dimensionality Reduction
|
||||
|
||||
### Chapter Outline
|
||||
|
||||
- Unsupervised dimensionality reduction via principal component analysis
|
||||
- The main steps behind principal component analysis
|
||||
- Extracting the principal components step by step
|
||||
- Total and explained variance
|
||||
- Feature transformation
|
||||
- Principal component analysis in scikit-learn
|
||||
- Supervised data compression via linear discriminant analysis
|
||||
- Principal component analysis versus linear discriminant analysis
|
||||
- The inner workings of linear discriminant analysis
|
||||
- Computing the scatter matrices
|
||||
- Selecting linear discriminants for the new feature subspace
|
||||
- Projecting samples onto the new feature space
|
||||
- LDA via scikit-learn
|
||||
- Using kernel principal component analysis for nonlinear mappings
|
||||
- Kernel functions and the kernel trick
|
||||
- Implementing a kernel principal component analysis in Python
|
||||
- Example 1 – separating half-moon shapes
|
||||
- Example 2 – separating concentric circles
|
||||
- Projecting new data points
|
||||
- Kernel principal component analysis in scikit-learn
|
||||
- Summary
|
||||
|
||||
### A note on using the code examples
|
||||
|
||||
The recommended way to interact with the code examples in this book is via Jupyter Notebook (the `.ipynb` files). Using Jupyter Notebook, you will be able to execute the code step by step and have all the resulting outputs (including plots and images) all in one convenient document.
|
||||
|
||||

|
||||
|
||||
|
||||
|
||||
Setting up Jupyter Notebook is really easy: if you are using the Anaconda Python distribution, all you need to install jupyter notebook is to execute the following command in your terminal:
|
||||
|
||||
conda install jupyter notebook
|
||||
|
||||
Then you can launch jupyter notebook by executing
|
||||
|
||||
jupyter notebook
|
||||
|
||||
A window will open up in your browser, which you can then use to navigate to the target directory that contains the `.ipynb` file you wish to open.
|
||||
|
||||
**More installation and setup instructions can be found in the [README.md file of Chapter 1](../ch01/README.md)**.
|
||||
|
||||
**(Even if you decide not to install Jupyter Notebook, note that you can also view the notebook files on GitHub by simply clicking on them: [`ch05.ipynb`](ch05.ipynb))**
|
||||
|
||||
In addition to the code examples, I added a table of contents to each Jupyter notebook as well as section headers that are consistent with the content of the book. Also, I included the original images and figures in hope that these make it easier to navigate and work with the code interactively as you are reading the book.
|
||||
|
||||

|
||||
|
||||
|
||||
When I was creating these notebooks, I was hoping to make your reading (and coding) experience as convenient as possible! However, if you don't wish to use Jupyter Notebooks, I also converted these notebooks to regular Python script files (`.py` files) that can be viewed and edited in any plaintext editor.
|
||||
@@ -2125,22 +2125,13 @@
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"[NbConvertApp] Converting notebook ch05.ipynb to script\n",
|
||||
"[NbConvertApp] Writing 27544 bytes to ch05.py\n"
|
||||
"[NbConvertApp] Writing 27705 bytes to ch05.py\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"! python ../.convert_notebook_to_script.py --input ch05.ipynb --output ch05.py"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"collapsed": true
|
||||
},
|
||||
"outputs": [],
|
||||
"source": []
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
|
||||
@@ -1,6 +1,22 @@
|
||||
|
||||
# coding: utf-8
|
||||
|
||||
|
||||
import pandas as pd
|
||||
from sklearn.model_selection import train_test_split
|
||||
from sklearn.preprocessing import StandardScaler
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
from sklearn.decomposition import PCA
|
||||
from matplotlib.colors import ListedColormap
|
||||
from sklearn.linear_model import LogisticRegression
|
||||
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA
|
||||
from scipy.spatial.distance import pdist, squareform
|
||||
from scipy import exp
|
||||
from scipy.linalg import eigh
|
||||
from sklearn.datasets import make_moons
|
||||
from sklearn.datasets import make_circles
|
||||
from sklearn.decomposition import KernelPCA
|
||||
|
||||
# *Python Machine Learning 2nd Edition* by [Sebastian Raschka](https://sebastianraschka.com), Packt Publishing Ltd. 2017
|
||||
#
|
||||
# Code Repository: https://github.com/rasbt/python-machine-learning-book-2nd-edition
|
||||
@@ -13,7 +29,6 @@
|
||||
|
||||
# Note that the optional watermark extension is a small IPython notebook plugin that I developed to make the code reproducible. You can just skip the following line(s).
|
||||
|
||||
# In[1]:
|
||||
|
||||
|
||||
|
||||
@@ -46,27 +61,22 @@
|
||||
# - [Summary](#Summary)
|
||||
|
||||
|
||||
# In[2]:
|
||||
|
||||
|
||||
from IPython.display import Image
|
||||
|
||||
|
||||
# # Unsupervised dimensionality reduction via principal component analysis
|
||||
|
||||
# ## The main steps behind principal component analysis
|
||||
|
||||
# In[3]:
|
||||
|
||||
|
||||
|
||||
|
||||
# ## Extracting the principal components step-by-step
|
||||
|
||||
# In[4]:
|
||||
|
||||
|
||||
import pandas as pd
|
||||
|
||||
df_wine = pd.read_csv('https://archive.ics.uci.edu/ml/'
|
||||
'machine-learning-databases/wine/wine.data',
|
||||
@@ -87,14 +97,11 @@ df_wine.columns = ['Class label', 'Alcohol', 'Malic acid', 'Ash',
|
||||
df_wine.head()
|
||||
|
||||
|
||||
# <hr>
|
||||
|
||||
# Splitting the data into 70% training and 30% test subsets.
|
||||
|
||||
# In[5]:
|
||||
|
||||
|
||||
from sklearn.model_selection import train_test_split
|
||||
|
||||
X, y = df_wine.iloc[:, 1:].values, df_wine.iloc[:, 0].values
|
||||
|
||||
@@ -105,10 +112,8 @@ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3,
|
||||
|
||||
# Standardizing the data.
|
||||
|
||||
# In[6]:
|
||||
|
||||
|
||||
from sklearn.preprocessing import StandardScaler
|
||||
|
||||
sc = StandardScaler()
|
||||
X_train_std = sc.fit_transform(X_train)
|
||||
@@ -161,10 +166,8 @@ X_test_std = sc.transform(X_test)
|
||||
|
||||
# Eigendecomposition of the covariance matrix.
|
||||
|
||||
# In[7]:
|
||||
|
||||
|
||||
import numpy as np
|
||||
cov_mat = np.cov(X_train_std.T)
|
||||
eigen_vals, eigen_vecs = np.linalg.eig(cov_mat)
|
||||
|
||||
@@ -181,7 +184,6 @@ print('\nEigenvalues \n%s' % eigen_vals)
|
||||
|
||||
# ## Total and explained variance
|
||||
|
||||
# In[8]:
|
||||
|
||||
|
||||
tot = sum(eigen_vals)
|
||||
@@ -189,10 +191,8 @@ var_exp = [(i / tot) for i in sorted(eigen_vals, reverse=True)]
|
||||
cum_var_exp = np.cumsum(var_exp)
|
||||
|
||||
|
||||
# In[9]:
|
||||
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
|
||||
plt.bar(range(1, 14), var_exp, alpha=0.5, align='center',
|
||||
@@ -210,7 +210,6 @@ plt.show()
|
||||
|
||||
# ## Feature transformation
|
||||
|
||||
# In[10]:
|
||||
|
||||
|
||||
# Make a list of (eigenvalue, eigenvector) tuples
|
||||
@@ -221,7 +220,6 @@ eigen_pairs = [(np.abs(eigen_vals[i]), eigen_vecs[:, i])
|
||||
eigen_pairs.sort(key=lambda k: k[0], reverse=True)
|
||||
|
||||
|
||||
# In[11]:
|
||||
|
||||
|
||||
w = np.hstack((eigen_pairs[0][1][:, np.newaxis],
|
||||
@@ -240,13 +238,11 @@ print('Matrix W:\n', w)
|
||||
# then $-v$ is also an eigenvector that has the same eigenvalue, since
|
||||
# $$\Sigma \cdot (-v) = -\Sigma v = -\lambda v = \lambda \cdot (-v).$$
|
||||
|
||||
# In[12]:
|
||||
|
||||
|
||||
X_train_std[0].dot(w)
|
||||
|
||||
|
||||
# In[13]:
|
||||
|
||||
|
||||
X_train_pca = X_train_std.dot(w)
|
||||
@@ -273,17 +269,14 @@ plt.show()
|
||||
#
|
||||
# The following four code cells has been added in addition to the content to the book, to illustrate how to replicate the results from our own PCA implementation in scikit-learn:
|
||||
|
||||
# In[14]:
|
||||
|
||||
|
||||
from sklearn.decomposition import PCA
|
||||
|
||||
pca = PCA()
|
||||
X_train_pca = pca.fit_transform(X_train_std)
|
||||
pca.explained_variance_ratio_
|
||||
|
||||
|
||||
# In[15]:
|
||||
|
||||
|
||||
plt.bar(range(1, 14), pca.explained_variance_ratio_, alpha=0.5, align='center')
|
||||
@@ -294,7 +287,6 @@ plt.xlabel('Principal components')
|
||||
plt.show()
|
||||
|
||||
|
||||
# In[16]:
|
||||
|
||||
|
||||
pca = PCA(n_components=2)
|
||||
@@ -302,7 +294,6 @@ X_train_pca = pca.fit_transform(X_train_std)
|
||||
X_test_pca = pca.transform(X_test_std)
|
||||
|
||||
|
||||
# In[17]:
|
||||
|
||||
|
||||
plt.scatter(X_train_pca[:, 0], X_train_pca[:, 1])
|
||||
@@ -311,10 +302,8 @@ plt.ylabel('PC 2')
|
||||
plt.show()
|
||||
|
||||
|
||||
# In[18]:
|
||||
|
||||
|
||||
from matplotlib.colors import ListedColormap
|
||||
|
||||
def plot_decision_regions(X, y, classifier, resolution=0.02):
|
||||
|
||||
@@ -347,10 +336,8 @@ def plot_decision_regions(X, y, classifier, resolution=0.02):
|
||||
|
||||
# Training logistic regression classifier using the first 2 principal components.
|
||||
|
||||
# In[19]:
|
||||
|
||||
|
||||
from sklearn.linear_model import LogisticRegression
|
||||
|
||||
pca = PCA(n_components=2)
|
||||
X_train_pca = pca.fit_transform(X_train_std)
|
||||
@@ -360,7 +347,6 @@ lr = LogisticRegression()
|
||||
lr = lr.fit(X_train_pca, y_train)
|
||||
|
||||
|
||||
# In[20]:
|
||||
|
||||
|
||||
plot_decision_regions(X_train_pca, y_train, classifier=lr)
|
||||
@@ -372,7 +358,6 @@ plt.tight_layout()
|
||||
plt.show()
|
||||
|
||||
|
||||
# In[21]:
|
||||
|
||||
|
||||
plot_decision_regions(X_test_pca, y_test, classifier=lr)
|
||||
@@ -384,7 +369,6 @@ plt.tight_layout()
|
||||
plt.show()
|
||||
|
||||
|
||||
# In[22]:
|
||||
|
||||
|
||||
pca = PCA(n_components=None)
|
||||
@@ -397,7 +381,6 @@ pca.explained_variance_ratio_
|
||||
|
||||
# ## Principal component analysis versus linear discriminant analysis
|
||||
|
||||
# In[4]:
|
||||
|
||||
|
||||
|
||||
@@ -409,7 +392,6 @@ pca.explained_variance_ratio_
|
||||
|
||||
# Calculate the mean vectors for each class:
|
||||
|
||||
# In[24]:
|
||||
|
||||
|
||||
np.set_printoptions(precision=4)
|
||||
@@ -422,7 +404,6 @@ for label in range(1, 4):
|
||||
|
||||
# Compute the within-class scatter matrix:
|
||||
|
||||
# In[25]:
|
||||
|
||||
|
||||
d = 13 # number of features
|
||||
@@ -439,14 +420,12 @@ print('Within-class scatter matrix: %sx%s' % (S_W.shape[0], S_W.shape[1]))
|
||||
|
||||
# Better: covariance matrix since classes are not equally distributed:
|
||||
|
||||
# In[26]:
|
||||
|
||||
|
||||
print('Class label distribution: %s'
|
||||
% np.bincount(y_train)[1:])
|
||||
|
||||
|
||||
# In[27]:
|
||||
|
||||
|
||||
d = 13 # number of features
|
||||
@@ -460,7 +439,6 @@ print('Scaled within-class scatter matrix: %sx%s' % (S_W.shape[0],
|
||||
|
||||
# Compute the between-class scatter matrix:
|
||||
|
||||
# In[28]:
|
||||
|
||||
|
||||
mean_overall = np.mean(X_train_std, axis=0)
|
||||
@@ -480,7 +458,6 @@ print('Between-class scatter matrix: %sx%s' % (S_B.shape[0], S_B.shape[1]))
|
||||
|
||||
# Solve the generalized eigenvalue problem for the matrix $S_W^{-1}S_B$:
|
||||
|
||||
# In[29]:
|
||||
|
||||
|
||||
eigen_vals, eigen_vecs = np.linalg.eig(np.linalg.inv(S_W).dot(S_B))
|
||||
@@ -495,7 +472,6 @@ eigen_vals, eigen_vecs = np.linalg.eig(np.linalg.inv(S_W).dot(S_B))
|
||||
|
||||
# Sort eigenvectors in descending order of the eigenvalues:
|
||||
|
||||
# In[30]:
|
||||
|
||||
|
||||
# Make a list of (eigenvalue, eigenvector) tuples
|
||||
@@ -512,7 +488,6 @@ for eigen_val in eigen_pairs:
|
||||
print(eigen_val[0])
|
||||
|
||||
|
||||
# In[31]:
|
||||
|
||||
|
||||
tot = sum(eigen_vals.real)
|
||||
@@ -532,7 +507,6 @@ plt.tight_layout()
|
||||
plt.show()
|
||||
|
||||
|
||||
# In[32]:
|
||||
|
||||
|
||||
w = np.hstack((eigen_pairs[0][1][:, np.newaxis].real,
|
||||
@@ -543,7 +517,6 @@ print('Matrix W:\n', w)
|
||||
|
||||
# ## Projecting samples onto the new feature space
|
||||
|
||||
# In[33]:
|
||||
|
||||
|
||||
X_train_lda = X_train_std.dot(w)
|
||||
@@ -566,19 +539,15 @@ plt.show()
|
||||
|
||||
# ## LDA via scikit-learn
|
||||
|
||||
# In[34]:
|
||||
|
||||
|
||||
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA
|
||||
|
||||
lda = LDA(n_components=2)
|
||||
X_train_lda = lda.fit_transform(X_train_std, y_train)
|
||||
|
||||
|
||||
# In[35]:
|
||||
|
||||
|
||||
from sklearn.linear_model import LogisticRegression
|
||||
lr = LogisticRegression()
|
||||
lr = lr.fit(X_train_lda, y_train)
|
||||
|
||||
@@ -591,7 +560,6 @@ plt.tight_layout()
|
||||
plt.show()
|
||||
|
||||
|
||||
# In[36]:
|
||||
|
||||
|
||||
X_test_lda = lda.transform(X_test_std)
|
||||
@@ -608,7 +576,6 @@ plt.show()
|
||||
|
||||
# # Using kernel principal component analysis for nonlinear mappings
|
||||
|
||||
# In[5]:
|
||||
|
||||
|
||||
|
||||
@@ -616,13 +583,8 @@ plt.show()
|
||||
|
||||
# ## Implementing a kernel principal component analysis in Python
|
||||
|
||||
# In[38]:
|
||||
|
||||
|
||||
from scipy.spatial.distance import pdist, squareform
|
||||
from scipy import exp
|
||||
from scipy.linalg import eigh
|
||||
import numpy as np
|
||||
|
||||
def rbf_kernel_pca(X, gamma, n_components):
|
||||
"""
|
||||
@@ -674,11 +636,8 @@ def rbf_kernel_pca(X, gamma, n_components):
|
||||
|
||||
# ### Example 1: Separating half-moon shapes
|
||||
|
||||
# In[39]:
|
||||
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
from sklearn.datasets import make_moons
|
||||
|
||||
X, y = make_moons(n_samples=100, random_state=123)
|
||||
|
||||
@@ -690,10 +649,8 @@ plt.tight_layout()
|
||||
plt.show()
|
||||
|
||||
|
||||
# In[40]:
|
||||
|
||||
|
||||
from sklearn.decomposition import PCA
|
||||
|
||||
scikit_pca = PCA(n_components=2)
|
||||
X_spca = scikit_pca.fit_transform(X)
|
||||
@@ -721,7 +678,6 @@ plt.tight_layout()
|
||||
plt.show()
|
||||
|
||||
|
||||
# In[41]:
|
||||
|
||||
|
||||
X_kpca = rbf_kernel_pca(X, gamma=15, n_components=2)
|
||||
@@ -751,10 +707,8 @@ plt.show()
|
||||
|
||||
# ### Example 2: Separating concentric circles
|
||||
|
||||
# In[42]:
|
||||
|
||||
|
||||
from sklearn.datasets import make_circles
|
||||
|
||||
X, y = make_circles(n_samples=1000, random_state=123, noise=0.1, factor=0.2)
|
||||
|
||||
@@ -766,7 +720,6 @@ plt.tight_layout()
|
||||
plt.show()
|
||||
|
||||
|
||||
# In[43]:
|
||||
|
||||
|
||||
scikit_pca = PCA(n_components=2)
|
||||
@@ -795,7 +748,6 @@ plt.tight_layout()
|
||||
plt.show()
|
||||
|
||||
|
||||
# In[44]:
|
||||
|
||||
|
||||
X_kpca = rbf_kernel_pca(X, gamma=15, n_components=2)
|
||||
@@ -825,13 +777,8 @@ plt.show()
|
||||
|
||||
# ## Projecting new data points
|
||||
|
||||
# In[45]:
|
||||
|
||||
|
||||
from scipy.spatial.distance import pdist, squareform
|
||||
from scipy import exp
|
||||
from scipy.linalg import eigh
|
||||
import numpy as np
|
||||
|
||||
def rbf_kernel_pca(X, gamma, n_components):
|
||||
"""
|
||||
@@ -886,28 +833,24 @@ def rbf_kernel_pca(X, gamma, n_components):
|
||||
return alphas, lambdas
|
||||
|
||||
|
||||
# In[46]:
|
||||
|
||||
|
||||
X, y = make_moons(n_samples=100, random_state=123)
|
||||
alphas, lambdas = rbf_kernel_pca(X, gamma=15, n_components=1)
|
||||
|
||||
|
||||
# In[47]:
|
||||
|
||||
|
||||
x_new = X[25]
|
||||
x_new
|
||||
|
||||
|
||||
# In[48]:
|
||||
|
||||
|
||||
x_proj = alphas[25] # original projection
|
||||
x_proj
|
||||
|
||||
|
||||
# In[49]:
|
||||
|
||||
|
||||
def project_x(x_new, X, gamma, alphas, lambdas):
|
||||
@@ -920,7 +863,6 @@ x_reproj = project_x(x_new, X, gamma=15, alphas=alphas, lambdas=lambdas)
|
||||
x_reproj
|
||||
|
||||
|
||||
# In[50]:
|
||||
|
||||
|
||||
plt.scatter(alphas[y == 0, 0], np.zeros((50)),
|
||||
@@ -941,10 +883,8 @@ plt.show()
|
||||
|
||||
# ## Kernel principal component analysis in scikit-learn
|
||||
|
||||
# In[51]:
|
||||
|
||||
|
||||
from sklearn.decomposition import KernelPCA
|
||||
|
||||
X, y = make_moons(n_samples=100, random_state=123)
|
||||
scikit_kpca = KernelPCA(n_components=2, kernel='rbf', gamma=15)
|
||||
@@ -966,3 +906,11 @@ plt.show()
|
||||
# # Summary
|
||||
|
||||
# ...
|
||||
|
||||
# ---
|
||||
#
|
||||
# Readers may ignore the next cell.
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
Python Machine Learning - Code Examples
|
||||
|
||||
|
||||
## Chapter 6: Learning Best Practices for Model Evaluation and Hyperparameter Tuning
|
||||
|
||||
### Chapter Outline
|
||||
|
||||
- Streamlining workflows with pipelines
|
||||
- Loading the Breast Cancer Wisconsin dataset
|
||||
- Combining transformers and estimators in a pipeline
|
||||
- Using k-fold cross-validation to assess model performance
|
||||
- The holdout method
|
||||
- K-fold cross-validation
|
||||
- Debugging algorithms with learning and validation curves
|
||||
- Diagnosing bias and variance problems with learning curves
|
||||
- Addressing over- and underfitting with validation curves
|
||||
- Fine-tuning machine learning models via grid search
|
||||
- Tuning hyperparameters via grid search
|
||||
- Algorithm selection with nested cross-validation
|
||||
- Looking at different performance evaluation metrics
|
||||
- Reading a confusion matrix
|
||||
- Optimizing the precision and recall of a classification model
|
||||
- Plotting a receiver operating characteristic
|
||||
- Scoring metrics for multiclass classification
|
||||
- Dealing with class imbalance
|
||||
- Summary
|
||||
|
||||
### A note on using the code examples
|
||||
|
||||
The recommended way to interact with the code examples in this book is via Jupyter Notebook (the `.ipynb` files). Using Jupyter Notebook, you will be able to execute the code step by step and have all the resulting outputs (including plots and images) all in one convenient document.
|
||||
|
||||

|
||||
|
||||
|
||||
|
||||
Setting up Jupyter Notebook is really easy: if you are using the Anaconda Python distribution, all you need to install jupyter notebook is to execute the following command in your terminal:
|
||||
|
||||
conda install jupyter notebook
|
||||
|
||||
Then you can launch jupyter notebook by executing
|
||||
|
||||
jupyter notebook
|
||||
|
||||
A window will open up in your browser, which you can then use to navigate to the target directory that contains the `.ipynb` file you wish to open.
|
||||
|
||||
**More installation and setup instructions can be found in the [README.md file of Chapter 1](../ch01/README.md)**.
|
||||
|
||||
**(Even if you decide not to install Jupyter Notebook, note that you can also view the notebook files on GitHub by simply clicking on them: [`ch06.ipynb`](ch06.ipynb))**
|
||||
|
||||
In addition to the code examples, I added a table of contents to each Jupyter notebook as well as section headers that are consistent with the content of the book. Also, I included the original images and figures in hope that these make it easier to navigate and work with the code interactively as you are reading the book.
|
||||
|
||||

|
||||
|
||||
|
||||
When I was creating these notebooks, I was hoping to make your reading (and coding) experience as convenient as possible! However, if you don't wish to use Jupyter Notebooks, I also converted these notebooks to regular Python script files (`.py` files) that can be viewed and edited in any plaintext editor.
|
||||
@@ -1635,7 +1635,7 @@
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"[NbConvertApp] Converting notebook ch06.ipynb to script\n",
|
||||
"[NbConvertApp] Writing 16998 bytes to ch06.py\n"
|
||||
"[NbConvertApp] Writing 16984 bytes to ch06.py\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
|
||||
@@ -1,6 +1,29 @@
|
||||
|
||||
# coding: utf-8
|
||||
|
||||
|
||||
import pandas as pd
|
||||
from sklearn.preprocessing import LabelEncoder
|
||||
from sklearn.model_selection import train_test_split
|
||||
from sklearn.preprocessing import StandardScaler
|
||||
from sklearn.decomposition import PCA
|
||||
from sklearn.linear_model import LogisticRegression
|
||||
from sklearn.pipeline import make_pipeline
|
||||
import numpy as np
|
||||
from sklearn.model_selection import StratifiedKFold
|
||||
from sklearn.model_selection import cross_val_score
|
||||
import matplotlib.pyplot as plt
|
||||
from sklearn.model_selection import learning_curve
|
||||
from sklearn.model_selection import validation_curve
|
||||
from sklearn.model_selection import GridSearchCV
|
||||
from sklearn.svm import SVC
|
||||
from sklearn.tree import DecisionTreeClassifier
|
||||
from sklearn.metrics import confusion_matrix
|
||||
from sklearn.metrics import precision_score, recall_score, f1_score
|
||||
from sklearn.metrics import make_scorer
|
||||
from sklearn.metrics import roc_curve, auc
|
||||
from scipy import interp
|
||||
from sklearn.utils import resample
|
||||
|
||||
# *Python Machine Learning 2nd Edition* by [Sebastian Raschka](https://sebastianraschka.com), Packt Publishing Ltd. 2017
|
||||
#
|
||||
# Code Repository: https://github.com/rasbt/python-machine-learning-book-2nd-edition
|
||||
@@ -13,7 +36,6 @@
|
||||
|
||||
# Note that the optional watermark extension is a small IPython notebook plugin that I developed to make the code reproducible. You can just skip the following line(s).
|
||||
|
||||
# In[1]:
|
||||
|
||||
|
||||
|
||||
@@ -44,10 +66,8 @@
|
||||
# - [Summary](#Summary)
|
||||
|
||||
|
||||
# In[2]:
|
||||
|
||||
|
||||
from IPython.display import Image
|
||||
|
||||
|
||||
# # Streamlining workflows with pipelines
|
||||
@@ -56,10 +76,8 @@ from IPython.display import Image
|
||||
|
||||
# ## Loading the Breast Cancer Wisconsin dataset
|
||||
|
||||
# In[3]:
|
||||
|
||||
|
||||
import pandas as pd
|
||||
|
||||
df = pd.read_csv('https://archive.ics.uci.edu/ml/'
|
||||
'machine-learning-databases'
|
||||
@@ -74,18 +92,14 @@ df = pd.read_csv('https://archive.ics.uci.edu/ml/'
|
||||
df.head()
|
||||
|
||||
|
||||
# In[4]:
|
||||
|
||||
|
||||
df.shape
|
||||
|
||||
|
||||
# <hr>
|
||||
|
||||
# In[5]:
|
||||
|
||||
|
||||
from sklearn.preprocessing import LabelEncoder
|
||||
|
||||
|
||||
X = df.loc[:, 2:].values
|
||||
y = df.loc[:, 1].values
|
||||
@@ -94,16 +108,13 @@ y = le.fit_transform(y)
|
||||
le.classes_
|
||||
|
||||
|
||||
# In[6]:
|
||||
|
||||
|
||||
le.transform(['M', 'B'])
|
||||
|
||||
|
||||
# In[7]:
|
||||
|
||||
|
||||
from sklearn.model_selection import train_test_split
|
||||
|
||||
X_train, X_test, y_train, y_test = train_test_split(X, y,
|
||||
test_size=0.20,
|
||||
@@ -114,13 +125,8 @@ X_train, X_test, y_train, y_test = train_test_split(X, y,
|
||||
|
||||
# ## Combining transformers and estimators in a pipeline
|
||||
|
||||
# In[8]:
|
||||
|
||||
|
||||
from sklearn.preprocessing import StandardScaler
|
||||
from sklearn.decomposition import PCA
|
||||
from sklearn.linear_model import LogisticRegression
|
||||
from sklearn.pipeline import make_pipeline
|
||||
|
||||
pipe_lr = make_pipeline(StandardScaler(),
|
||||
PCA(n_components=2),
|
||||
@@ -131,7 +137,6 @@ y_pred = pipe_lr.predict(X_test)
|
||||
print('Test Accuracy: %.3f' % pipe_lr.score(X_test, y_test))
|
||||
|
||||
|
||||
# In[9]:
|
||||
|
||||
|
||||
|
||||
@@ -143,7 +148,6 @@ print('Test Accuracy: %.3f' % pipe_lr.score(X_test, y_test))
|
||||
|
||||
# ## The holdout method
|
||||
|
||||
# In[10]:
|
||||
|
||||
|
||||
|
||||
@@ -151,16 +155,12 @@ print('Test Accuracy: %.3f' % pipe_lr.score(X_test, y_test))
|
||||
|
||||
# ## K-fold cross-validation
|
||||
|
||||
# In[11]:
|
||||
|
||||
|
||||
|
||||
|
||||
# In[12]:
|
||||
|
||||
|
||||
import numpy as np
|
||||
from sklearn.model_selection import StratifiedKFold
|
||||
|
||||
|
||||
kfold = StratifiedKFold(n_splits=10,
|
||||
@@ -177,10 +177,8 @@ for k, (train, test) in enumerate(kfold):
|
||||
print('\nCV accuracy: %.3f +/- %.3f' % (np.mean(scores), np.std(scores)))
|
||||
|
||||
|
||||
# In[13]:
|
||||
|
||||
|
||||
from sklearn.model_selection import cross_val_score
|
||||
|
||||
scores = cross_val_score(estimator=pipe_lr,
|
||||
X=X_train,
|
||||
@@ -197,16 +195,12 @@ print('CV accuracy: %.3f +/- %.3f' % (np.mean(scores), np.std(scores)))
|
||||
|
||||
# ## Diagnosing bias and variance problems with learning curves
|
||||
|
||||
# In[14]:
|
||||
|
||||
|
||||
|
||||
|
||||
# In[15]:
|
||||
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
from sklearn.model_selection import learning_curve
|
||||
|
||||
|
||||
pipe_lr = make_pipeline(StandardScaler(),
|
||||
@@ -256,10 +250,8 @@ plt.show()
|
||||
|
||||
# ## Addressing over- and underfitting with validation curves
|
||||
|
||||
# In[16]:
|
||||
|
||||
|
||||
from sklearn.model_selection import validation_curve
|
||||
|
||||
|
||||
param_range = [0.001, 0.01, 0.1, 1.0, 10.0, 100.0]
|
||||
@@ -311,11 +303,8 @@ plt.show()
|
||||
|
||||
# ## Tuning hyperparameters via grid search
|
||||
|
||||
# In[17]:
|
||||
|
||||
|
||||
from sklearn.model_selection import GridSearchCV
|
||||
from sklearn.svm import SVC
|
||||
|
||||
pipe_svc = make_pipeline(StandardScaler(),
|
||||
SVC(random_state=1))
|
||||
@@ -338,7 +327,6 @@ print(gs.best_score_)
|
||||
print(gs.best_params_)
|
||||
|
||||
|
||||
# In[18]:
|
||||
|
||||
|
||||
clf = gs.best_estimator_
|
||||
@@ -349,12 +337,10 @@ print('Test accuracy: %.3f' % clf.score(X_test, y_test))
|
||||
|
||||
# ## Algorithm selection with nested cross-validation
|
||||
|
||||
# In[19]:
|
||||
|
||||
|
||||
|
||||
|
||||
# In[20]:
|
||||
|
||||
|
||||
gs = GridSearchCV(estimator=pipe_svc,
|
||||
@@ -368,10 +354,8 @@ print('CV accuracy: %.3f +/- %.3f' % (np.mean(scores),
|
||||
np.std(scores)))
|
||||
|
||||
|
||||
# In[21]:
|
||||
|
||||
|
||||
from sklearn.tree import DecisionTreeClassifier
|
||||
|
||||
gs = GridSearchCV(estimator=DecisionTreeClassifier(random_state=0),
|
||||
param_grid=[{'max_depth': [1, 2, 3, 4, 5, 6, 7, None]}],
|
||||
@@ -391,15 +375,12 @@ print('CV accuracy: %.3f +/- %.3f' % (np.mean(scores),
|
||||
|
||||
# ## Reading a confusion matrix
|
||||
|
||||
# In[22]:
|
||||
|
||||
|
||||
|
||||
|
||||
# In[23]:
|
||||
|
||||
|
||||
from sklearn.metrics import confusion_matrix
|
||||
|
||||
pipe_svc.fit(X_train, y_train)
|
||||
y_pred = pipe_svc.predict(X_test)
|
||||
@@ -407,7 +388,6 @@ confmat = confusion_matrix(y_true=y_test, y_pred=y_pred)
|
||||
print(confmat)
|
||||
|
||||
|
||||
# In[24]:
|
||||
|
||||
|
||||
fig, ax = plt.subplots(figsize=(2.5, 2.5))
|
||||
@@ -428,13 +408,11 @@ plt.show()
|
||||
|
||||
# Remember that we previously encoded the class labels so that *malignant* samples are the "postive" class (1), and *benign* samples are the "negative" class (0):
|
||||
|
||||
# In[25]:
|
||||
|
||||
|
||||
le.transform(['M', 'B'])
|
||||
|
||||
|
||||
# In[26]:
|
||||
|
||||
|
||||
confmat = confusion_matrix(y_true=y_test, y_pred=y_pred)
|
||||
@@ -443,7 +421,6 @@ print(confmat)
|
||||
|
||||
# Next, we printed the confusion matrix like so:
|
||||
|
||||
# In[27]:
|
||||
|
||||
|
||||
confmat = confusion_matrix(y_true=y_test, y_pred=y_pred)
|
||||
@@ -452,7 +429,6 @@ print(confmat)
|
||||
|
||||
# Note that the (true) class 0 samples that are correctly predicted as class 0 (true negatives) are now in the upper left corner of the matrix (index 0, 0). In order to change the ordering so that the true negatives are in the lower right corner (index 1,1) and the true positves are in the upper left, we can use the `labels` argument like shown below:
|
||||
|
||||
# In[28]:
|
||||
|
||||
|
||||
confmat = confusion_matrix(y_true=y_test, y_pred=y_pred, labels=[1, 0])
|
||||
@@ -466,20 +442,16 @@ print(confmat)
|
||||
|
||||
# ## Optimizing the precision and recall of a classification model
|
||||
|
||||
# In[29]:
|
||||
|
||||
|
||||
from sklearn.metrics import precision_score, recall_score, f1_score
|
||||
|
||||
print('Precision: %.3f' % precision_score(y_true=y_test, y_pred=y_pred))
|
||||
print('Recall: %.3f' % recall_score(y_true=y_test, y_pred=y_pred))
|
||||
print('F1: %.3f' % f1_score(y_true=y_test, y_pred=y_pred))
|
||||
|
||||
|
||||
# In[30]:
|
||||
|
||||
|
||||
from sklearn.metrics import make_scorer
|
||||
|
||||
scorer = make_scorer(f1_score, pos_label=0)
|
||||
|
||||
@@ -504,11 +476,8 @@ print(gs.best_params_)
|
||||
|
||||
# ## Plotting a receiver operating characteristic
|
||||
|
||||
# In[31]:
|
||||
|
||||
|
||||
from sklearn.metrics import roc_curve, auc
|
||||
from scipy import interp
|
||||
|
||||
pipe_lr = make_pipeline(StandardScaler(),
|
||||
PCA(n_components=2),
|
||||
@@ -574,7 +543,6 @@ plt.show()
|
||||
|
||||
# ## The scoring metrics for multiclass classification
|
||||
|
||||
# In[32]:
|
||||
|
||||
|
||||
pre_scorer = make_scorer(score_func=precision_score,
|
||||
@@ -585,24 +553,20 @@ pre_scorer = make_scorer(score_func=precision_score,
|
||||
|
||||
# ## Dealing with class imbalance
|
||||
|
||||
# In[33]:
|
||||
|
||||
|
||||
X_imb = np.vstack((X[y == 0], X[y == 1][:40]))
|
||||
y_imb = np.hstack((y[y == 0], y[y == 1][:40]))
|
||||
|
||||
|
||||
# In[34]:
|
||||
|
||||
|
||||
y_pred = np.zeros(y_imb.shape[0])
|
||||
np.mean(y_pred == y_imb) * 100
|
||||
|
||||
|
||||
# In[35]:
|
||||
|
||||
|
||||
from sklearn.utils import resample
|
||||
|
||||
print('Number of class 1 samples before:', X_imb[y_imb == 1].shape[0])
|
||||
|
||||
@@ -615,14 +579,12 @@ X_upsampled, y_upsampled = resample(X_imb[y_imb == 1],
|
||||
print('Number of class 1 samples after:', X_upsampled.shape[0])
|
||||
|
||||
|
||||
# In[36]:
|
||||
|
||||
|
||||
X_bal = np.vstack((X[y == 0], X_upsampled))
|
||||
y_bal = np.hstack((y[y == 0], y_upsampled))
|
||||
|
||||
|
||||
# In[37]:
|
||||
|
||||
|
||||
y_pred = np.zeros(y_bal.shape[0])
|
||||
@@ -638,13 +600,6 @@ np.mean(y_pred == y_bal) * 100
|
||||
#
|
||||
# Readers may ignore the next cell.
|
||||
|
||||
# In[ ]:
|
||||
|
||||
|
||||
|
||||
|
||||
# In[ ]:
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
Python Machine Learning - Code Examples
|
||||
|
||||
|
||||
## Chapter 7: Combining Different Models for Ensemble Learning
|
||||
|
||||
### Chapter Outline
|
||||
|
||||
- Learning with ensembles
|
||||
- Combining classifiers via majority vote
|
||||
- Implementing a simple majority vote classifier
|
||||
- Using the majority voting principle to make predictions
|
||||
- Evaluating and tuning the ensemble classifier
|
||||
- Bagging – building an ensemble of classifiers from bootstrap samples
|
||||
- Bagging in a nutshell
|
||||
- Applying bagging to classify samples in the Wine dataset
|
||||
- Leveraging weak learners via adaptive boosting
|
||||
- How boosting works
|
||||
- Applying AdaBoost using scikit-learn
|
||||
- Summary
|
||||
|
||||
### A note on using the code examples
|
||||
|
||||
The recommended way to interact with the code examples in this book is via Jupyter Notebook (the `.ipynb` files). Using Jupyter Notebook, you will be able to execute the code step by step and have all the resulting outputs (including plots and images) all in one convenient document.
|
||||
|
||||

|
||||
|
||||
|
||||
|
||||
Setting up Jupyter Notebook is really easy: if you are using the Anaconda Python distribution, all you need to install jupyter notebook is to execute the following command in your terminal:
|
||||
|
||||
conda install jupyter notebook
|
||||
|
||||
Then you can launch jupyter notebook by executing
|
||||
|
||||
jupyter notebook
|
||||
|
||||
A window will open up in your browser, which you can then use to navigate to the target directory that contains the `.ipynb` file you wish to open.
|
||||
|
||||
**More installation and setup instructions can be found in the [README.md file of Chapter 1](../ch01/README.md)**.
|
||||
|
||||
**(Even if you decide not to install Jupyter Notebook, note that you can also view the notebook files on GitHub by simply clicking on them: [`ch07.ipynb`](ch07.ipynb))**
|
||||
|
||||
In addition to the code examples, I added a table of contents to each Jupyter notebook as well as section headers that are consistent with the content of the book. Also, I included the original images and figures in hope that these make it easier to navigate and work with the code interactively as you are reading the book.
|
||||
|
||||

|
||||
|
||||
|
||||
When I was creating these notebooks, I was hoping to make your reading (and coding) experience as convenient as possible! However, if you don't wish to use Jupyter Notebooks, I also converted these notebooks to regular Python script files (`.py` files) that can be viewed and edited in any plaintext editor.
|
||||
@@ -1542,7 +1542,7 @@
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"[NbConvertApp] Converting notebook ch07.ipynb to script\n",
|
||||
"[NbConvertApp] Writing 21930 bytes to ch07.py\n"
|
||||
"[NbConvertApp] Writing 22091 bytes to ch07.py\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
|
||||
@@ -1,6 +1,34 @@
|
||||
|
||||
# coding: utf-8
|
||||
|
||||
|
||||
from scipy.misc import comb
|
||||
import math
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
from sklearn.base import BaseEstimator
|
||||
from sklearn.base import ClassifierMixin
|
||||
from sklearn.preprocessing import LabelEncoder
|
||||
from sklearn.externals import six
|
||||
from sklearn.base import clone
|
||||
from sklearn.pipeline import _name_estimators
|
||||
import operator
|
||||
from sklearn import datasets
|
||||
from sklearn.preprocessing import StandardScaler
|
||||
from sklearn.model_selection import train_test_split
|
||||
from sklearn.linear_model import LogisticRegression
|
||||
from sklearn.tree import DecisionTreeClassifier
|
||||
from sklearn.neighbors import KNeighborsClassifier
|
||||
from sklearn.pipeline import Pipeline
|
||||
from sklearn.model_selection import cross_val_score
|
||||
from sklearn.metrics import roc_curve
|
||||
from sklearn.metrics import auc
|
||||
from itertools import product
|
||||
from sklearn.model_selection import GridSearchCV
|
||||
import pandas as pd
|
||||
from sklearn.ensemble import BaggingClassifier
|
||||
from sklearn.metrics import accuracy_score
|
||||
from sklearn.ensemble import AdaBoostClassifier
|
||||
|
||||
# *Python Machine Learning 2nd Edition* by [Sebastian Raschka](https://sebastianraschka.com), Packt Publishing Ltd. 2017
|
||||
#
|
||||
# Code Repository: https://github.com/rasbt/python-machine-learning-book-2nd-edition
|
||||
@@ -13,7 +41,6 @@
|
||||
|
||||
# Note that the optional watermark extension is a small IPython notebook plugin that I developed to make the code reproducible. You can just skip the following line(s).
|
||||
|
||||
# In[1]:
|
||||
|
||||
|
||||
|
||||
@@ -37,29 +64,22 @@
|
||||
# - [Summary](#Summary)
|
||||
|
||||
|
||||
# In[1]:
|
||||
|
||||
|
||||
from IPython.display import Image
|
||||
|
||||
|
||||
# # Learning with ensembles
|
||||
|
||||
# In[2]:
|
||||
|
||||
|
||||
|
||||
|
||||
# In[3]:
|
||||
|
||||
|
||||
|
||||
|
||||
# In[5]:
|
||||
|
||||
|
||||
from scipy.misc import comb
|
||||
import math
|
||||
|
||||
def ensemble_error(n_classifier, error):
|
||||
k_start = int(math.ceil(n_classifier / 2.))
|
||||
@@ -68,26 +88,21 @@ def ensemble_error(n_classifier, error):
|
||||
return sum(probs)
|
||||
|
||||
|
||||
# In[6]:
|
||||
|
||||
|
||||
ensemble_error(n_classifier=11, error=0.25)
|
||||
|
||||
|
||||
# In[7]:
|
||||
|
||||
|
||||
import numpy as np
|
||||
|
||||
error_range = np.arange(0.0, 1.01, 0.01)
|
||||
ens_errors = [ensemble_error(n_classifier=11, error=error)
|
||||
for error in error_range]
|
||||
|
||||
|
||||
# In[8]:
|
||||
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
plt.plot(error_range,
|
||||
ens_errors,
|
||||
@@ -113,16 +128,13 @@ plt.show()
|
||||
|
||||
# ## Implementing a simple majority vote classifier
|
||||
|
||||
# In[9]:
|
||||
|
||||
|
||||
import numpy as np
|
||||
|
||||
np.argmax(np.bincount([0, 0, 1],
|
||||
weights=[0.2, 0.2, 0.6]))
|
||||
|
||||
|
||||
# In[10]:
|
||||
|
||||
|
||||
ex = np.array([[0.9, 0.1],
|
||||
@@ -135,23 +147,13 @@ p = np.average(ex,
|
||||
p
|
||||
|
||||
|
||||
# In[11]:
|
||||
|
||||
|
||||
np.argmax(p)
|
||||
|
||||
|
||||
# In[12]:
|
||||
|
||||
|
||||
from sklearn.base import BaseEstimator
|
||||
from sklearn.base import ClassifierMixin
|
||||
from sklearn.preprocessing import LabelEncoder
|
||||
from sklearn.externals import six
|
||||
from sklearn.base import clone
|
||||
from sklearn.pipeline import _name_estimators
|
||||
import numpy as np
|
||||
import operator
|
||||
|
||||
|
||||
class MajorityVoteClassifier(BaseEstimator,
|
||||
@@ -285,13 +287,8 @@ class MajorityVoteClassifier(BaseEstimator,
|
||||
|
||||
# ## Using the majority voting principle to make predictions
|
||||
|
||||
# In[13]:
|
||||
|
||||
|
||||
from sklearn import datasets
|
||||
from sklearn.preprocessing import StandardScaler
|
||||
from sklearn.preprocessing import LabelEncoder
|
||||
from sklearn.model_selection import train_test_split
|
||||
|
||||
iris = datasets.load_iris()
|
||||
X, y = iris.data[50:, [1, 2]], iris.target[50:]
|
||||
@@ -304,15 +301,8 @@ X_train, X_test, y_train, y_test = train_test_split(X, y,
|
||||
stratify=y)
|
||||
|
||||
|
||||
# In[14]:
|
||||
|
||||
|
||||
import numpy as np
|
||||
from sklearn.linear_model import LogisticRegression
|
||||
from sklearn.tree import DecisionTreeClassifier
|
||||
from sklearn.neighbors import KNeighborsClassifier
|
||||
from sklearn.pipeline import Pipeline
|
||||
from sklearn.model_selection import cross_val_score
|
||||
|
||||
clf1 = LogisticRegression(penalty='l2',
|
||||
C=0.001,
|
||||
@@ -344,7 +334,6 @@ for clf, label in zip([pipe1, clf2, pipe3], clf_labels):
|
||||
% (scores.mean(), scores.std(), label))
|
||||
|
||||
|
||||
# In[15]:
|
||||
|
||||
|
||||
# Majority Rule (hard) Voting
|
||||
@@ -367,11 +356,8 @@ for clf, label in zip(all_clf, clf_labels):
|
||||
|
||||
# # Evaluating and tuning the ensemble classifier
|
||||
|
||||
# In[16]:
|
||||
|
||||
|
||||
from sklearn.metrics import roc_curve
|
||||
from sklearn.metrics import auc
|
||||
|
||||
colors = ['black', 'orange', 'blue', 'green']
|
||||
linestyles = [':', '--', '-.', '-']
|
||||
@@ -406,17 +392,14 @@ plt.ylabel('True positive rate (TPR)')
|
||||
plt.show()
|
||||
|
||||
|
||||
# In[17]:
|
||||
|
||||
|
||||
sc = StandardScaler()
|
||||
X_train_std = sc.fit_transform(X_train)
|
||||
|
||||
|
||||
# In[18]:
|
||||
|
||||
|
||||
from itertools import product
|
||||
|
||||
all_clf = [pipe1, clf2, pipe3, mv_clf]
|
||||
|
||||
@@ -468,16 +451,13 @@ plt.text(-12.5, 4.5,
|
||||
plt.show()
|
||||
|
||||
|
||||
# In[19]:
|
||||
|
||||
|
||||
mv_clf.get_params()
|
||||
|
||||
|
||||
# In[20]:
|
||||
|
||||
|
||||
from sklearn.model_selection import GridSearchCV
|
||||
|
||||
params = {'decisiontreeclassifier__max_depth': [1, 2],
|
||||
'pipeline-1__clf__C': [0.001, 0.1, 100.0]}
|
||||
@@ -495,7 +475,6 @@ for r, _ in enumerate(grid.cv_results_['mean_test_score']):
|
||||
grid.cv_results_['params'][r]))
|
||||
|
||||
|
||||
# In[21]:
|
||||
|
||||
|
||||
print('Best parameters: %s' % grid.best_params_)
|
||||
@@ -514,25 +493,21 @@ print('Accuracy: %.2f' % grid.best_score_)
|
||||
#
|
||||
# In addition, the "best" estimator can directly be accessed via the `best_estimator_` attribute.
|
||||
|
||||
# In[22]:
|
||||
|
||||
|
||||
grid.best_estimator_.classifiers
|
||||
|
||||
|
||||
# In[23]:
|
||||
|
||||
|
||||
mv_clf = grid.best_estimator_
|
||||
|
||||
|
||||
# In[24]:
|
||||
|
||||
|
||||
mv_clf.set_params(**grid.best_estimator_.get_params())
|
||||
|
||||
|
||||
# In[25]:
|
||||
|
||||
|
||||
mv_clf
|
||||
@@ -541,24 +516,20 @@ mv_clf
|
||||
|
||||
# # Bagging -- Building an ensemble of classifiers from bootstrap samples
|
||||
|
||||
# In[4]:
|
||||
|
||||
|
||||
|
||||
|
||||
# ## Bagging in a nutshell
|
||||
|
||||
# In[28]:
|
||||
|
||||
|
||||
|
||||
|
||||
# ## Applying bagging to classify samples in the Wine dataset
|
||||
|
||||
# In[29]:
|
||||
|
||||
|
||||
import pandas as pd
|
||||
|
||||
df_wine = pd.read_csv('https://archive.ics.uci.edu/ml/'
|
||||
'machine-learning-databases/wine/wine.data',
|
||||
@@ -583,11 +554,8 @@ y = df_wine['Class label'].values
|
||||
X = df_wine[['Alcohol', 'OD280/OD315 of diluted wines']].values
|
||||
|
||||
|
||||
# In[30]:
|
||||
|
||||
|
||||
from sklearn.preprocessing import LabelEncoder
|
||||
from sklearn.model_selection import train_test_split
|
||||
|
||||
|
||||
le = LabelEncoder()
|
||||
@@ -599,11 +567,8 @@ X_train, X_test, y_train, y_test = train_test_split(X, y,
|
||||
stratify=y)
|
||||
|
||||
|
||||
# In[31]:
|
||||
|
||||
|
||||
from sklearn.ensemble import BaggingClassifier
|
||||
from sklearn.tree import DecisionTreeClassifier
|
||||
|
||||
tree = DecisionTreeClassifier(criterion='entropy',
|
||||
max_depth=None,
|
||||
@@ -619,10 +584,8 @@ bag = BaggingClassifier(base_estimator=tree,
|
||||
random_state=1)
|
||||
|
||||
|
||||
# In[32]:
|
||||
|
||||
|
||||
from sklearn.metrics import accuracy_score
|
||||
|
||||
tree = tree.fit(X_train, y_train)
|
||||
y_train_pred = tree.predict(X_train)
|
||||
@@ -643,11 +606,8 @@ print('Bagging train/test accuracies %.3f/%.3f'
|
||||
% (bag_train, bag_test))
|
||||
|
||||
|
||||
# In[33]:
|
||||
|
||||
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
x_min = X_train[:, 0].min() - 1
|
||||
x_max = X_train[:, 0].max() + 1
|
||||
@@ -697,22 +657,18 @@ plt.show()
|
||||
|
||||
# ## How boosting works
|
||||
|
||||
# In[34]:
|
||||
|
||||
|
||||
|
||||
|
||||
# In[35]:
|
||||
|
||||
|
||||
|
||||
|
||||
# ## Applying AdaBoost using scikit-learn
|
||||
|
||||
# In[36]:
|
||||
|
||||
|
||||
from sklearn.ensemble import AdaBoostClassifier
|
||||
|
||||
tree = DecisionTreeClassifier(criterion='entropy',
|
||||
max_depth=1,
|
||||
@@ -724,7 +680,6 @@ ada = AdaBoostClassifier(base_estimator=tree,
|
||||
random_state=1)
|
||||
|
||||
|
||||
# In[37]:
|
||||
|
||||
|
||||
tree = tree.fit(X_train, y_train)
|
||||
@@ -746,7 +701,6 @@ print('AdaBoost train/test accuracies %.3f/%.3f'
|
||||
% (ada_train, ada_test))
|
||||
|
||||
|
||||
# In[38]:
|
||||
|
||||
|
||||
x_min, x_max = X_train[:, 0].min() - 1, X_train[:, 0].max() + 1
|
||||
@@ -788,3 +742,11 @@ plt.show()
|
||||
# # Summary
|
||||
|
||||
# ...
|
||||
|
||||
# ---
|
||||
#
|
||||
# Readers may ignore the next cell.
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
Python Machine Learning - Code Examples
|
||||
|
||||
|
||||
## Chapter 8: Applying Machine Learning to Sentiment Analysis
|
||||
|
||||
### Chapter Outline
|
||||
|
||||
- Artificial neurons – a brief glimpse into the early history of machine learning
|
||||
- The formal definition of an artificial neuron
|
||||
- The perceptron learning rule
|
||||
- Implementing a perceptron learning algorithm in Python
|
||||
- An object-oriented perceptron API
|
||||
- Training a perceptron model on the Iris dataset
|
||||
- Adaptive linear neurons and the convergence of learning
|
||||
- Minimizing cost functions with gradient descent
|
||||
- Implementing an Adaptive Linear Neuron in Python
|
||||
- Improving gradient descent through feature scaling
|
||||
- Large scale machine learning and stochastic gradient descent
|
||||
- Summary
|
||||
|
||||
### A note on using the code examples
|
||||
|
||||
The recommended way to interact with the code examples in this book is via Jupyter Notebook (the `.ipynb` files). Using Jupyter Notebook, you will be able to execute the code step by step and have all the resulting outputs (including plots and images) all in one convenient document.
|
||||
|
||||

|
||||
|
||||
|
||||
|
||||
Setting up Jupyter Notebook is really easy: if you are using the Anaconda Python distribution, all you need to install jupyter notebook is to execute the following command in your terminal:
|
||||
|
||||
conda install jupyter notebook
|
||||
|
||||
Then you can launch jupyter notebook by executing
|
||||
|
||||
jupyter notebook
|
||||
|
||||
A window will open up in your browser, which you can then use to navigate to the target directory that contains the `.ipynb` file you wish to open.
|
||||
|
||||
**More installation and setup instructions can be found in the [README.md file of Chapter 1](../ch01/README.md)**.
|
||||
|
||||
**(Even if you decide not to install Jupyter Notebook, note that you can also view the notebook files on GitHub by simply clicking on them: [`ch08.ipynb`](ch08.ipynb))**
|
||||
|
||||
In addition to the code examples, I added a table of contents to each Jupyter notebook as well as section headers that are consistent with the content of the book. Also, I included the original images and figures in hope that these make it easier to navigate and work with the code interactively as you are reading the book.
|
||||
|
||||

|
||||
|
||||
|
||||
When I was creating these notebooks, I was hoping to make your reading (and coding) experience as convenient as possible! However, if you don't wish to use Jupyter Notebooks, I also converted these notebooks to regular Python script files (`.py` files) that can be viewed and edited in any plaintext editor.
|
||||
@@ -1800,7 +1800,7 @@
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"[NbConvertApp] Converting notebook ch08.ipynb to script\n",
|
||||
"[NbConvertApp] Writing 24445 bytes to ch08.py\n"
|
||||
"[NbConvertApp] Writing 24613 bytes to ch08.py\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
|
||||
@@ -1,6 +1,29 @@
|
||||
|
||||
# coding: utf-8
|
||||
|
||||
|
||||
import os
|
||||
import sys
|
||||
import tarfile
|
||||
import time
|
||||
import pyprind
|
||||
import pandas as pd
|
||||
import numpy as np
|
||||
from sklearn.feature_extraction.text import CountVectorizer
|
||||
from sklearn.feature_extraction.text import TfidfTransformer
|
||||
import re
|
||||
from nltk.stem.porter import PorterStemmer
|
||||
import nltk
|
||||
from nltk.corpus import stopwords
|
||||
from sklearn.pipeline import Pipeline
|
||||
from sklearn.linear_model import LogisticRegression
|
||||
from sklearn.feature_extraction.text import TfidfVectorizer
|
||||
from sklearn.model_selection import GridSearchCV
|
||||
from sklearn.model_selection import StratifiedKFold
|
||||
from sklearn.model_selection import cross_val_score
|
||||
from sklearn.feature_extraction.text import HashingVectorizer
|
||||
from sklearn.linear_model import SGDClassifier
|
||||
from sklearn.decomposition import LatentDirichletAllocation
|
||||
|
||||
# *Python Machine Learning 2nd Edition* by [Sebastian Raschka](https://sebastianraschka.com), Packt Publishing Ltd. 2017
|
||||
#
|
||||
# Code Repository: https://github.com/rasbt/python-machine-learning-book-2nd-edition
|
||||
@@ -13,7 +36,6 @@
|
||||
|
||||
# Note that the optional watermark extension is a small IPython notebook plugin that I developed to make the code reproducible. You can just skip the following line(s).
|
||||
|
||||
# In[1]:
|
||||
|
||||
|
||||
|
||||
@@ -54,13 +76,8 @@
|
||||
|
||||
# **Optional code to download and unzip the dataset via Python:**
|
||||
|
||||
# In[2]:
|
||||
|
||||
|
||||
import os
|
||||
import sys
|
||||
import tarfile
|
||||
import time
|
||||
|
||||
|
||||
source = 'http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz'
|
||||
@@ -92,7 +109,6 @@ if not os.path.isdir('aclImdb') and not os.path.isfile('aclImdb_v1.tar.gz'):
|
||||
urllib.request.urlretrieve(source, target, reporthook)
|
||||
|
||||
|
||||
# In[3]:
|
||||
|
||||
|
||||
if not os.path.isdir('aclImdb'):
|
||||
@@ -103,12 +119,8 @@ if not os.path.isdir('aclImdb'):
|
||||
|
||||
# ## Preprocessing the movie dataset into more convenient format
|
||||
|
||||
# In[23]:
|
||||
|
||||
|
||||
import pyprind
|
||||
import pandas as pd
|
||||
import os
|
||||
|
||||
# change the `basepath` to the directory of the
|
||||
# unzipped movie dataset
|
||||
@@ -133,10 +145,8 @@ df.columns = ['review', 'sentiment']
|
||||
|
||||
# Shuffling the DataFrame:
|
||||
|
||||
# In[24]:
|
||||
|
||||
|
||||
import numpy as np
|
||||
|
||||
np.random.seed(0)
|
||||
df = df.reindex(np.random.permutation(df.index))
|
||||
@@ -144,27 +154,22 @@ df = df.reindex(np.random.permutation(df.index))
|
||||
|
||||
# Optional: Saving the assembled data as CSV file:
|
||||
|
||||
# In[25]:
|
||||
|
||||
|
||||
df.to_csv('movie_data.csv', index=False, encoding='utf-8')
|
||||
|
||||
|
||||
# In[26]:
|
||||
|
||||
|
||||
import pandas as pd
|
||||
|
||||
df = pd.read_csv('movie_data.csv', encoding='utf-8')
|
||||
df.head(3)
|
||||
|
||||
|
||||
# <hr>
|
||||
# ### Note
|
||||
#
|
||||
# If you have problems with creating the `movie_data.csv` file in the previous chapter, you can find a download a zip archive at
|
||||
# https://github.com/rasbt/python-machine-learning-book-2nd-edition/tree/master/code/ch08/
|
||||
# <hr>
|
||||
|
||||
|
||||
# # Introducing the bag-of-words model
|
||||
@@ -179,11 +184,8 @@ df.head(3)
|
||||
# 3. The sun is shining, the weather is sweet, and one and one is two
|
||||
#
|
||||
|
||||
# In[6]:
|
||||
|
||||
|
||||
import numpy as np
|
||||
from sklearn.feature_extraction.text import CountVectorizer
|
||||
|
||||
count = CountVectorizer()
|
||||
docs = np.array([
|
||||
@@ -195,7 +197,6 @@ bag = count.fit_transform(docs)
|
||||
|
||||
# Now let us print the contents of the vocabulary to get a better understanding of the underlying concepts:
|
||||
|
||||
# In[7]:
|
||||
|
||||
|
||||
print(count.vocabulary_)
|
||||
@@ -205,7 +206,6 @@ print(count.vocabulary_)
|
||||
|
||||
# Each index position in the feature vectors shown here corresponds to the integer values that are stored as dictionary items in the CountVectorizer vocabulary. For example, the rst feature at index position 0 resembles the count of the word and, which only occurs in the last document, and the word is at index position 1 (the 2nd feature in the document vectors) occurs in all three sentences. Those values in the feature vectors are also called the raw term frequencies: *tf (t,d)*—the number of times a term t occurs in a document *d*.
|
||||
|
||||
# In[8]:
|
||||
|
||||
|
||||
print(bag.toarray())
|
||||
@@ -214,7 +214,6 @@ print(bag.toarray())
|
||||
|
||||
# ## Assessing word relevancy via term frequency-inverse document frequency
|
||||
|
||||
# In[9]:
|
||||
|
||||
|
||||
np.set_printoptions(precision=2)
|
||||
@@ -233,10 +232,8 @@ np.set_printoptions(precision=2)
|
||||
#
|
||||
# Scikit-learn implements yet another transformer, the `TfidfTransformer`, that takes the raw term frequencies from `CountVectorizer` as input and transforms them into tf-idfs:
|
||||
|
||||
# In[10]:
|
||||
|
||||
|
||||
from sklearn.feature_extraction.text import TfidfTransformer
|
||||
|
||||
tfidf = TfidfTransformer(use_idf=True,
|
||||
norm='l2',
|
||||
@@ -275,7 +272,6 @@ print(tfidf.fit_transform(count.fit_transform(docs))
|
||||
#
|
||||
# $$\text{tf-idf}("is",d3)= 3 \times (0+1) = 3$$
|
||||
|
||||
# In[11]:
|
||||
|
||||
|
||||
tf_is = 3
|
||||
@@ -295,7 +291,6 @@ print('tf-idf of term "is" = %.2f' % tfidf_is)
|
||||
|
||||
# As we can see, the results match the results returned by scikit-learn's `TfidfTransformer` (below). Since we now understand how tf-idfs are calculated, let us proceed to the next sections and apply those concepts to the movie review dataset.
|
||||
|
||||
# In[12]:
|
||||
|
||||
|
||||
tfidf = TfidfTransformer(use_idf=True, norm=None, smooth_idf=True)
|
||||
@@ -303,7 +298,6 @@ raw_tfidf = tfidf.fit_transform(count.fit_transform(docs)).toarray()[-1]
|
||||
raw_tfidf
|
||||
|
||||
|
||||
# In[13]:
|
||||
|
||||
|
||||
l2_tfidf = raw_tfidf / np.sqrt(np.sum(raw_tfidf**2))
|
||||
@@ -313,16 +307,13 @@ l2_tfidf
|
||||
|
||||
# ## Cleaning text data
|
||||
|
||||
# In[14]:
|
||||
|
||||
|
||||
df.loc[0, 'review'][-50:]
|
||||
|
||||
|
||||
# In[15]:
|
||||
|
||||
|
||||
import re
|
||||
def preprocessor(text):
|
||||
text = re.sub('<[^>]*>', '', text)
|
||||
emoticons = re.findall('(?::|;|=)(?:-)?(?:\)|\(|D|P)',
|
||||
@@ -332,19 +323,16 @@ def preprocessor(text):
|
||||
return text
|
||||
|
||||
|
||||
# In[16]:
|
||||
|
||||
|
||||
preprocessor(df.loc[0, 'review'][-50:])
|
||||
|
||||
|
||||
# In[17]:
|
||||
|
||||
|
||||
preprocessor("</a>This :) is :( a test :-)!")
|
||||
|
||||
|
||||
# In[18]:
|
||||
|
||||
|
||||
df['review'] = df['review'].apply(preprocessor)
|
||||
@@ -353,10 +341,8 @@ df['review'] = df['review'].apply(preprocessor)
|
||||
|
||||
# ## Processing documents into tokens
|
||||
|
||||
# In[9]:
|
||||
|
||||
|
||||
from nltk.stem.porter import PorterStemmer
|
||||
|
||||
porter = PorterStemmer()
|
||||
|
||||
@@ -368,30 +354,24 @@ def tokenizer_porter(text):
|
||||
return [porter.stem(word) for word in text.split()]
|
||||
|
||||
|
||||
# In[10]:
|
||||
|
||||
|
||||
tokenizer('runners like running and thus they run')
|
||||
|
||||
|
||||
# In[11]:
|
||||
|
||||
|
||||
tokenizer_porter('runners like running and thus they run')
|
||||
|
||||
|
||||
# In[12]:
|
||||
|
||||
|
||||
import nltk
|
||||
|
||||
nltk.download('stopwords')
|
||||
|
||||
|
||||
# In[13]:
|
||||
|
||||
|
||||
from nltk.corpus import stopwords
|
||||
|
||||
stop = stopwords.words('english')
|
||||
[w for w in tokenizer_porter('a runner likes running and runs a lot')[-10:]
|
||||
@@ -403,7 +383,6 @@ if w not in stop]
|
||||
|
||||
# Strip HTML and punctuation to speed up the GridSearch later:
|
||||
|
||||
# In[24]:
|
||||
|
||||
|
||||
X_train = df.loc[:25000, 'review'].values
|
||||
@@ -412,13 +391,8 @@ X_test = df.loc[25000:, 'review'].values
|
||||
y_test = df.loc[25000:, 'sentiment'].values
|
||||
|
||||
|
||||
# In[25]:
|
||||
|
||||
|
||||
from sklearn.pipeline import Pipeline
|
||||
from sklearn.linear_model import LogisticRegression
|
||||
from sklearn.feature_extraction.text import TfidfVectorizer
|
||||
from sklearn.model_selection import GridSearchCV
|
||||
|
||||
tfidf = TfidfVectorizer(strip_accents=None,
|
||||
lowercase=False,
|
||||
@@ -470,7 +444,6 @@ gs_lr_tfidf = GridSearchCV(lr_tfidf, param_grid,
|
||||
# 'clf__C': [1.0, 10.0]},
|
||||
# ]
|
||||
|
||||
# In[ ]:
|
||||
|
||||
|
||||
## @Readers: PLEASE IGNORE THIS CELL
|
||||
@@ -490,41 +463,31 @@ if 'TRAVIS' in os.environ:
|
||||
y_test = df.loc[25000:25250, 'sentiment'].values
|
||||
|
||||
|
||||
# In[26]:
|
||||
|
||||
|
||||
gs_lr_tfidf.fit(X_train, y_train)
|
||||
|
||||
|
||||
# In[27]:
|
||||
|
||||
|
||||
print('Best parameter set: %s ' % gs_lr_tfidf.best_params_)
|
||||
print('CV Accuracy: %.3f' % gs_lr_tfidf.best_score_)
|
||||
|
||||
|
||||
# In[28]:
|
||||
|
||||
|
||||
clf = gs_lr_tfidf.best_estimator_
|
||||
print('Test Accuracy: %.3f' % clf.score(X_test, y_test))
|
||||
|
||||
|
||||
# <hr>
|
||||
# <hr>
|
||||
|
||||
# #### Start comment:
|
||||
#
|
||||
# Please note that `gs_lr_tfidf.best_score_` is the average k-fold cross-validation score. I.e., if we have a `GridSearchCV` object with 5-fold cross-validation (like the one above), the `best_score_` attribute returns the average score over the 5-folds of the best model. To illustrate this with an example:
|
||||
|
||||
# In[29]:
|
||||
|
||||
|
||||
from sklearn.linear_model import LogisticRegression
|
||||
import numpy as np
|
||||
|
||||
from sklearn.model_selection import StratifiedKFold
|
||||
from sklearn.model_selection import cross_val_score
|
||||
|
||||
np.random.seed(0)
|
||||
np.set_printoptions(precision=6)
|
||||
@@ -540,10 +503,8 @@ cross_val_score(LogisticRegression(random_state=123), X, y, cv=cv5_idx)
|
||||
#
|
||||
# Next, let us use the `GridSearchCV` object and feed it the same 5 cross-validation sets (via the pre-generated `cv3_idx` indices):
|
||||
|
||||
# In[30]:
|
||||
|
||||
|
||||
from sklearn.model_selection import GridSearchCV
|
||||
|
||||
gs = GridSearchCV(LogisticRegression(), {}, cv=cv5_idx, verbose=3).fit(X, y)
|
||||
|
||||
@@ -552,7 +513,6 @@ gs = GridSearchCV(LogisticRegression(), {}, cv=cv5_idx, verbose=3).fit(X, y)
|
||||
|
||||
# Now, the best_score_ attribute of the `GridSearchCV` object, which becomes available after `fit`ting, returns the average accuracy score of the best model:
|
||||
|
||||
# In[31]:
|
||||
|
||||
|
||||
gs.best_score_
|
||||
@@ -560,7 +520,6 @@ gs.best_score_
|
||||
|
||||
# As we can see, the result above is consistent with the average score computed the `cross_val_score`.
|
||||
|
||||
# In[32]:
|
||||
|
||||
|
||||
cross_val_score(LogisticRegression(), X, y, cv=cv5_idx).mean()
|
||||
@@ -568,18 +527,12 @@ cross_val_score(LogisticRegression(), X, y, cv=cv5_idx).mean()
|
||||
|
||||
# #### End comment.
|
||||
#
|
||||
# <hr>
|
||||
# <hr>
|
||||
|
||||
|
||||
# # Working with bigger data - online algorithms and out-of-core learning
|
||||
|
||||
# In[27]:
|
||||
|
||||
|
||||
import numpy as np
|
||||
import re
|
||||
from nltk.corpus import stopwords
|
||||
|
||||
def tokenizer(text):
|
||||
text = re.sub('<[^>]*>', '', text)
|
||||
@@ -597,13 +550,11 @@ def stream_docs(path):
|
||||
yield text, label
|
||||
|
||||
|
||||
# In[28]:
|
||||
|
||||
|
||||
next(stream_docs(path='movie_data.csv'))
|
||||
|
||||
|
||||
# In[29]:
|
||||
|
||||
|
||||
def get_minibatch(doc_stream, size):
|
||||
@@ -618,11 +569,8 @@ def get_minibatch(doc_stream, size):
|
||||
return docs, y
|
||||
|
||||
|
||||
# In[30]:
|
||||
|
||||
|
||||
from sklearn.feature_extraction.text import HashingVectorizer
|
||||
from sklearn.linear_model import SGDClassifier
|
||||
|
||||
vect = HashingVectorizer(decode_error='ignore',
|
||||
n_features=2**21,
|
||||
@@ -638,10 +586,8 @@ doc_stream = stream_docs(path='movie_data.csv')
|
||||
# - You can replace `Perceptron(n_iter, ...)` by `Perceptron(max_iter, ...)` in scikit-learn >= 0.19. The `n_iter` parameter is used here deriberately, because some people still use scikit-learn 0.18.
|
||||
#
|
||||
|
||||
# In[31]:
|
||||
|
||||
|
||||
import pyprind
|
||||
pbar = pyprind.ProgBar(45)
|
||||
|
||||
classes = np.array([0, 1])
|
||||
@@ -654,7 +600,6 @@ for _ in range(45):
|
||||
pbar.update()
|
||||
|
||||
|
||||
# In[32]:
|
||||
|
||||
|
||||
X_test, y_test = get_minibatch(doc_stream, size=5000)
|
||||
@@ -662,7 +607,6 @@ X_test = vect.transform(X_test)
|
||||
print('Accuracy: %.3f' % clf.score(X_test, y_test))
|
||||
|
||||
|
||||
# In[33]:
|
||||
|
||||
|
||||
clf = clf.partial_fit(X_test, y_test)
|
||||
@@ -674,16 +618,13 @@ clf = clf.partial_fit(X_test, y_test)
|
||||
|
||||
# ### Latent Dirichlet Allocation with scikit-learn
|
||||
|
||||
# In[1]:
|
||||
|
||||
|
||||
import pandas as pd
|
||||
|
||||
df = pd.read_csv('movie_data.csv', encoding='utf-8')
|
||||
df.head(3)
|
||||
|
||||
|
||||
# In[ ]:
|
||||
|
||||
|
||||
## @Readers: PLEASE IGNORE THIS CELL
|
||||
@@ -700,10 +641,8 @@ if 'TRAVIS' in os.environ:
|
||||
print('SMALL DATA SUBSET CREATED FOR TESTING')
|
||||
|
||||
|
||||
# In[2]:
|
||||
|
||||
|
||||
from sklearn.feature_extraction.text import CountVectorizer
|
||||
|
||||
count = CountVectorizer(stop_words='english',
|
||||
max_df=.1,
|
||||
@@ -711,10 +650,8 @@ count = CountVectorizer(stop_words='english',
|
||||
X = count.fit_transform(df['review'].values)
|
||||
|
||||
|
||||
# In[3]:
|
||||
|
||||
|
||||
from sklearn.decomposition import LatentDirichletAllocation
|
||||
|
||||
lda = LatentDirichletAllocation(n_topics=10,
|
||||
random_state=123,
|
||||
@@ -722,13 +659,11 @@ lda = LatentDirichletAllocation(n_topics=10,
|
||||
X_topics = lda.fit_transform(X)
|
||||
|
||||
|
||||
# In[4]:
|
||||
|
||||
|
||||
lda.components_.shape
|
||||
|
||||
|
||||
# In[5]:
|
||||
|
||||
|
||||
n_top_words = 5
|
||||
@@ -756,7 +691,6 @@ for topic_idx, topic in enumerate(lda.components_):
|
||||
|
||||
# To confirm that the categories make sense based on the reviews, let's plot 5 movies from the horror movie category (category 6 at index position 5):
|
||||
|
||||
# In[6]:
|
||||
|
||||
|
||||
horror = X_topics[:, 5].argsort()[::-1]
|
||||
@@ -770,3 +704,13 @@ for iter_idx, movie_idx in enumerate(horror[:3]):
|
||||
|
||||
|
||||
# # Summary
|
||||
|
||||
# ...
|
||||
|
||||
# ---
|
||||
#
|
||||
# Readers may ignore the next cell.
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
Python Machine Learning - Code Examples
|
||||
|
||||
|
||||
## Chapter 10: Predicting Continuous Target Variables with Regression Analysis
|
||||
|
||||
### Chapter Outline
|
||||
|
||||
- Introducing linear regression
|
||||
- Simple linear regression
|
||||
- Multiple linear regression
|
||||
- Exploring the Housing dataset
|
||||
- Loading the Housing dataset into a data frame
|
||||
- Visualizing the important characteristics of a dataset
|
||||
- Looking at relationships using a correlation matrix
|
||||
- Implementing an ordinary least squares linear regression model
|
||||
- Solving regression for regression parameters with gradient descent
|
||||
- Estimating coef cient of a regression model via scikit-learn
|
||||
- Fitting a robust regression model using RANSAC
|
||||
- Evaluating the performance of linear regression models
|
||||
- Using regularized methods for regression
|
||||
- Turning a linear regression model into a curve – polynomial
|
||||
regression
|
||||
- Adding polynomial terms using scikit-learn
|
||||
- Modeling nonlinear relationships in the Housing dataset
|
||||
- Dealing with nonlinear relationships using random forests
|
||||
- Decision tree regression
|
||||
- Random forest regression
|
||||
- Summary
|
||||
|
||||
### A note on using the code examples
|
||||
|
||||
The recommended way to interact with the code examples in this book is via Jupyter Notebook (the `.ipynb` files). Using Jupyter Notebook, you will be able to execute the code step by step and have all the resulting outputs (including plots and images) all in one convenient document.
|
||||
|
||||

|
||||
|
||||
|
||||
|
||||
Setting up Jupyter Notebook is really easy: if you are using the Anaconda Python distribution, all you need to install jupyter notebook is to execute the following command in your terminal:
|
||||
|
||||
conda install jupyter notebook
|
||||
|
||||
Then you can launch jupyter notebook by executing
|
||||
|
||||
jupyter notebook
|
||||
|
||||
A window will open up in your browser, which you can then use to navigate to the target directory that contains the `.ipynb` file you wish to open.
|
||||
|
||||
**More installation and setup instructions can be found in the [README.md file of Chapter 1](../ch01/README.md)**.
|
||||
|
||||
**(Even if you decide not to install Jupyter Notebook, note that you can also view the notebook files on GitHub by simply clicking on them: [`ch10.ipynb`](ch10.ipynb))**
|
||||
|
||||
In addition to the code examples, I added a table of contents to each Jupyter notebook as well as section headers that are consistent with the content of the book. Also, I included the original images and figures in hope that these make it easier to navigate and work with the code interactively as you are reading the book.
|
||||
|
||||

|
||||
|
||||
|
||||
When I was creating these notebooks, I was hoping to make your reading (and coding) experience as convenient as possible! However, if you don't wish to use Jupyter Notebooks, I also converted these notebooks to regular Python script files (`.py` files) that can be viewed and edited in any plaintext editor.
|
||||
@@ -533,7 +533,7 @@
|
||||
" xticklabels=cols)\n",
|
||||
"\n",
|
||||
"plt.tight_layout()\n",
|
||||
"plt.savefig('images/10_04.png', dpi=300)\n",
|
||||
"# plt.savefig('images/10_04.png', dpi=300)\n",
|
||||
"plt.show()"
|
||||
]
|
||||
},
|
||||
@@ -712,7 +712,7 @@
|
||||
"plt.xlabel('Average number of rooms [RM] (standardized)')\n",
|
||||
"plt.ylabel('Price in $1000s [MEDV] (standardized)')\n",
|
||||
"\n",
|
||||
"plt.savefig('images/10_06.png', dpi=300)\n",
|
||||
"#plt.savefig('images/10_06.png', dpi=300)\n",
|
||||
"plt.show()"
|
||||
]
|
||||
},
|
||||
@@ -1715,7 +1715,7 @@
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"[NbConvertApp] Converting notebook ch10.ipynb to script\n",
|
||||
"[NbConvertApp] Writing 18570 bytes to ch10.py\n"
|
||||
"[NbConvertApp] Writing 18559 bytes to ch10.py\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
|
||||
@@ -1,6 +1,24 @@
|
||||
|
||||
# coding: utf-8
|
||||
|
||||
|
||||
import pandas as pd
|
||||
import matplotlib.pyplot as plt
|
||||
import seaborn as sns
|
||||
import numpy as np
|
||||
from sklearn.preprocessing import StandardScaler
|
||||
from sklearn.linear_model import LinearRegression
|
||||
from sklearn.linear_model import RANSACRegressor
|
||||
from sklearn.model_selection import train_test_split
|
||||
import scipy as sp
|
||||
from sklearn.metrics import r2_score
|
||||
from sklearn.metrics import mean_squared_error
|
||||
from sklearn.linear_model import Lasso
|
||||
from sklearn.linear_model import Ridge
|
||||
from sklearn.linear_model import ElasticNet
|
||||
from sklearn.preprocessing import PolynomialFeatures
|
||||
from sklearn.tree import DecisionTreeRegressor
|
||||
from sklearn.ensemble import RandomForestRegressor
|
||||
|
||||
# *Python Machine Learning 2nd Edition* by [Sebastian Raschka](https://sebastianraschka.com), Packt Publishing Ltd. 2017
|
||||
#
|
||||
# Code Repository: https://github.com/rasbt/python-machine-learning-book-2nd-edition
|
||||
@@ -13,7 +31,6 @@
|
||||
|
||||
# Note that the optional watermark extension is a small IPython notebook plugin that I developed to make the code reproducible. You can just skip the following line(s).
|
||||
|
||||
# In[1]:
|
||||
|
||||
|
||||
|
||||
@@ -50,24 +67,20 @@
|
||||
# - [Summary](#Summary)
|
||||
|
||||
|
||||
# In[2]:
|
||||
|
||||
|
||||
from IPython.display import Image
|
||||
|
||||
|
||||
# # Introducing linear regression
|
||||
|
||||
# ## Simple linear regression
|
||||
|
||||
# In[3]:
|
||||
|
||||
|
||||
|
||||
|
||||
# ## Multiple linear regression
|
||||
|
||||
# In[4]:
|
||||
|
||||
|
||||
|
||||
@@ -101,10 +114,8 @@ from IPython.display import Image
|
||||
# 14. MEDV Median value of owner-occupied homes in $1000s
|
||||
# </pre>
|
||||
|
||||
# In[5]:
|
||||
|
||||
|
||||
import pandas as pd
|
||||
|
||||
df = pd.read_csv('https://raw.githubusercontent.com/rasbt/'
|
||||
'python-machine-learning-book-2nd-edition'
|
||||
@@ -118,7 +129,6 @@ df.columns = ['CRIM', 'ZN', 'INDUS', 'CHAS',
|
||||
df.head()
|
||||
|
||||
|
||||
# <hr>
|
||||
#
|
||||
# ### Note:
|
||||
#
|
||||
@@ -135,14 +145,10 @@ df.head()
|
||||
|
||||
# ## Visualizing the important characteristics of a dataset
|
||||
|
||||
# In[6]:
|
||||
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
import seaborn as sns
|
||||
|
||||
|
||||
# In[7]:
|
||||
|
||||
|
||||
cols = ['LSTAT', 'INDUS', 'NOX', 'RM', 'MEDV']
|
||||
@@ -153,10 +159,8 @@ plt.tight_layout()
|
||||
plt.show()
|
||||
|
||||
|
||||
# In[8]:
|
||||
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
cm = np.corrcoef(df[cols].values.T)
|
||||
@@ -171,7 +175,7 @@ hm = sns.heatmap(cm,
|
||||
xticklabels=cols)
|
||||
|
||||
plt.tight_layout()
|
||||
plt.savefig('images/10_04.png', dpi=300)
|
||||
# plt.savefig('images/10_04.png', dpi=300)
|
||||
plt.show()
|
||||
|
||||
|
||||
@@ -182,7 +186,6 @@ plt.show()
|
||||
|
||||
# ## Solving regression for regression parameters with gradient descent
|
||||
|
||||
# In[9]:
|
||||
|
||||
|
||||
class LinearRegressionGD(object):
|
||||
@@ -211,17 +214,14 @@ class LinearRegressionGD(object):
|
||||
return self.net_input(X)
|
||||
|
||||
|
||||
# In[10]:
|
||||
|
||||
|
||||
X = df[['RM']].values
|
||||
y = df['MEDV'].values
|
||||
|
||||
|
||||
# In[11]:
|
||||
|
||||
|
||||
from sklearn.preprocessing import StandardScaler
|
||||
|
||||
|
||||
sc_x = StandardScaler()
|
||||
@@ -230,14 +230,12 @@ X_std = sc_x.fit_transform(X)
|
||||
y_std = sc_y.fit_transform(y[:, np.newaxis]).flatten()
|
||||
|
||||
|
||||
# In[12]:
|
||||
|
||||
|
||||
lr = LinearRegressionGD()
|
||||
lr.fit(X_std, y_std)
|
||||
|
||||
|
||||
# In[13]:
|
||||
|
||||
|
||||
plt.plot(range(1, lr.n_iter+1), lr.cost_)
|
||||
@@ -248,7 +246,6 @@ plt.xlabel('Epoch')
|
||||
plt.show()
|
||||
|
||||
|
||||
# In[14]:
|
||||
|
||||
|
||||
def lin_regplot(X, y, model):
|
||||
@@ -257,25 +254,22 @@ def lin_regplot(X, y, model):
|
||||
return
|
||||
|
||||
|
||||
# In[15]:
|
||||
|
||||
|
||||
lin_regplot(X_std, y_std, lr)
|
||||
plt.xlabel('Average number of rooms [RM] (standardized)')
|
||||
plt.ylabel('Price in $1000s [MEDV] (standardized)')
|
||||
|
||||
plt.savefig('images/10_06.png', dpi=300)
|
||||
#plt.savefig('images/10_06.png', dpi=300)
|
||||
plt.show()
|
||||
|
||||
|
||||
# In[16]:
|
||||
|
||||
|
||||
print('Slope: %.3f' % lr.w_[1])
|
||||
print('Intercept: %.3f' % lr.w_[0])
|
||||
|
||||
|
||||
# In[17]:
|
||||
|
||||
|
||||
num_rooms_std = sc_x.transform(np.array([[5.0]]))
|
||||
@@ -286,13 +280,10 @@ print("Price in $1000s: %.3f" % sc_y.inverse_transform(price_std))
|
||||
|
||||
# ## Estimating the coefficient of a regression model via scikit-learn
|
||||
|
||||
# In[18]:
|
||||
|
||||
|
||||
from sklearn.linear_model import LinearRegression
|
||||
|
||||
|
||||
# In[19]:
|
||||
|
||||
|
||||
slr = LinearRegression()
|
||||
@@ -302,7 +293,6 @@ print('Slope: %.3f' % slr.coef_[0])
|
||||
print('Intercept: %.3f' % slr.intercept_)
|
||||
|
||||
|
||||
# In[20]:
|
||||
|
||||
|
||||
lin_regplot(X, y, slr)
|
||||
@@ -315,7 +305,6 @@ plt.show()
|
||||
|
||||
# **Normal Equations** alternative:
|
||||
|
||||
# In[21]:
|
||||
|
||||
|
||||
# adding a column vector of "ones"
|
||||
@@ -331,10 +320,8 @@ print('Intercept: %.3f' % w[0])
|
||||
|
||||
# # Fitting a robust regression model using RANSAC
|
||||
|
||||
# In[22]:
|
||||
|
||||
|
||||
from sklearn.linear_model import RANSACRegressor
|
||||
|
||||
ransac = RANSACRegressor(LinearRegression(),
|
||||
max_trials=100,
|
||||
@@ -366,7 +353,6 @@ plt.legend(loc='upper left')
|
||||
plt.show()
|
||||
|
||||
|
||||
# In[23]:
|
||||
|
||||
|
||||
print('Slope: %.3f' % ransac.estimator_.coef_[0])
|
||||
@@ -376,10 +362,8 @@ print('Intercept: %.3f' % ransac.estimator_.intercept_)
|
||||
|
||||
# # Evaluating the performance of linear regression models
|
||||
|
||||
# In[24]:
|
||||
|
||||
|
||||
from sklearn.model_selection import train_test_split
|
||||
|
||||
X = df.iloc[:, :-1].values
|
||||
y = df['MEDV'].values
|
||||
@@ -388,7 +372,6 @@ X_train, X_test, y_train, y_test = train_test_split(
|
||||
X, y, test_size=0.3, random_state=0)
|
||||
|
||||
|
||||
# In[25]:
|
||||
|
||||
|
||||
slr = LinearRegression()
|
||||
@@ -398,31 +381,24 @@ y_train_pred = slr.predict(X_train)
|
||||
y_test_pred = slr.predict(X_test)
|
||||
|
||||
|
||||
# In[26]:
|
||||
|
||||
|
||||
import numpy as np
|
||||
import scipy as sp
|
||||
|
||||
ary = np.array(range(100000))
|
||||
|
||||
|
||||
# In[27]:
|
||||
|
||||
|
||||
|
||||
|
||||
# In[28]:
|
||||
|
||||
|
||||
|
||||
|
||||
# In[29]:
|
||||
|
||||
|
||||
|
||||
|
||||
# In[30]:
|
||||
|
||||
|
||||
plt.scatter(y_train_pred, y_train_pred - y_train,
|
||||
@@ -442,11 +418,8 @@ plt.tight_layout()
|
||||
plt.show()
|
||||
|
||||
|
||||
# In[31]:
|
||||
|
||||
|
||||
from sklearn.metrics import r2_score
|
||||
from sklearn.metrics import mean_squared_error
|
||||
|
||||
print('MSE train: %.3f, test: %.3f' % (
|
||||
mean_squared_error(y_train, y_train_pred),
|
||||
@@ -459,10 +432,8 @@ print('R^2 train: %.3f, test: %.3f' % (
|
||||
|
||||
# # Using regularized methods for regression
|
||||
|
||||
# In[32]:
|
||||
|
||||
|
||||
from sklearn.linear_model import Lasso
|
||||
|
||||
lasso = Lasso(alpha=0.1)
|
||||
lasso.fit(X_train, y_train)
|
||||
@@ -471,7 +442,6 @@ y_test_pred = lasso.predict(X_test)
|
||||
print(lasso.coef_)
|
||||
|
||||
|
||||
# In[33]:
|
||||
|
||||
|
||||
print('MSE train: %.3f, test: %.3f' % (
|
||||
@@ -484,35 +454,28 @@ print('R^2 train: %.3f, test: %.3f' % (
|
||||
|
||||
# Ridge regression:
|
||||
|
||||
# In[34]:
|
||||
|
||||
|
||||
from sklearn.linear_model import Ridge
|
||||
ridge = Ridge(alpha=1.0)
|
||||
|
||||
|
||||
# LASSO regression:
|
||||
|
||||
# In[35]:
|
||||
|
||||
|
||||
from sklearn.linear_model import Lasso
|
||||
lasso = Lasso(alpha=1.0)
|
||||
|
||||
|
||||
# Elastic Net regression:
|
||||
|
||||
# In[36]:
|
||||
|
||||
|
||||
from sklearn.linear_model import ElasticNet
|
||||
elanet = ElasticNet(alpha=1.0, l1_ratio=0.5)
|
||||
|
||||
|
||||
|
||||
# # Turning a linear regression model into a curve - polynomial regression
|
||||
|
||||
# In[37]:
|
||||
|
||||
|
||||
X = np.array([258.0, 270.0, 294.0,
|
||||
@@ -526,10 +489,8 @@ y = np.array([236.4, 234.4, 252.8,
|
||||
390.8])
|
||||
|
||||
|
||||
# In[38]:
|
||||
|
||||
|
||||
from sklearn.preprocessing import PolynomialFeatures
|
||||
|
||||
lr = LinearRegression()
|
||||
pr = LinearRegression()
|
||||
@@ -537,7 +498,6 @@ quadratic = PolynomialFeatures(degree=2)
|
||||
X_quad = quadratic.fit_transform(X)
|
||||
|
||||
|
||||
# In[39]:
|
||||
|
||||
|
||||
# fit linear features
|
||||
@@ -560,14 +520,12 @@ plt.tight_layout()
|
||||
plt.show()
|
||||
|
||||
|
||||
# In[40]:
|
||||
|
||||
|
||||
y_lin_pred = lr.predict(X)
|
||||
y_quad_pred = pr.predict(X_quad)
|
||||
|
||||
|
||||
# In[41]:
|
||||
|
||||
|
||||
print('Training MSE linear: %.3f, quadratic: %.3f' % (
|
||||
@@ -581,7 +539,6 @@ print('Training R^2 linear: %.3f, quadratic: %.3f' % (
|
||||
|
||||
# ## Modeling nonlinear relationships in the Housing Dataset
|
||||
|
||||
# In[42]:
|
||||
|
||||
|
||||
X = df[['LSTAT']].values
|
||||
@@ -642,7 +599,6 @@ plt.show()
|
||||
|
||||
# Transforming the dataset:
|
||||
|
||||
# In[43]:
|
||||
|
||||
|
||||
X = df[['LSTAT']].values
|
||||
@@ -683,10 +639,8 @@ plt.show()
|
||||
|
||||
# ## Decision tree regression
|
||||
|
||||
# In[44]:
|
||||
|
||||
|
||||
from sklearn.tree import DecisionTreeRegressor
|
||||
|
||||
X = df[['LSTAT']].values
|
||||
y = df['MEDV'].values
|
||||
@@ -706,7 +660,6 @@ plt.show()
|
||||
|
||||
# ## Random forest regression
|
||||
|
||||
# In[45]:
|
||||
|
||||
|
||||
X = df.iloc[:, :-1].values
|
||||
@@ -716,10 +669,8 @@ X_train, X_test, y_train, y_test = train_test_split(
|
||||
X, y, test_size=0.4, random_state=1)
|
||||
|
||||
|
||||
# In[46]:
|
||||
|
||||
|
||||
from sklearn.ensemble import RandomForestRegressor
|
||||
|
||||
forest = RandomForestRegressor(n_estimators=1000,
|
||||
criterion='mse',
|
||||
@@ -737,7 +688,6 @@ print('R^2 train: %.3f, test: %.3f' % (
|
||||
r2_score(y_test, y_test_pred)))
|
||||
|
||||
|
||||
# In[47]:
|
||||
|
||||
|
||||
plt.scatter(y_train_pred,
|
||||
@@ -777,13 +727,6 @@ plt.show()
|
||||
#
|
||||
# Readers may ignore the next cell.
|
||||
|
||||
# In[ ]:
|
||||
|
||||
|
||||
|
||||
|
||||
# In[ ]:
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
Python Machine Learning - Code Examples
|
||||
|
||||
|
||||
## Chapter 11: Working with Unlabeled Data – Clustering Analysis
|
||||
|
||||
### Chapter Outline
|
||||
|
||||
- Grouping objects by similarity using k-means
|
||||
- K-means clustering using scikit-learn
|
||||
- A smarter way of placing the initial cluster centroids using k-means++
|
||||
- Hard versus soft clustering
|
||||
- Using the elbow method to find the optimal number of clusters
|
||||
- Quantifying the quality of clustering via silhouette plots
|
||||
- Organizing clusters as a hierarchical tree
|
||||
- Grouping clusters in bottom-up fashion
|
||||
- Performing hierarchical clustering on a distance matrix
|
||||
- Attaching dendrograms to a heat map
|
||||
- Applying agglomerative clustering via scikit-learn
|
||||
- Locating regions of high density via DBSCAN
|
||||
- Summary
|
||||
|
||||
### A note on using the code examples
|
||||
|
||||
The recommended way to interact with the code examples in this book is via Jupyter Notebook (the `.ipynb` files). Using Jupyter Notebook, you will be able to execute the code step by step and have all the resulting outputs (including plots and images) all in one convenient document.
|
||||
|
||||

|
||||
|
||||
|
||||
|
||||
Setting up Jupyter Notebook is really easy: if you are using the Anaconda Python distribution, all you need to install jupyter notebook is to execute the following command in your terminal:
|
||||
|
||||
conda install jupyter notebook
|
||||
|
||||
Then you can launch jupyter notebook by executing
|
||||
|
||||
jupyter notebook
|
||||
|
||||
A window will open up in your browser, which you can then use to navigate to the target directory that contains the `.ipynb` file you wish to open.
|
||||
|
||||
**More installation and setup instructions can be found in the [README.md file of Chapter 1](../ch01/README.md)**.
|
||||
|
||||
**(Even if you decide not to install Jupyter Notebook, note that you can also view the notebook files on GitHub by simply clicking on them: [`ch11.ipynb`](ch11.ipynb))**
|
||||
|
||||
In addition to the code examples, I added a table of contents to each Jupyter notebook as well as section headers that are consistent with the content of the book. Also, I included the original images and figures in hope that these make it easier to navigate and work with the code interactively as you are reading the book.
|
||||
|
||||

|
||||
|
||||
|
||||
When I was creating these notebooks, I was hoping to make your reading (and coding) experience as convenient as possible! However, if you don't wish to use Jupyter Notebooks, I also converted these notebooks to regular Python script files (`.py` files) that can be viewed and edited in any plaintext editor.
|
||||
@@ -1408,7 +1408,7 @@
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"[NbConvertApp] Converting notebook ch11.ipynb to script\n",
|
||||
"[NbConvertApp] Writing 13988 bytes to ch11.py\n"
|
||||
"[NbConvertApp] Writing 14002 bytes to ch11.py\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
|
||||
@@ -1,6 +1,21 @@
|
||||
|
||||
# coding: utf-8
|
||||
|
||||
|
||||
from sklearn.datasets import make_blobs
|
||||
import matplotlib.pyplot as plt
|
||||
from sklearn.cluster import KMeans
|
||||
import numpy as np
|
||||
from matplotlib import cm
|
||||
from sklearn.metrics import silhouette_samples
|
||||
import pandas as pd
|
||||
from scipy.spatial.distance import pdist, squareform
|
||||
from scipy.cluster.hierarchy import linkage
|
||||
from scipy.cluster.hierarchy import dendrogram
|
||||
# from scipy.cluster.hierarchy import set_link_color_palette
|
||||
from sklearn.cluster import AgglomerativeClustering
|
||||
from sklearn.datasets import make_moons
|
||||
from sklearn.cluster import DBSCAN
|
||||
|
||||
# *Python Machine Learning 2nd Edition* by [Sebastian Raschka](https://sebastianraschka.com), Packt Publishing Ltd. 2017
|
||||
#
|
||||
# Code Repository: https://github.com/rasbt/python-machine-learning-book-2nd-edition
|
||||
@@ -13,7 +28,6 @@
|
||||
|
||||
# Note that the optional watermark extension is a small IPython notebook plugin that I developed to make the code reproducible. You can just skip the following line(s).
|
||||
|
||||
# In[1]:
|
||||
|
||||
|
||||
|
||||
@@ -38,20 +52,16 @@
|
||||
# - [Summary](#Summary)
|
||||
|
||||
|
||||
# In[2]:
|
||||
|
||||
|
||||
from IPython.display import Image
|
||||
|
||||
|
||||
# # Grouping objects by similarity using k-means
|
||||
|
||||
# ## K-means clustering using scikit-learn
|
||||
|
||||
# In[3]:
|
||||
|
||||
|
||||
from sklearn.datasets import make_blobs
|
||||
|
||||
X, y = make_blobs(n_samples=150,
|
||||
n_features=2,
|
||||
@@ -61,10 +71,8 @@ X, y = make_blobs(n_samples=150,
|
||||
random_state=0)
|
||||
|
||||
|
||||
# In[4]:
|
||||
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
plt.scatter(X[:, 0], X[:, 1],
|
||||
c='white', marker='o', edgecolor='black', s=50)
|
||||
@@ -74,10 +82,8 @@ plt.tight_layout()
|
||||
plt.show()
|
||||
|
||||
|
||||
# In[5]:
|
||||
|
||||
|
||||
from sklearn.cluster import KMeans
|
||||
|
||||
km = KMeans(n_clusters=3,
|
||||
init='random',
|
||||
@@ -89,7 +95,6 @@ km = KMeans(n_clusters=3,
|
||||
y_km = km.fit_predict(X)
|
||||
|
||||
|
||||
# In[6]:
|
||||
|
||||
|
||||
plt.scatter(X[y_km == 0, 0],
|
||||
@@ -130,13 +135,11 @@ plt.show()
|
||||
|
||||
# ## Using the elbow method to find the optimal number of clusters
|
||||
|
||||
# In[7]:
|
||||
|
||||
|
||||
print('Distortion: %.2f' % km.inertia_)
|
||||
|
||||
|
||||
# In[8]:
|
||||
|
||||
|
||||
distortions = []
|
||||
@@ -159,12 +162,8 @@ plt.show()
|
||||
|
||||
# ## Quantifying the quality of clustering via silhouette plots
|
||||
|
||||
# In[9]:
|
||||
|
||||
|
||||
import numpy as np
|
||||
from matplotlib import cm
|
||||
from sklearn.metrics import silhouette_samples
|
||||
|
||||
km = KMeans(n_clusters=3,
|
||||
init='k-means++',
|
||||
@@ -204,7 +203,6 @@ plt.show()
|
||||
|
||||
# Comparison to "bad" clustering:
|
||||
|
||||
# In[10]:
|
||||
|
||||
|
||||
km = KMeans(n_clusters=2,
|
||||
@@ -239,7 +237,6 @@ plt.tight_layout()
|
||||
plt.show()
|
||||
|
||||
|
||||
# In[11]:
|
||||
|
||||
|
||||
cluster_labels = np.unique(y_km)
|
||||
@@ -275,16 +272,12 @@ plt.show()
|
||||
|
||||
# ## Grouping clusters in bottom-up fashion
|
||||
|
||||
# In[12]:
|
||||
|
||||
|
||||
|
||||
|
||||
# In[13]:
|
||||
|
||||
|
||||
import pandas as pd
|
||||
import numpy as np
|
||||
|
||||
np.random.seed(123)
|
||||
|
||||
@@ -299,10 +292,8 @@ df
|
||||
|
||||
# ## Performing hierarchical clustering on a distance matrix
|
||||
|
||||
# In[14]:
|
||||
|
||||
|
||||
from scipy.spatial.distance import pdist, squareform
|
||||
|
||||
row_dist = pd.DataFrame(squareform(pdist(df, metric='euclidean')),
|
||||
columns=labels,
|
||||
@@ -312,12 +303,10 @@ row_dist
|
||||
|
||||
# We can either pass a condensed distance matrix (upper triangular) from the `pdist` function, or we can pass the "original" data array and define the `metric='euclidean'` argument in `linkage`. However, we should not pass the squareform distance matrix, which would yield different distance values although the overall clustering could be the same.
|
||||
|
||||
# In[15]:
|
||||
|
||||
|
||||
# 1. incorrect approach: Squareform distance matrix
|
||||
|
||||
from scipy.cluster.hierarchy import linkage
|
||||
|
||||
row_clusters = linkage(row_dist, method='complete', metric='euclidean')
|
||||
pd.DataFrame(row_clusters,
|
||||
@@ -327,7 +316,6 @@ pd.DataFrame(row_clusters,
|
||||
for i in range(row_clusters.shape[0])])
|
||||
|
||||
|
||||
# In[16]:
|
||||
|
||||
|
||||
# 2. correct approach: Condensed distance matrix
|
||||
@@ -340,7 +328,6 @@ pd.DataFrame(row_clusters,
|
||||
for i in range(row_clusters.shape[0])])
|
||||
|
||||
|
||||
# In[17]:
|
||||
|
||||
|
||||
# 3. correct approach: Input sample matrix
|
||||
@@ -353,13 +340,10 @@ pd.DataFrame(row_clusters,
|
||||
for i in range(row_clusters.shape[0])])
|
||||
|
||||
|
||||
# In[18]:
|
||||
|
||||
|
||||
from scipy.cluster.hierarchy import dendrogram
|
||||
|
||||
# make dendrogram black (part 1/2)
|
||||
# from scipy.cluster.hierarchy import set_link_color_palette
|
||||
# set_link_color_palette(['black'])
|
||||
|
||||
row_dendr = dendrogram(row_clusters,
|
||||
@@ -377,7 +361,6 @@ plt.show()
|
||||
|
||||
# ## Attaching dendrograms to a heat map
|
||||
|
||||
# In[19]:
|
||||
|
||||
|
||||
# plot row dendrogram
|
||||
@@ -411,10 +394,8 @@ plt.show()
|
||||
|
||||
# ## Applying agglomerative clustering via scikit-learn
|
||||
|
||||
# In[20]:
|
||||
|
||||
|
||||
from sklearn.cluster import AgglomerativeClustering
|
||||
|
||||
ac = AgglomerativeClustering(n_clusters=3,
|
||||
affinity='euclidean',
|
||||
@@ -423,7 +404,6 @@ labels = ac.fit_predict(X)
|
||||
print('Cluster labels: %s' % labels)
|
||||
|
||||
|
||||
# In[21]:
|
||||
|
||||
|
||||
ac = AgglomerativeClustering(n_clusters=2,
|
||||
@@ -436,15 +416,12 @@ print('Cluster labels: %s' % labels)
|
||||
|
||||
# # Locating regions of high density via DBSCAN
|
||||
|
||||
# In[22]:
|
||||
|
||||
|
||||
|
||||
|
||||
# In[23]:
|
||||
|
||||
|
||||
from sklearn.datasets import make_moons
|
||||
|
||||
X, y = make_moons(n_samples=200, noise=0.05, random_state=0)
|
||||
plt.scatter(X[:, 0], X[:, 1])
|
||||
@@ -455,7 +432,6 @@ plt.show()
|
||||
|
||||
# K-means and hierarchical clustering:
|
||||
|
||||
# In[24]:
|
||||
|
||||
|
||||
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 3))
|
||||
@@ -490,10 +466,8 @@ plt.show()
|
||||
|
||||
# Density-based clustering:
|
||||
|
||||
# In[25]:
|
||||
|
||||
|
||||
from sklearn.cluster import DBSCAN
|
||||
|
||||
db = DBSCAN(eps=0.2, min_samples=5, metric='euclidean')
|
||||
y_db = db.fit_predict(X)
|
||||
@@ -520,7 +494,11 @@ plt.show()
|
||||
#
|
||||
# Readers may ignore the next cell.
|
||||
|
||||
# In[2]:
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
Python Machine Learning - Code Examples
|
||||
|
||||
|
||||
## Chapter 12: Implementing a Multilayer Arti cial Neural
|
||||
Network from Scratch
|
||||
|
||||
### Chapter Outline
|
||||
|
||||
- Modeling complex functions with arti cial neural networks
|
||||
- Single-layer neural network recap
|
||||
- Introducing the multilayer neural network architecture
|
||||
- Activating a neural network via forward propagation
|
||||
- Classifying handwritten digits
|
||||
- Obtaining the MNIST dataset
|
||||
- Implementing a multilayer perceptron
|
||||
- Training an artificial neural network
|
||||
- Computing the logistic cost function
|
||||
- Developing your intuition for backpropagation
|
||||
- Training neural networks via backpropagation
|
||||
- About the convergence in neural networks
|
||||
- A few last words about the neural network implementation
|
||||
- Summary
|
||||
|
||||
### A note on using the code examples
|
||||
|
||||
The recommended way to interact with the code examples in this book is via Jupyter Notebook (the `.ipynb` files). Using Jupyter Notebook, you will be able to execute the code step by step and have all the resulting outputs (including plots and images) all in one convenient document.
|
||||
|
||||

|
||||
|
||||
|
||||
|
||||
Setting up Jupyter Notebook is really easy: if you are using the Anaconda Python distribution, all you need to install jupyter notebook is to execute the following command in your terminal:
|
||||
|
||||
conda install jupyter notebook
|
||||
|
||||
Then you can launch jupyter notebook by executing
|
||||
|
||||
jupyter notebook
|
||||
|
||||
A window will open up in your browser, which you can then use to navigate to the target directory that contains the `.ipynb` file you wish to open.
|
||||
|
||||
**More installation and setup instructions can be found in the [README.md file of Chapter 1](../ch01/README.md)**.
|
||||
|
||||
**(Even if you decide not to install Jupyter Notebook, note that you can also view the notebook files on GitHub by simply clicking on them: [`ch12.ipynb`](ch12.ipynb))**
|
||||
|
||||
In addition to the code examples, I added a table of contents to each Jupyter notebook as well as section headers that are consistent with the content of the book. Also, I included the original images and figures in hope that these make it easier to navigate and work with the code interactively as you are reading the book.
|
||||
|
||||

|
||||
|
||||
|
||||
When I was creating these notebooks, I was hoping to make your reading (and coding) experience as convenient as possible! However, if you don't wish to use Jupyter Notebooks, I also converted these notebooks to regular Python script files (`.py` files) that can be viewed and edited in any plaintext editor.
|
||||
@@ -103,7 +103,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 2,
|
||||
"execution_count": 1,
|
||||
"metadata": {
|
||||
"collapsed": true
|
||||
},
|
||||
@@ -201,17 +201,17 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 5,
|
||||
"execution_count": 2,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"data": {
|
||||
"image/png": "iVBORw0KGgoAAAANSUhEUgAACEwAAAWDCAYAAADP0jOoAAABGWlDQ1BJQ0MgUHJvZmlsZQAAKJFj\nYGBSSCwoyGESYGDIzSspCnJ3UoiIjFJgf8jAycDGwMjAzsCcmFxc4BgQ4MMABDAaFXy7BlQJBJd1\nQWZhyuMFXCmpxclA+g8QZycXFJUwMDBmANnK5SUFIHYPkC2SlA1mLwCxi4AOBLK3gNjpEPYJsBoI\n+w5YTUiQM5D9AcjmSwKzmUB28aVD2AIgNtReEBB0TMlPSlUA+V7D0NLSQpNEPxAEJakVJSDaOb+g\nsigzPaNEwREYUqkKnnnJejoKRgaG5gwMoHCHqP4cCA5PRrEzCDEEQIjNkWBg8F/KwMDyByFm0svA\nsECHgYF/KkJMzZCBQUCfgWHfnOTSojKoMYxMxgwMhPgAlS5KE7hN+asAAAAJcEhZcwAALiMAAC4j\nAXilP3YAAEAASURBVHgB7N0PXFT3ne//d/cBpsRAi43sFu+GpJhU8f6w92q32l7tuNpW030M6Uab\nLZp2Y0oiXRMw7T4Ut9XF2yv4aJqIzS0mJPrbVNm42j/w2I22wSvRR6t7C9lAV/S20kp3MbfSShaq\nJIHHY+4ZUWBmvmeYGebM39fkQZj5nnO+f57f7znnI+c757zLY73ECwEEEEAAAQQQQAABBBBAAAEE\nEEAAAQQQQAABBBBAAAEEEEAAAQQQSCOBP0ijttJUBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQ\nQAABBBBAAAEEEEDgugATJhgICCCAAAIIIIAAAggggAACCCCAAAIIIIAAAggggAACCCCAAAIIIJB2\nAkyYSLsup8EIIIAAAggggAACCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAgggwIQJxgACCCCAAAII\nIIAAAggggAACCCCAAAIIIIAAAggggAACCCCAAAIIpJ0AEybSrstpMAIIIIAAAggggAACCCCAAAII\nIIAAAggggAACCCCAAAIIIIAAAggwYYIxgAACCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAggggAAC\nCCCAAAJpJ8CEibTrchqMAAIIIIAAAggggAACCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAkyYYAwg\ngAACCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAggggAACCCCAQNoJMGEi7bqcBiOAAAIIIIAAAggg\ngAACCCCAAAIIIIAAAggggAACCCCAAAIIIIAAEyYYAwgggAACCCCAAAIIIIAAAggggAACCCCAAAII\nIIAAAggggAACCCCQdgJMmEi7LqfBCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAggggAACCCCAAAII\nIMCECcYAAggggAACCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAggggAACCKSdABMm0q7LaTACCCCA\nAAIIIIAAAggggAACCCCAAAIIIIAAAggggAACCCCAAAIIMGGCMYAAAggggAACCCCAAAIIIIAAAggg\ngAACCCCAAAIIIIAAAggggAACaSfAhIm063IajAACCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAggg\ngAACCCCAAAJMmGAMIIAAAggggAACCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAggggEDaCTBhIu26\nnAYjgAACCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAggggAACCCCAABMmGAMIIIAAAggggAACCCCA\nAAIIIIAAAggggAACCCCAAAIIIIAAAgggkHYCTJhIuy6nwQgggAACCCCAAAIIIIAAAggggAACCCCA\nAAIIIIAAAggggAACCCDAhAnGAAIIIIAAAggggAACCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAgik\nnQATJtKuy2kwAggggAACCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAggggAACCDBhgjGAAAIIIIAA\nAggggAACCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAmknwISJtOtyGowAAggggAACCCCAAAIIIIAA\nAggggAACCCCAAAIIIIAAAggggAACTJhgDCCAAAIIIIAAAggggAACCCCAAAIIIIAAAggggAACCCCA\nAAIIIIBA2gkwYSLtupwGI4AAAggggAACCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAggggAATJhgD\nCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAggggAACCCCAAAIIIJB2AkyYSLsup8EIIIAAAggggAAC\nCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAgggwIQJxgACCCCAAAIIIIAAAggggAACCCCAAAIIIIAA\nAggggAACCCCAAAIIpJ0AEybSrstpMAIIIIAAAggggAACCCCAAAIIIIAAAggggAACCCCAAAIIIIAA\nAggwYYIxgAACCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAggggAACCCCAAAJpJ8CEibTrchqMAAII\nIIAAAggggAACCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAkyYYAwggAACCCCAAAIIIIAAAggggAAC\nCCCAAAIIIIAAAggggAACCCCAQNoJMGEi7bqcBiOAAAIIIIAAAggggAACCCCAAAIIIIAAAggggAAC\nCCCAAAIIIIAAEyYYAwgggAACCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAggggAACCCCQdgJMmEi7\nLqfBCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAggggAACCCCAAAIIIMCECcYAAggggAACCCCAAAII\nIIAAAggggAACCCCAAAIIIIAAAggggAACCKSdABMm0q7LaTACCCCAAAIIIIAAAggggAACCCCAAAII\nIIAAAggggAACCCCAAAIIMGGCMYAAAggggAACCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAggggAAC\naSfAhIm063IajAACCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAggggAACCCCAAAJMmGAMIIAAAggg\ngAACCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAggggEDaCTBhIu26nAYjgAACCCCAAAIIIIAAAggg\ngAACCCCAAAIIIIAAAggggAACCCCAABMmGAMIIIAAAggggAACCCCAAAIIIIAAAggggAACCCCAAAII\nIIAAAgggkHYCTJhIuy6nwQgggAACCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAggggAACCCDAhAnG\nAAIIIIAAAggggAACCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAgiknQATJtKuy2kwAggggAACCCCA\nAAIIIIAAAggggAACCCCAAAIIIIAAAggggAACCDBhgjGAAAIIIIAAAggggAACCCCAAAIIIIAAAggg\ngAACCCCAAAIIIIAAAmknwISJtOtyGowAAggggAACCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAggg\ngAACTJhgDCCAAAIIIIAAAggggAACCCCAAAIIIIAAAggggAACCCCAAAIIIIBA2gkwYSLtupwGI4AA\nAggggAACCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAggggAATJhgDCCCAAAIIIIAAAggggAACCCCA\nAAIIIIAAAggggAACCCCAAAIIIJB2AkyYSLsup8EIIIAAAggggAACCCCAAAIIIIAAAggggAACCCCA\nAAIIIIAAAgggwIQJxgACCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAggggAACCCCAAAIIpJ0AEybS\nrstpMAIIIIAAAggggAACCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAggwYYIxgAACCCCAAAIIIIAA\nAggggAACCCCAAAIIIIAAAggggAACCCCAAAJpJ8CEibTrchqMAAIIIIAAAggggAACCCCAAAIIIIAA\nAggggAACCCCAAAIIIIAAAkyYYAwggAACCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAggggAACCCCA\nQNoJMGEi7bqcBiOAAAIIIIAAAggggAACCCCAAAIIIIAAAggggAACCCCAAAIIIIAAEyYYAwgggAAC\nCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAggggAACCCCQdgJMmEi7LqfBCCCAAAIIIIAAAggggAAC\nCCCAAAIIIIAAAggggAACCCCAAAIIIMCECcYAAggggAACCCCAAAIIIIAAAggggAACCCCAAAIIIIAA\nAggggAACCKSdABMm0q7LaTACCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAggggAACCCCAAAIIZEAQ\nXGDw0nn9/I2rvisNS7d/cL4KcuHzhUnDT0N96uz6tawhMf5ifIxb8A4BS2Cov0ddv/ytj8WwMvXB\n+cVKisPoyKC6u17XmZ/8RG2vder1X7yuy5dHm9PV1aWiIpdmf+hDWn7vp/TJZR/TnPxsn7byAYFU\nFBjq61ZX95uyduXxl4Pnv+SKx0Z06XyHfMNH66h3+wdVXJA77hX1d/EqN+oNSawMifUSqz+oTcIJ\nJH2c5xUl1ku4cUWFEEAAAQQQQAABBBBAAAEEEIilwLs81iuWBSZXWYPaMy9HFV2Bta49fUWbFzn5\nR+/AMklJPIH2Pcu0sKI1oGKMjwASEtJYwLyfFOn0wFktSuC5BUN9nXqp/hmt394QVu+5ympV8zdf\n0qKCBG5cWC1iZQT8BQa1d1mOylv90yVnzn9JFo8NtmtZzkL58xTVntbZzYsC0aKVEq9yo1X/BM3H\nfA5zaqwnKALVQiCIgHkfSfw4z9skYr0gHcsiBBBAAAEEEEAAAQQQQAABBNJIgEdyTLine truncated
|
||||
"image/png": "iVBORw0KGgoAAAANSUhEUgAACEYAAAWECAYAAADF9ZPZAAABGWlDQ1BJQ0MgUHJvZmlsZQAAKJFj\nYGBSSCwoyGESYGDIzSspCnJ3UoiIjF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gggAACCCCAAAIIIIAA\nAggggAACCCCAAAIIIIAAAggggAACCCDAwgjGAAIIIIAAAggggAACCCCAAAIIIIAAAggggAACCCCA\nAAIIIIAAAghkrQALI7K2a2kYAggggAACCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAggggAACCLAw\ngjGAAAIIIIAAAggggAACCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAlkrwMKIrO1aGoYAAggggAAC\nCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAggggAACLIxgDCCAAAIIIIAAAggggAACCCCAAAIIIIAA\nAggggAACCCCAAAIIIIBA1gqwMCJru5aGIYAAAggggAACCCCAAAIIIIAAAggggAACCCCAAAIIIIAA\nAggggAALIxgDCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAggggAACCCCAAAIIIJC1AiyMyNqupWEI\nIIAAAggggAACCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAgggwMIIxgACCCCAAAIIIIAAAggggAAC\nCCCAAAIIIIAAAggggAACCCCAAAIIZK0ACyOytmtpGAIIIIAAAggggAACCCCAAAIIIIAAAggggAAC\nCCCAAAIIIIAAAgiwMIIxgAACCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAggggAACCCCAAAJZK8DC\niKztWhqGAAIIIIAAAggggAACCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAiyMYAwggAACCCCAAAII\nIIAAAggggAACCCCAAAIIIIAAAggggAACCCCAQNYKsDAia7uWhiGAAAIIIIAAAggggAACCCCAAAII\nIIAAAggggAACCCCAAAIIIIAACyMYAwgggAACCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAggggAAC\nCCCQtQIsjMjarqVhCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAggggAACCCCAAAIIIMDCCMYAAggg\ngAACCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAggggAACCGStAAsjsrZraRgCCCCAAAIIIIAAAggg\ngAACCCCAAAIIIIAAAggggAACCCCAAAIIsDCCMYAAAggggAACCCCAAAIIIIAAAggggAACCCCAAAII\nIIAAAggggAACWSvAwois7VoahgACCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAggggAACCCCAAAIs\njGAMIIAAAggggAACCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAggggEDWCrAwImu7loYhgAACCCCA\nAAIIIIAAAggggAACCCCAAAIIIIAAAggggAACCCCAAAsjGAMIIIAAAggggAACCCCAAAIIIIAAAggg\ngAACCCCAAAIIIIAAAgggkLUCLIzI2q6lYQgggAACCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAggg\ngAACCCDAwgjGAAIIIIAAAggggAACCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAghkrQALI7K2a2kY\nAggggAACCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAggggAACCLAwgjGAAAIIIIAAAggggAACCCCA\nAAIIIIAAAggggAACCCCAAAIIIIAAAlkrwMKIrO1aGoYAAggggAACCCCAAAIIIIAAAggggAACCCCA\nAAIIIIAAAggggAACLIxgDCCAAAIIIIAAAggggAACCCCAAAIIIIAAAggggAACCCCAAAIIIIBA1gqw\nMCJru5aGIYAAAggggAACCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAggggEDOZCMYunxeP37jWnCz\nR6S7PzBPxQWTjiPYgU/ScL+6e34ua0iMvxgf4xa8Q8ASGB7oU89PfxlkMaJcfWBemTLiMDo6pN6e\n13X6Rz9S52vdev0nr+vKlZvN6enpUWmpR7M++EEt/ciH9adL/kizi/KD2soHBLJRYLi/Vz29b8ra\nlcdfSTz/Zd58bFSXz3cpeAppHfnu/oDKigvGzRL6Lh1lJrQB7syMuZ47+4VauUog4+d6MWn2a/8T\nn9DTP7ESd1zRF7pO6/Ey5oAxUZIIAQQQQAABBBBAAAEEEEAAAZcKvMtnvVxatyRUa0h75k5TVU94\n1vWnrmrzwmR9sR1eHiHuFDizZ4kWVHWEVY7xEUZCwCQWMO8npTo1eFYLXfz98XB/t15qfE7rtjdF\n1XueinrV/c3ntLDYxY2LqkVERiBUYEh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FAwCUCHOeS3hHdzVVauZtVEUmHpgAEEEAAAQQQQAABBBBAAAEEXCbA\nwgiXdQjVGRcYHRrQ8PhH3iGAwA2BfD2yo8FgUapNK509CiIw8WTaz2av2aln1y9XUV6ggN37Anm3\nHdAB21tHNOnf+jhC2ekRjkByBBJ7/EtOHckVAQQQiEcgsce5yTTPc6o+cHqP5q1tchqdeAgggAAC\nCCCAAAIIIIAAAgggkEUCLIzIos7MpqYM9x5W7rQ/VifPBcimbqUtCRKYsXijLp06oAqvRx6PR97y\nWp24eFreYkdX/MdqwX42RmHzJl9rvnJEdstNLr/5lk06ghFAIFkCiTr+Jat+5IsAALine truncated
|
||||
"text/plain": [
|
||||
"<IPython.core.display.Image object>"
|
||||
]
|
||||
},
|
||||
"execution_count": 5,
|
||||
"execution_count": 2,
|
||||
"metadata": {
|
||||
"image/png": {
|
||||
"width": 500
|
||||
@@ -615,7 +615,7 @@
|
||||
" Learning rate.\n",
|
||||
" shuffle : bool (default: True)\n",
|
||||
" Shuffles training data every epoch if True to prevent circles.\n",
|
||||
" minibatche_size : int (default: 1)\n",
|
||||
" minibatch_size : int (default: 1)\n",
|
||||
" Number of training samples per minibatch.\n",
|
||||
" seed : int (default: None)\n",
|
||||
" Random seed for initalizing weights and shuffling.\n",
|
||||
@@ -1324,7 +1324,7 @@
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"[NbConvertApp] Converting notebook ch12.ipynb to script\n",
|
||||
"[NbConvertApp] Writing 19205 bytes to ch12.py\n"
|
||||
"[NbConvertApp] Writing 19365 bytes to ch12.py\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
|
||||
@@ -1,6 +1,14 @@
|
||||
|
||||
# coding: utf-8
|
||||
|
||||
|
||||
import os
|
||||
import struct
|
||||
import numpy as np
|
||||
import sys
|
||||
import gzip
|
||||
import shutil
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
# *Python Machine Learning 2nd Edition* by [Sebastian Raschka](https://sebastianraschka.com), Packt Publishing Ltd. 2017
|
||||
#
|
||||
# Code Repository: https://github.com/rasbt/python-machine-learning-book-2nd-edition
|
||||
@@ -14,7 +22,6 @@
|
||||
|
||||
# Note that the optional watermark extension is a small IPython notebook plugin that I developed to make the code reproducible. You can just skip the following line(s).
|
||||
|
||||
# In[1]:
|
||||
|
||||
|
||||
|
||||
@@ -38,10 +45,8 @@
|
||||
# - [Summary](#Summary)
|
||||
|
||||
|
||||
# In[2]:
|
||||
|
||||
|
||||
from IPython.display import Image
|
||||
|
||||
|
||||
# # Modeling complex functions with artificial neural networks
|
||||
@@ -50,7 +55,6 @@ from IPython.display import Image
|
||||
|
||||
# ## Single-layer neural network recap
|
||||
|
||||
# In[3]:
|
||||
|
||||
|
||||
|
||||
@@ -58,12 +62,10 @@ from IPython.display import Image
|
||||
|
||||
# ## Introducing the multi-layer neural network architecture
|
||||
|
||||
# In[4]:
|
||||
|
||||
|
||||
|
||||
|
||||
# In[5]:
|
||||
|
||||
|
||||
|
||||
@@ -71,7 +73,6 @@ from IPython.display import Image
|
||||
|
||||
# ## Activating a neural network via forward propagation
|
||||
|
||||
# In[6]:
|
||||
|
||||
|
||||
|
||||
@@ -97,12 +98,8 @@ from IPython.display import Image
|
||||
# in your local MNIST download directory, or, using your favorite unzipping tool if you are working with a machine running on Microsoft Windows. The images are stored in byte form, and using the following function, we will read them into NumPy arrays that we will use to train our MLP.
|
||||
#
|
||||
|
||||
# In[7]:
|
||||
|
||||
|
||||
import os
|
||||
import struct
|
||||
import numpy as np
|
||||
|
||||
def load_mnist(path, kind='train'):
|
||||
"""Load MNIST data from `path`"""
|
||||
@@ -127,19 +124,14 @@ def load_mnist(path, kind='train'):
|
||||
return images, labels
|
||||
|
||||
|
||||
# In[8]:
|
||||
|
||||
|
||||
|
||||
|
||||
# In[9]:
|
||||
|
||||
|
||||
# unzips mnist
|
||||
|
||||
import sys
|
||||
import gzip
|
||||
import shutil
|
||||
|
||||
if (sys.version_info > (3, 0)):
|
||||
writemode = 'wb'
|
||||
@@ -152,14 +144,12 @@ for z in zipped_mnist:
|
||||
outfile.write(decompressed.read())
|
||||
|
||||
|
||||
# In[10]:
|
||||
|
||||
|
||||
X_train, y_train = load_mnist('', kind='train')
|
||||
print('Rows: %d, columns: %d' % (X_train.shape[0], X_train.shape[1]))
|
||||
|
||||
|
||||
# In[11]:
|
||||
|
||||
|
||||
X_test, y_test = load_mnist('', kind='t10k')
|
||||
@@ -168,10 +158,8 @@ print('Rows: %d, columns: %d' % (X_test.shape[0], X_test.shape[1]))
|
||||
|
||||
# Visualize the first digit of each class:
|
||||
|
||||
# In[12]:
|
||||
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
fig, ax = plt.subplots(nrows=2, ncols=5, sharex=True, sharey=True,)
|
||||
ax = ax.flatten()
|
||||
@@ -188,7 +176,6 @@ plt.show()
|
||||
|
||||
# Visualize 25 different versions of "7":
|
||||
|
||||
# In[13]:
|
||||
|
||||
|
||||
fig, ax = plt.subplots(nrows=5, ncols=5, sharex=True, sharey=True,)
|
||||
@@ -204,10 +191,8 @@ plt.tight_layout()
|
||||
plt.show()
|
||||
|
||||
|
||||
# In[14]:
|
||||
|
||||
|
||||
import numpy as np
|
||||
|
||||
np.savez_compressed('mnist_scaled.npz',
|
||||
X_train=X_train,
|
||||
@@ -216,14 +201,12 @@ np.savez_compressed('mnist_scaled.npz',
|
||||
y_test=y_test)
|
||||
|
||||
|
||||
# In[15]:
|
||||
|
||||
|
||||
mnist = np.load('mnist_scaled.npz')
|
||||
mnist.files
|
||||
|
||||
|
||||
# In[16]:
|
||||
|
||||
|
||||
X_train, y_train, X_test, y_test = [mnist[f] for f in ['X_train', 'y_train',
|
||||
@@ -237,11 +220,8 @@ X_train.shape
|
||||
|
||||
# ## Implementing a multi-layer perceptron
|
||||
|
||||
# In[17]:
|
||||
|
||||
|
||||
import numpy as np
|
||||
import sys
|
||||
|
||||
|
||||
class NeuralNetMLP(object):
|
||||
@@ -260,7 +240,7 @@ class NeuralNetMLP(object):
|
||||
Learning rate.
|
||||
shuffle : bool (default: True)
|
||||
Shuffles training data every epoch if True to prevent circles.
|
||||
minibatche_size : int (default: 1)
|
||||
minibatch_size : int (default: 1)
|
||||
Number of training samples per minibatch.
|
||||
seed : int (default: None)
|
||||
Random seed for initalizing weights and shuffling.
|
||||
@@ -495,7 +475,6 @@ class NeuralNetMLP(object):
|
||||
return self
|
||||
|
||||
|
||||
# In[18]:
|
||||
|
||||
|
||||
n_epochs = 200
|
||||
@@ -511,7 +490,6 @@ if 'TRAVIS' in os.environ:
|
||||
n_epochs = 20
|
||||
|
||||
|
||||
# In[19]:
|
||||
|
||||
|
||||
nn = NeuralNetMLP(n_hidden=100,
|
||||
@@ -565,10 +543,8 @@ nn.fit(X_train=X_train[:55000],
|
||||
#
|
||||
#
|
||||
|
||||
# In[20]:
|
||||
|
||||
|
||||
import numpy as np
|
||||
|
||||
a = np.arange(5)
|
||||
b = a
|
||||
@@ -583,10 +559,8 @@ print('a & b', np.may_share_memory(a, b))
|
||||
#
|
||||
# ---
|
||||
|
||||
# In[21]:
|
||||
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
plt.plot(range(nn.epochs), nn.eval_['cost'])
|
||||
plt.ylabel('Cost')
|
||||
@@ -595,7 +569,6 @@ plt.xlabel('Epochs')
|
||||
plt.show()
|
||||
|
||||
|
||||
# In[22]:
|
||||
|
||||
|
||||
plt.plot(range(nn.epochs), nn.eval_['train_acc'],
|
||||
@@ -609,7 +582,6 @@ plt.legend()
|
||||
plt.show()
|
||||
|
||||
|
||||
# In[23]:
|
||||
|
||||
|
||||
y_test_pred = nn.predict(X_test)
|
||||
@@ -619,7 +591,6 @@ acc = (np.sum(y_test == y_test_pred)
|
||||
print('Test accuracy: %.2f%%' % (acc * 100))
|
||||
|
||||
|
||||
# In[24]:
|
||||
|
||||
|
||||
miscl_img = X_test[y_test != y_test_pred][:25]
|
||||
@@ -647,7 +618,6 @@ plt.show()
|
||||
|
||||
# ## Computing the logistic cost function
|
||||
|
||||
# In[25]:
|
||||
|
||||
|
||||
|
||||
@@ -659,12 +629,10 @@ plt.show()
|
||||
|
||||
# ## Training neural networks via backpropagation
|
||||
|
||||
# In[26]:
|
||||
|
||||
|
||||
|
||||
|
||||
# In[6]:
|
||||
|
||||
|
||||
|
||||
@@ -672,7 +640,6 @@ plt.show()
|
||||
|
||||
# # Convergence in neural networks
|
||||
|
||||
# In[28]:
|
||||
|
||||
|
||||
|
||||
@@ -683,3 +650,11 @@ plt.show()
|
||||
# # Summary
|
||||
|
||||
# ...
|
||||
|
||||
# ---
|
||||
#
|
||||
# Readers may ignore the next cell.
|
||||
|
||||
|
||||
|
||||
|
||||
|
Before Width: | Height: | Size: 391 KiB After Width: | Height: | Size: 391 KiB |
@@ -18,7 +18,7 @@ class NeuralNetMLP(object):
|
||||
Learning rate.
|
||||
shuffle : bool (default: True)
|
||||
Shuffles training data every epoch if True to prevent circles.
|
||||
minibatche_size : int (default: 1)
|
||||
minibatch_size : int (default: 1)
|
||||
Number of training samples per minibatch.
|
||||
seed : int (default: None)
|
||||
Random seed for initalizing weights and shuffling.
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
Python Machine Learning - Code Examples
|
||||
|
||||
|
||||
## Chapter 13: Parallelizing Neural Network Training with TensorFlow
|
||||
|
||||
### Chapter Outline
|
||||
|
||||
- TensorFlow and training performance
|
||||
- What is TensorFlow?
|
||||
- How we will learn TensorFlow
|
||||
- First steps with TensorFlow
|
||||
- Working with array structures
|
||||
- Developing a simple model with the low-level TensorFlow API
|
||||
- Training neural networks ef ciently with high-level TensorFlow APIs
|
||||
- Building multilayer neural networks using TensorFlow's Layers API
|
||||
- Developing a multilayer neural network with Keras
|
||||
- Choosing activation functions for multilayer networks
|
||||
- Logistic function recap
|
||||
- Estimating class probabilities in multiclass classification via the softmax function
|
||||
- Broadening the output spectrum using a hyperbolic tangent
|
||||
- Rectified linear unit activation
|
||||
- Summary
|
||||
|
||||
### A note on using the code examples
|
||||
|
||||
The recommended way to interact with the code examples in this book is via Jupyter Notebook (the `.ipynb` files). Using Jupyter Notebook, you will be able to execute the code step by step and have all the resulting outputs (including plots and images) all in one convenient document.
|
||||
|
||||

|
||||
|
||||
|
||||
|
||||
Setting up Jupyter Notebook is really easy: if you are using the Anaconda Python distribution, all you need to install jupyter notebook is to execute the following command in your terminal:
|
||||
|
||||
conda install jupyter notebook
|
||||
|
||||
Then you can launch jupyter notebook by executing
|
||||
|
||||
jupyter notebook
|
||||
|
||||
A window will open up in your browser, which you can then use to navigate to the target directory that contains the `.ipynb` file you wish to open.
|
||||
|
||||
**More installation and setup instructions can be found in the [README.md file of Chapter 1](../ch01/README.md)**.
|
||||
|
||||
**(Even if you decide not to install Jupyter Notebook, note that you can also view the notebook files on GitHub by simply clicking on them: [`ch13.ipynb`](ch13.ipynb))**
|
||||
|
||||
In addition to the code examples, I added a table of contents to each Jupyter notebook as well as section headers that are consistent with the content of the book. Also, I included the original images and figures in hope that these make it easier to navigate and work with the code interactively as you are reading the book.
|
||||
|
||||

|
||||
|
||||
|
||||
When I was creating these notebooks, I was hoping to make your reading (and coding) experience as convenient as possible! However, if you don't wish to use Jupyter Notebooks, I also converted these notebooks to regular Python script files (`.py` files) that can be viewed and edited in any plaintext editor.
|
||||
@@ -65,12 +65,12 @@
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Sebastian Raschka & Vahid Mirjalili \n",
|
||||
"last updated: 2017-09-06 \n",
|
||||
"last updated: 2017-09-19 \n",
|
||||
"\n",
|
||||
"CPython 3.6.1\n",
|
||||
"IPython 6.1.0\n",
|
||||
"\n",
|
||||
"numpy 1.12.1\n",
|
||||
"numpy 1.13.1\n",
|
||||
"tensorflow 1.3.0\n",
|
||||
"matplotlib 2.0.2\n"
|
||||
]
|
||||
@@ -430,7 +430,7 @@
|
||||
"data": {
|
||||
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAbYAAAEmCAYAAAAOb7UzAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\n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CfQ6ytJGQzadxh9VbdZxMRKQb5BNsZ7v7c\nwAd3XwWc6e7Ph1dW6cge7UCiy5EiIsUgn2tn683sm8APgs/vC9ZVA72hVVYiptZWMXfqRD2bTUSk\nSOTTYvsQ0AZ8PnhtAxaTC7VLwiutdGQzaXX5FxEpEqO22Nz9IPC/g9fx9Lc5kG1I8dPWbezq7GZG\nXU3U5YiIlLVRW2xmdoGZ/cLM1prZhoFXIYorFWfP1UBtEZFikc89truBzwErgb5wyylNZ81OkUwY\nrVs6uPTMmVGXIyJS1vIJtv3u/tPQKylhNZVJ5p9Upw4kIiJFIJ9g+42ZfRVYBhweWDl4CIDkOpD8\nrHUb/f1OImFRlyMiUrbyCbaLj3sHcOAt419O6WpqSPP9p15i054uTq2fFHU5IiJlK59ekW8uRCGl\nLpsJOpC0dSjYREQiNGywmdk17n6/mX1qqO3u/o2RDmxmdwHvBna5+4Jg3ReB64H2YLcvuPvDYym8\n2Jw2YxK1VUlat+zj6rMboi5HRKRsjdRimxK814/x2N8FbgXuPW79v7j718d4zKKVTLine truncated
|
||||
"text/plain": [
|
||||
"<matplotlib.figure.Figure at 0x112fc7f60>"
|
||||
"<matplotlib.figure.Figure at 0x11bda1c50>"
|
||||
]
|
||||
},
|
||||
"metadata": {},
|
||||
@@ -471,7 +471,7 @@
|
||||
"data": {
|
||||
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAagAAAEYCAYAAAAJeGK1AAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzt3XlwlPed7/v3T1JrQYDEDkbGyBgDEgIBYjGS2BqhpeOT\ncZwa25VlkplTLtfcOPH4JB58JlOxMzN1PSnXGadi58647JwZV+aOJ9dhToG7kQCx7yAWy2wWu8Vi\nhAwNCCR1S7/7h3BbzSpArae79XlVpQq+/XQ/37RBH/rp3/P7GmstIiIi0SbB6QZERERuRQElIiJR\nSQElIiJRSQElIiJRSQElIiJRSQElIiJRSQElIiJRSQElIiJR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ligFvihtVZbEohI3AsEAmzcuJFNmzaFjV3v27cvZWVl\n5OTkhL62uFM4deXxeBWxgDLGjAR+DORYa68ZY/4APAv8a6TOKSISDerq6li+fDkXLlwI1YwxzJgx\ng/nz54e2M5M7i/QlviQgzRgTAPoApyN8PhERx1y6dInKykoOHDgQVh85ciQej4cRILine truncated
|
||||
"text/plain": [
|
||||
"<matplotlib.figure.Figure at 0x116344908>"
|
||||
"<matplotlib.figure.Figure at 0x11be4a160>"
|
||||
]
|
||||
},
|
||||
"metadata": {},
|
||||
@@ -701,7 +701,7 @@
|
||||
" y_copy = data[:, -1].astype(int)\n",
|
||||
" \n",
|
||||
" for i in range(0, X.shape[0], batch_size):\n",
|
||||
" yield (X[i:i+batch_size, :], y[i:i+batch_size])"
|
||||
" yield (X_copy[i:i+batch_size, :], y_copy[i:i+batch_size])"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -778,7 +778,7 @@
|
||||
" training_loss = []\n",
|
||||
" batch_generator = create_batch_generator(\n",
|
||||
" X_train_centered, y_train, \n",
|
||||
" batch_size=64, shuffle=True)\n",
|
||||
" batch_size=64)\n",
|
||||
" for batch_X, batch_y in batch_generator:\n",
|
||||
" ## prepare a dict to feed data to our network:\n",
|
||||
" feed = {tf_x:batch_X, tf_y:batch_y}\n",
|
||||
@@ -1389,7 +1389,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 1,
|
||||
"execution_count": 2,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
@@ -1397,7 +1397,7 @@
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"[NbConvertApp] Converting notebook ch13.ipynb to script\n",
|
||||
"[NbConvertApp] Writing 18188 bytes to ch13.py\n"
|
||||
"[NbConvertApp] Writing 18184 bytes to ch13.py\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
|
||||
@@ -1,6 +1,16 @@
|
||||
|
||||
# coding: utf-8
|
||||
|
||||
|
||||
import tensorflow as tf
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
import sys
|
||||
import gzip
|
||||
import shutil
|
||||
import os
|
||||
import struct
|
||||
import tensorflow.contrib.keras as keras
|
||||
|
||||
# *Python Machine Learning 2nd Edition* by [Sebastian Raschka](https://sebastianraschka.com) and Vahid Mirjalili, Packt Publishing Ltd. 2017
|
||||
#
|
||||
# Code Repository: https://github.com/rasbt/python-machine-learning-book-2nd-edition
|
||||
@@ -29,29 +39,24 @@
|
||||
|
||||
# Note that the optional watermark extension is a small IPython notebook plugin that I developed to make the code reproducible. You can just skip the following line(s).
|
||||
|
||||
# In[1]:
|
||||
|
||||
|
||||
|
||||
|
||||
# *The use of `watermark` is optional. You can install this IPython extension via "`pip install watermark`". For more information, please see: https://github.com/rasbt/watermark.*
|
||||
|
||||
# In[2]:
|
||||
|
||||
|
||||
|
||||
|
||||
# In[3]:
|
||||
|
||||
|
||||
from IPython.display import Image
|
||||
|
||||
|
||||
# ## Building, compiling, and running machine learning models with TensorFlow
|
||||
|
||||
# ### Performance challenges of expensive computations
|
||||
|
||||
# In[4]:
|
||||
|
||||
|
||||
|
||||
@@ -60,10 +65,8 @@ from IPython.display import Image
|
||||
|
||||
# ### First steps with TensorFlow
|
||||
|
||||
# In[5]:
|
||||
|
||||
|
||||
import tensorflow as tf
|
||||
|
||||
## create a graph
|
||||
g = tf.Graph()
|
||||
@@ -86,7 +89,6 @@ with tf.Session(graph=g) as sess:
|
||||
t, sess.run(z, feed_dict={x:t})))
|
||||
|
||||
|
||||
# In[6]:
|
||||
|
||||
|
||||
with tf.Session(graph=g) as sess:
|
||||
@@ -96,11 +98,8 @@ with tf.Session(graph=g) as sess:
|
||||
|
||||
# ### Working with array structures
|
||||
|
||||
# In[7]:
|
||||
|
||||
|
||||
import tensorflow as tf
|
||||
import numpy as np
|
||||
|
||||
|
||||
g = tf.Graph()
|
||||
@@ -132,11 +131,8 @@ with tf.Session(graph=g) as sess:
|
||||
|
||||
# ### Developing a simple model with low-level TensorFlow API
|
||||
|
||||
# In[8]:
|
||||
|
||||
|
||||
import tensorflow as tf
|
||||
import numpy as np
|
||||
|
||||
X_train = np.arange(10).reshape((10, 1))
|
||||
y_train = np.array([1.0, 1.3, 3.1,
|
||||
@@ -145,7 +141,6 @@ y_train = np.array([1.0, 1.3, 3.1,
|
||||
9.0])
|
||||
|
||||
|
||||
# In[9]:
|
||||
|
||||
|
||||
class TfLinreg(object):
|
||||
@@ -198,13 +193,11 @@ class TfLinreg(object):
|
||||
self.optimizer = optimizer.minimize(self.mean_cost)
|
||||
|
||||
|
||||
# In[10]:
|
||||
|
||||
|
||||
lrmodel = TfLinreg(x_dim=X_train.shape[1], learning_rate=0.01)
|
||||
|
||||
|
||||
# In[11]:
|
||||
|
||||
|
||||
def train_linreg(sess, model, X_train, y_train, num_epochs=10):
|
||||
@@ -221,17 +214,14 @@ def train_linreg(sess, model, X_train, y_train, num_epochs=10):
|
||||
return training_costs
|
||||
|
||||
|
||||
# In[12]:
|
||||
|
||||
|
||||
sess = tf.Session(graph=lrmodel.g)
|
||||
training_costs = train_linreg(sess, lrmodel, X_train, y_train)
|
||||
|
||||
|
||||
# In[13]:
|
||||
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
plt.plot(range(1,len(training_costs) + 1), training_costs)
|
||||
plt.tight_layout()
|
||||
@@ -241,7 +231,6 @@ plt.ylabel('Training Cost')
|
||||
plt.show()
|
||||
|
||||
|
||||
# In[14]:
|
||||
|
||||
|
||||
def predict_linreg(sess, model, X_test):
|
||||
@@ -250,7 +239,6 @@ def predict_linreg(sess, model, X_test):
|
||||
return y_pred
|
||||
|
||||
|
||||
# In[15]:
|
||||
|
||||
|
||||
plt.scatter(X_train, y_train,
|
||||
@@ -275,15 +263,10 @@ plt.show()
|
||||
|
||||
# - See Chapter 12 for details on MNIST
|
||||
|
||||
# In[16]:
|
||||
|
||||
|
||||
# unzips mnist
|
||||
|
||||
import sys
|
||||
import gzip
|
||||
import shutil
|
||||
import os
|
||||
|
||||
if (sys.version_info > (3, 0)):
|
||||
writemode = 'wb'
|
||||
@@ -296,10 +279,8 @@ for z in zipped_mnist:
|
||||
outfile.write(decompressed.read())
|
||||
|
||||
|
||||
# In[17]:
|
||||
|
||||
|
||||
import struct
|
||||
|
||||
def load_mnist(path, kind='train'):
|
||||
"""Load MNIST data from `path`"""
|
||||
@@ -324,7 +305,6 @@ def load_mnist(path, kind='train'):
|
||||
return images, labels
|
||||
|
||||
|
||||
# In[18]:
|
||||
|
||||
|
||||
## loading the data
|
||||
@@ -349,10 +329,8 @@ print(X_train_centered.shape, y_train.shape)
|
||||
print(X_test_centered.shape, y_test.shape)
|
||||
|
||||
|
||||
# In[19]:
|
||||
|
||||
|
||||
import tensorflow as tf
|
||||
|
||||
n_features = X_train_centered.shape[1]
|
||||
n_classes = 10
|
||||
@@ -391,7 +369,6 @@ with g.as_default():
|
||||
}
|
||||
|
||||
|
||||
# In[20]:
|
||||
|
||||
|
||||
## define cost function and optimizer:
|
||||
@@ -407,7 +384,6 @@ with g.as_default():
|
||||
init_op = tf.global_variables_initializer()
|
||||
|
||||
|
||||
# In[21]:
|
||||
|
||||
|
||||
def create_batch_generator(X, y, batch_size=128, shuffle=False):
|
||||
@@ -421,10 +397,9 @@ def create_batch_generator(X, y, batch_size=128, shuffle=False):
|
||||
y_copy = data[:, -1].astype(int)
|
||||
|
||||
for i in range(0, X.shape[0], batch_size):
|
||||
yield (X[i:i+batch_size, :], y[i:i+batch_size])
|
||||
yield (X_copy[i:i+batch_size, :], y_copy[i:i+batch_size])
|
||||
|
||||
|
||||
# In[22]:
|
||||
|
||||
|
||||
## create a session to launch the graph
|
||||
@@ -438,7 +413,7 @@ for epoch in range(50):
|
||||
training_loss = []
|
||||
batch_generator = create_batch_generator(
|
||||
X_train_centered, y_train,
|
||||
batch_size=64, shuffle=True)
|
||||
batch_size=64)
|
||||
for batch_X, batch_y in batch_generator:
|
||||
## prepare a dict to feed data to our network:
|
||||
feed = {tf_x:batch_X, tf_y:batch_y}
|
||||
@@ -451,7 +426,6 @@ for epoch in range(50):
|
||||
))
|
||||
|
||||
|
||||
# In[23]:
|
||||
|
||||
|
||||
## do prediction on the test set:
|
||||
@@ -465,7 +439,6 @@ print('Test Accuracy: %.2f%%' % (
|
||||
|
||||
# ### Developing Multilayer Neural Networks with Keras
|
||||
|
||||
# In[24]:
|
||||
|
||||
|
||||
X_train, y_train = load_mnist('./', kind='train')
|
||||
@@ -489,17 +462,13 @@ print(X_train_centered.shape, y_train.shape)
|
||||
print(X_test_centered.shape, y_test.shape)
|
||||
|
||||
|
||||
# In[25]:
|
||||
|
||||
|
||||
import tensorflow as tf
|
||||
import tensorflow.contrib.keras as keras
|
||||
|
||||
np.random.seed(123)
|
||||
tf.set_random_seed(123)
|
||||
|
||||
|
||||
# In[26]:
|
||||
|
||||
|
||||
y_train_onehot = keras.utils.to_categorical(y_train)
|
||||
@@ -508,7 +477,6 @@ print('First 3 labels: ', y_train[:3])
|
||||
print('\nFirst 3 labels (one-hot):\n', y_train_onehot[:3])
|
||||
|
||||
|
||||
# In[27]:
|
||||
|
||||
|
||||
model = keras.models.Sequential()
|
||||
@@ -545,7 +513,6 @@ model.compile(optimizer=sgd_optimizer,
|
||||
loss='categorical_crossentropy')
|
||||
|
||||
|
||||
# In[28]:
|
||||
|
||||
|
||||
history = model.fit(X_train_centered, y_train_onehot,
|
||||
@@ -554,14 +521,12 @@ history = model.fit(X_train_centered, y_train_onehot,
|
||||
validation_split=0.1)
|
||||
|
||||
|
||||
# In[29]:
|
||||
|
||||
|
||||
y_train_pred = model.predict_classes(X_train_centered, verbose=0)
|
||||
print('First 3 predictions: ', y_train_pred[:3])
|
||||
|
||||
|
||||
# In[30]:
|
||||
|
||||
|
||||
y_train_pred = model.predict_classes(X_train_centered,
|
||||
@@ -573,7 +538,6 @@ print('First 3 predictions: ', y_train_pred[:3])
|
||||
print('Training accuracy: %.2f%%' % (train_acc * 100))
|
||||
|
||||
|
||||
# In[31]:
|
||||
|
||||
|
||||
y_test_pred = model.predict_classes(X_test_centered,
|
||||
@@ -588,10 +552,8 @@ print('Test accuracy: %.2f%%' % (test_acc * 100))
|
||||
|
||||
# ### Logistic function recap
|
||||
|
||||
# In[5]:
|
||||
|
||||
|
||||
import numpy as np
|
||||
|
||||
X = np.array([1, 1.4, 2.5]) ## first value must be 1
|
||||
w = np.array([0.4, 0.3, 0.5])
|
||||
@@ -609,7 +571,6 @@ def logistic_activation(X, w):
|
||||
print('P(y=1|x) = %.3f' % logistic_activation(X, w))
|
||||
|
||||
|
||||
# In[33]:
|
||||
|
||||
|
||||
# W : array with shape = (n_output_units, n_hidden_units+1)
|
||||
@@ -632,7 +593,6 @@ print('Net Input: \n', Z)
|
||||
print('Output Units:\n', y_probas)
|
||||
|
||||
|
||||
# In[34]:
|
||||
|
||||
|
||||
y_class = np.argmax(Z, axis=0)
|
||||
@@ -641,7 +601,6 @@ print('Predicted class label: %d' % y_class)
|
||||
|
||||
# ### Estimating class probabilities in multi-class classification via the softmax function
|
||||
|
||||
# In[35]:
|
||||
|
||||
|
||||
def softmax(z):
|
||||
@@ -651,7 +610,6 @@ y_probas = softmax(Z)
|
||||
print('Probabilities:\n', y_probas)
|
||||
|
||||
|
||||
# In[36]:
|
||||
|
||||
|
||||
np.sum(y_probas)
|
||||
@@ -659,10 +617,8 @@ np.sum(y_probas)
|
||||
|
||||
# ### Broadening the output spectrum by using a hyperbolic tangent
|
||||
|
||||
# In[7]:
|
||||
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
def tanh(z):
|
||||
e_p = np.exp(z)
|
||||
@@ -697,7 +653,6 @@ plt.show()
|
||||
|
||||
# ### Rectified Linear Unit activation
|
||||
|
||||
# In[38]:
|
||||
|
||||
|
||||
|
||||
@@ -710,12 +665,10 @@ plt.show()
|
||||
#
|
||||
# Readers may ignore the next cell.
|
||||
|
||||
# In[ ]:
|
||||
|
||||
|
||||
|
||||
|
||||
# In[ ]:
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
Python Machine Learning - Code Examples
|
||||
|
||||
|
||||
## Chapter 14: Going Deeper - The Mechanics of TensorFlow
|
||||
|
||||
### Chapter Outline
|
||||
|
||||
- Key features of TensorFlow
|
||||
- TensorFlow ranks and tensors
|
||||
- How to get the rank and shape of a tensor
|
||||
- Understanding TensorFlow's computation graphs
|
||||
- Placeholders in TensorFlow
|
||||
- Defining placeholders
|
||||
- Feeding placeholders with data
|
||||
- Defining placeholders for data arrays with varying batchsizes
|
||||
- Variables in TensorFlow
|
||||
- Defining variables
|
||||
- Initializing variables
|
||||
- Variable scope
|
||||
- Reusing variables
|
||||
- Building a regression model
|
||||
- Executing objects in a TensorFlow graph using their names
|
||||
- Saving and restoring a model in TensorFlow
|
||||
- Transforming Tensors as multidimensional data arrays
|
||||
- Utilizing controlflow mechanics in building graphs
|
||||
- Visualizing the graph with TensorBoard
|
||||
- Extending your TensorBoard experience
|
||||
- Summary
|
||||
|
||||
### A note on using the code examples
|
||||
|
||||
The recommended way to interact with the code examples in this book is via Jupyter Notebook (the `.ipynb` files). Using Jupyter Notebook, you will be able to execute the code step by step and have all the resulting outputs (including plots and images) all in one convenient document.
|
||||
|
||||

|
||||
|
||||
|
||||
|
||||
Setting up Jupyter Notebook is really easy: if you are using the Anaconda Python distribution, all you need to install jupyter notebook is to execute the following command in your terminal:
|
||||
|
||||
conda install jupyter notebook
|
||||
|
||||
Then you can launch jupyter notebook by executing
|
||||
|
||||
jupyter notebook
|
||||
|
||||
A window will open up in your browser, which you can then use to navigate to the target directory that contains the `.ipynb` file you wish to open.
|
||||
|
||||
**More installation and setup instructions can be found in the [README.md file of Chapter 1](../ch01/README.md)**.
|
||||
|
||||
**(Even if you decide not to install Jupyter Notebook, note that you can also view the notebook files on GitHub by simply clicking on them: [`ch14.ipynb`](ch14.ipynb))**
|
||||
|
||||
In addition to the code examples, I added a table of contents to each Jupyter notebook as well as section headers that are consistent with the content of the book. Also, I included the original images and figures in hope that these make it easier to navigate and work with the code interactively as you are reading the book.
|
||||
|
||||

|
||||
|
||||
|
||||
When I was creating these notebooks, I was hoping to make your reading (and coding) experience as convenient as possible! However, if you don't wish to use Jupyter Notebooks, I also converted these notebooks to regular Python script files (`.py` files) that can be viewed and edited in any plaintext editor.
|
||||
@@ -35,7 +35,7 @@
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Sebastian Raschka & Vahid Mirjalili \n",
|
||||
"last updated: 2017-08-29 \n",
|
||||
"last updated: 2017-09-17 \n",
|
||||
"\n",
|
||||
"CPython 3.6.1\n",
|
||||
"IPython 6.1.0\n",
|
||||
@@ -864,7 +864,7 @@
|
||||
"data": {
|
||||
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAYAAAAD8CAYAAAB+UHOxAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzt3X+QXWWZJ/DvN52L3EaWDkVUcqEN5bKhwEAydCFrrFpB\nJeGHkAFdYdUZR6sy7OqWUG7cpLAUHbZIbWrG2RktmYxS7pQsRifQZiQawiRbjGjUbpIQIomDgMCF\nlSg2iGlMd/LsH/fe5vTpc849P957z7nnfj9VqXTfe/qe93Zy3+f98bzvSzODiIj0n3l5F0BERPKh\nACAi0qcUAERE+pQCgIhIn1IAEBHpUwoAIiJ9SgFARKRPKQCIiPQpBQARkT41P+8CRDnttNNs8eLF\neRdDRKRnjI+P/9rMFsa5ttABYPHixRgbG8u7GCIiPYPkL+NeqyEgEZE+pQAgItKnFABERPqUAoCI\nSJ9SABAR6VOFzgISEemk0T11bNx+CM9NTGLRUBVrVy7B6uW1vIvVNQoAItKXRvfUsf6e/ZicOgYA\nqE9MYv09+wGgb4KAhoBEpC9t3H5opvJvmZw6ho3bD+VUou6LHQBI3knyBZKPeh7bSPIgyUdI3kty\nKORnnyK5n+ReklrZJSK5e25iMtHjZZSkB/B1AKt8j+0A8FYzOx/AzwGsj/j5S8xsmZmNJCuiiIh7\ni4aq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||
"<matplotlib.figure.Figure at 0x10ea33908>"
|
||||
"<matplotlib.figure.Figure at 0x10d6f7f28>"
|
||||
]
|
||||
},
|
||||
"metadata": {},
|
||||
@@ -923,11 +923,21 @@
|
||||
"Epoch 450: 4.5742\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"data": {
|
||||
"text/plain": [
|
||||
"[<matplotlib.lines.Line2D at 0x12176ea20>]"
|
||||
]
|
||||
},
|
||||
"execution_count": 24,
|
||||
"metadata": {},
|
||||
"output_type": "execute_result"
|
||||
},
|
||||
{
|
||||
"data": {
|
||||
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAXQAAAD8CAYAAABn919SAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAHmpJREFUeJzt3XmUXHWd9/H3t5be93Sl00ln3/eQNGEJEEYQERAQRfEA\n6hlm4qij6DznURmfeXTUZ47buJzBLSMMjCDqAAEFQXaC7B0SSEL2hJDuLN2dTu/p/ff8UZXQ6Wyd\nruq+Vbc+r3Pq1L2/uqn7/fWBT//6dzdzziEiIqkv4HUBIiKSGAp0ERGfUKCLiPiEAl1ExCcU6CIi\nPqFAFxHxCQW6iIhPKNBFRHxCgS4i4hOhkdxZaWmpmzRp0kjuUkQk5a1Zs6beORc53XYjGuiTJk2i\nqqpqJHcpIpLyzGz3YLbTlIuIiE8o0EVEfEKBLiLiEwp0ERGfUKCLiPiEAl1ExCcU6CIiPpESgf7s\nllp+/tx2r8sQEUlqKRHoL+84yE+e2kZnT6/XpYiIJK2UCPTFE4ro6ulj495mr0sREUlapw10M7vT\nzGrNbEO/th+Y2WYze8vMVplZ0XAWuXhCMQBv7D40nLsREUlpgxmh3wVcPqDtSWCec24BsBW4LcF1\nHWN0QRbjS7J5410FuojIyZw20J1zq4GGAW1POOd6YquvABXDUNsxFk8oZs3uQzjnhntXIiIpKRFz\n6H8LPJaA7zmlJROLOdDcSU3j4eHelYhISoor0M3s60APcO8ptllhZlVmVlVXVzfkf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kMOdDMbB3wRqHTOzQOCwA2JKizZZIWDfOF906nafYjnttZ5XY6IyHHi\nnXIJAdlmFgJygL3xl5S8PlY5noribP79iS0apYtI0hlyoDvnaoAfAu8C+4Am59wTiSosGWWEAtx6\nyXQ21DTzl40HvC5HROQY8Uy5FAPXAJOBsUCumd10gu1WmFmVmVXV1aX+VMWHzxrHlEguP3pyi64e\nFZGkEs+Uy6XALudcnXOuG3gQOH/gRs65lc65SudcZSQSiWN3ySEUDPDlS2ew9UArf3rT1zNMIpJi\n4gn0d4FzzSzHzAy4BNiUmLKS25Xzy5k7toAf/GULHd26E6OIJId45tBfBe4H3gDWx75rZYLqSmqB\ngPH1K2ZT03iYu156x+tyRESAOM9ycc59wzk3yzk3zzl3s3OuM1GFJbvzp5Xyvlmj+dkz2/VUIxFJ\nCrpSNA7/fMUs2rt7+elTW70uRUREgR6PaaPzueHs8dz76rvsqGv1uhwRSXMK9Dh9+f0zyAoH+c4j\nb+tiIxHxlAI9TqV5mdx6yXSe3VLHU7q9roh4SIGeAJ9eNonpo/P41z9t1GmMIuIZBXoChIMBvnXN\nPKoPHebnz+3wuhwRSVMK9AQ5b+oorl44ll8+v4PdB9u8LkdE0pACPYG+fuVswgHj/zy0QQdIRWTE\nKdATqKwgi69cPosXttXzwBs1XpcjImlGgZ5gN587kcqJxXz7kbepbenwuhwRSSMK9AQLBIzvfXQB\nh7t7+cbDG70uR0TSiAJ9GEyN5HHrJdN5bMN+Hlu/z+tyRCRNKNCHyYqLpjB3bAH/8vBGGtt18y4R\nGX4K9GESDgb43kcW0NjexT+vWq+zXkRk2CnQh9G8cYX802Uz+PP6/dy/ptrrckTE5xTow+wzF03l\nnMklfPOPG3XBkYgMKwX6MAsGjB9/fBHBgHHr79bR3dvndUki4lNDDnQzm2lm6/q9mLine truncated
|
||||
"text/plain": [
|
||||
"<matplotlib.figure.Figure at 0x10eca35c0>"
|
||||
"<matplotlib.figure.Figure at 0x1216b9400>"
|
||||
]
|
||||
},
|
||||
"metadata": {},
|
||||
@@ -958,7 +968,7 @@
|
||||
" \n",
|
||||
"\n",
|
||||
"plt.plot(training_costs)\n",
|
||||
"plt.savefig('images/14_04.png', dpi=300)"
|
||||
"# plt.savefig('images/14_04.png', dpi=300)"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -977,7 +987,7 @@
|
||||
"data": {
|
||||
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAXYAAAD8CAYAAABjAo9vAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAGtBJREFUeJzt3X+QXWV5B/DvN5sbuYmUjcNayoY1sVUYMELKqtidthKs\nxPIrRS3Y4lRtJx2nWnVo7Eb+ADvtsG2s6IxOnYzaToeMiIArFW2AblqnTEF33SCGJB2qBLjgsA4u\nClnI7ubpH3sXdu+ec+8997znnPc99/uZYYa9e+9737ubfe57n/d5n0Mzg4iIlMeqoicgIiJuKbCL\niJSMAruISMkosIuIlIwCu4hIySiwi4iUjAK7iEjJKLCLiJSMAruISMmsLuJJTz31VNu4cWMRTy0i\nEqyJiYmfmVlfq/sVEtg3btyI8fHxIp5aRCRYJI+2cz+lYkRESkaBXUSkZBTYRURKRoFdRKRkFNhF\nREqmkKoYEZFQjU7WsHvfETw5PYPTe6vYefGZ2L6lv+hpLeNkxU7y4yQPkvwRya+SPMnFuCIiPhmd\nrGHXHQ+hNj0DA1CbnsGuOx7C6GSt6Kktkzqwk+wH8JcABs3sDQB6AFyddlwREd/s3ncEM7Pzy26b\nmZ3H7n1HCppRNFc59tUAqiRXA1gL4ElH44qIeOPJ6ZlEtxcldWA3sxqATwN4DMBTAJ41s7sb70dy\nB8lxkuNTU1Npn1ZEJHen91YT3V4UF6mY9QCuALAJwOkA1pG8pvF+ZrbHzAbNbLCvr2WrAxER7+y8\n+ExUKz3LbqtWerDz4jMLmlE0F6mYtwP4iZlNmdksgDsA/JaDcUVEvLJ9Sz9uvHIz+nurIID+3ipu\nvHKzd1UxLsodHwNwAcm1AGY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l2CtT7mmp7r1y5fRbsqNWxW4RCXvw+xEsbl\nJ424n/36tRWsXbO69FUxRVFgl2Bdf9k52Hnbg5idfznPXukhrr/snGX3y7rUMC7gJ61jjtrgTfJ4\nV1zW3Mf97K+/LFl/eUmGFnMiLkuDg4M2Pj6e+/NK+bRb7eJ73XRjCSAAVFYRIJa9cVUrPZlfPShq\nLmme1/effUhITpjZYMv7KbCLFG9oZCxylRylv7e64iIdrikY+6ndwK5UjJRaKAEqSf46j6oaNSML\nmwK7FCbroBvSCce4vHbcfYFw3rQkf07KHUluI3mE5CMkh12MKeXmslY6TkgHhKLq5CuriErP8ssJ\nL2765vHzk3ClDuwkewB8AcA7AZwN4L0kz047rpRb1kF3dLIWuwL28YBQVJ387veci93vPjfyyk0h\nvWlJ/lykYt4M4BEz+zEAkLwFwBUAHnYwtpRUlqcyF1ezcU6JOS1atFZlk0uFeqpV8uEisPcDeHzJ\n108AeEvjnUjuALADAAYGBhw8rYQgLg/caa1043gXntWH/Yenlo3f6hj788fnMDpZCzofnXV/92b5\ne+X2/Ze63JHkuwFsM7M/q3/9PgBvMbMPxz1G5Y5hSvoH3aweGog+ldmsVjpqvEbVSk9bvUnyKBnM\nkuta83bHBpL/3sSdPMsdawDOWPL1hvptUiKdVJg0ywMvBtUkbxTtNJSamZ1HD7ni+qKNOk1Z+LJa\nzfLqPK3y92q56z8Xgf37AF5HchMWAvrVAP7IwbjikWZ/7HF/0K3ywElrpdsNxvNmLVfunaQsfCuf\nzKrWvJP8vXL7fkldFWNmcwA+DGAfgEMAbjWzg80fJaGJqzBpVnvturthu49brB7prLine truncated
|
||||
"text/plain": [
|
||||
"<matplotlib.figure.Figure at 0x10f03ea90>"
|
||||
"<matplotlib.figure.Figure at 0x121817358>"
|
||||
]
|
||||
},
|
||||
"metadata": {},
|
||||
@@ -1148,7 +1158,7 @@
|
||||
"data": {
|
||||
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAYAAAAD8CAYAAAB+UHOxAAAABHNCSVQIC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eROcaWKV7RQptFBOWPLFgiH7b+hQ+GrX837EFQBKEoRkO8uWMlCHv18BI89BmPH\n2u1+/eDtt6G6OrrP2V+MDtd8r7JiMMZqS0fgL10Kb7wRPf7+96sCUJRKJddZrl4kyhD28wVs29bT\nvDJqFAwZEj2nWB2ueV1ldXXBCy9YQR8Ow7JliW+0caP9ckfkNz9Wi8EpShGQTpZrpqQT9++Xg9nU\nZMd06aXWJHTTTdYElKnD1RmTCPTubV9zlZOQ0+iggwetoP/mN+GCC2DwYJgwAW65BX7zG2/hf8wx\n8MEPwn/9l607PXhwAANJD10BKEqRkMsuWOnG/SfzEbjHnGn7xvgxdXWlNrZMCXSV1dEBzz4bneE/\n91zPUqLxDBwIU6dCKGT/TZxoa00UELEBOsXJpEmTzKpVPYqLKoqSJmPGeEf9NDfbjFcvvKKAghTI\nfmNKZWyZknEU0PbtUft9OAzPP2+XPIkYORKmTYsK/JNPtsuvHCMiq40xk1I6VxWAopQ/VVXWDxmP\nSHI5liv8xuRQsLEZYx20jrM2HLYO3GSccEJU2E+bFrVt5Zl0FICagBSlAkgl7j/f+Line truncated
|
||||
"text/plain": [
|
||||
"<matplotlib.figure.Figure at 0x119c09f28>"
|
||||
"<matplotlib.figure.Figure at 0x1224586a0>"
|
||||
]
|
||||
},
|
||||
"metadata": {},
|
||||
@@ -1171,7 +1181,7 @@
|
||||
"plt.plot(x_train, y_train, 'bo')\n",
|
||||
"plt.plot(x_test, y_test, 'bo', alpha=0.3)\n",
|
||||
"plt.plot(x_arr, y_arr.T[:, 0], '-r', lw=3)\n",
|
||||
"plt.savefig('images/14_05.png', dpi=400)\n",
|
||||
"# plt.savefig('images/14_05.png', dpi=400)\n",
|
||||
"plt.show()"
|
||||
]
|
||||
},
|
||||
@@ -1318,19 +1328,19 @@
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Tensor(\"t1:0\", shape=(10, 1), dtype=float32)\n",
|
||||
"Tensor(\"t1_1:0\", shape=(10, 1), dtype=float32)\n",
|
||||
"Tensor(\"t3:0\", shape=(20, 1), dtype=float32)\n",
|
||||
"Tensor(\"t4:0\", shape=(10, 2), dtype=float32)\n"
|
||||
"Tensor(\"t1:0\", shape=(5, 1), dtype=float32)\n",
|
||||
"Tensor(\"t2:0\", shape=(5, 1), dtype=float32)\n",
|
||||
"Tensor(\"t3:0\", shape=(10, 1), dtype=float32)\n",
|
||||
"Tensor(\"t4:0\", shape=(5, 2), dtype=float32)\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"g = tf.Graph()\n",
|
||||
"with g.as_default():\n",
|
||||
" t1 = tf.ones(shape=(10, 1), \n",
|
||||
" t1 = tf.ones(shape=(5, 1), \n",
|
||||
" dtype=tf.float32, name='t1')\n",
|
||||
" t2 = tf.zeros(shape=(10, 1),\n",
|
||||
" t2 = tf.zeros(shape=(5, 1),\n",
|
||||
" dtype=tf.float32, name='t2')\n",
|
||||
" print(t1)\n",
|
||||
" print(t2)\n",
|
||||
@@ -1356,16 +1366,6 @@
|
||||
" [ 1.]\n",
|
||||
" [ 1.]\n",
|
||||
" [ 1.]\n",
|
||||
" [ 1.]\n",
|
||||
" [ 1.]\n",
|
||||
" [ 1.]\n",
|
||||
" [ 1.]\n",
|
||||
" [ 1.]\n",
|
||||
" [ 0.]\n",
|
||||
" [ 0.]\n",
|
||||
" [ 0.]\n",
|
||||
" [ 0.]\n",
|
||||
" [ 0.]\n",
|
||||
" [ 0.]\n",
|
||||
" [ 0.]\n",
|
||||
" [ 0.]\n",
|
||||
@@ -1376,11 +1376,6 @@
|
||||
" [ 1. 0.]\n",
|
||||
" [ 1. 0.]\n",
|
||||
" [ 1. 0.]\n",
|
||||
" [ 1. 0.]\n",
|
||||
" [ 1. 0.]\n",
|
||||
" [ 1. 0.]\n",
|
||||
" [ 1. 0.]\n",
|
||||
" [ 1. 0.]\n",
|
||||
" [ 1. 0.]]\n"
|
||||
]
|
||||
}
|
||||
@@ -1733,7 +1728,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 1,
|
||||
"execution_count": 44,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
@@ -1741,13 +1736,22 @@
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"[NbConvertApp] Converting notebook ch14.ipynb to script\n",
|
||||
"[NbConvertApp] Writing 22882 bytes to ch14.py\n"
|
||||
"[NbConvertApp] Writing 22885 bytes to ch14.py\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"! python ../.convert_notebook_to_script.py --input ch14.ipynb --output ch14.py"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"collapsed": true
|
||||
},
|
||||
"outputs": [],
|
||||
"source": []
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
|
||||
# coding: utf-8
|
||||
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
import tensorflow as tf
|
||||
import numpy as np
|
||||
|
||||
# *Python Machine Learning 2nd Edition* by [Sebastian Raschka](https://sebastianraschka.com) and Vahid Mirjalili, Packt Publishing Ltd. 2017
|
||||
#
|
||||
# Code Repository: https://github.com/rasbt/python-machine-learning-book-2nd-edition
|
||||
@@ -11,7 +15,6 @@
|
||||
|
||||
# Note that the optional watermark extension is a small IPython notebook plugin that I developed to make the code reproducible. You can just skip the following line(s).
|
||||
|
||||
# In[1]:
|
||||
|
||||
|
||||
|
||||
@@ -40,30 +43,22 @@
|
||||
# - [Visualizing the graph with TensorBoard](#Visualizing-the-graph-with-TensorBoard)
|
||||
# - [Summary](#Summary)
|
||||
|
||||
# In[2]:
|
||||
|
||||
|
||||
from IPython.display import Image
|
||||
|
||||
|
||||
# In[3]:
|
||||
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
import tensorflow as tf
|
||||
import numpy as np
|
||||
|
||||
|
||||
# ## TensorFlow in a nutshell
|
||||
|
||||
# In[4]:
|
||||
|
||||
|
||||
|
||||
|
||||
# **How to get the rank and shape of a tensor**
|
||||
|
||||
# In[5]:
|
||||
|
||||
|
||||
g = tf.Graph()
|
||||
@@ -95,13 +90,11 @@ with tf.Session(graph=g) as sess:
|
||||
|
||||
# ## Understanding TensorFlow's computation graph
|
||||
|
||||
# In[6]:
|
||||
|
||||
|
||||
Image("images/14_02.png")
|
||||
|
||||
|
||||
# In[7]:
|
||||
|
||||
|
||||
g = tf.Graph()
|
||||
@@ -112,11 +105,11 @@ with g.as_default():
|
||||
b = tf.constant(2, name='b')
|
||||
c = tf.constant(3, name='c')
|
||||
|
||||
t = 2*(a-b) + c
|
||||
z = 2*(a-b) + c
|
||||
|
||||
## launch the graph
|
||||
with tf.Session(graph=g) as sess:
|
||||
print('2*(a-b)+c => ', sess.run(t))
|
||||
print('2*(a-b)+c => ', sess.run(z))
|
||||
|
||||
|
||||
# ## Working with TensorFlow’s placeholders, variables, and operations
|
||||
@@ -125,7 +118,6 @@ with tf.Session(graph=g) as sess:
|
||||
|
||||
# #### Defining placeholders
|
||||
|
||||
# In[8]:
|
||||
|
||||
|
||||
g = tf.Graph()
|
||||
@@ -144,7 +136,6 @@ with g.as_default():
|
||||
|
||||
# #### Feeding placeholders with data
|
||||
|
||||
# In[9]:
|
||||
|
||||
|
||||
## launch the previous graph
|
||||
@@ -158,7 +149,6 @@ with tf.Session(graph=g) as sess:
|
||||
|
||||
# Execution with and without feeding tf_c:
|
||||
|
||||
# In[10]:
|
||||
|
||||
|
||||
## launch the previous graph
|
||||
@@ -185,7 +175,6 @@ with tf.Session(graph=g) as sess:
|
||||
|
||||
# Placeholder for varying batchsizes:
|
||||
|
||||
# In[11]:
|
||||
|
||||
|
||||
g = tf.Graph()
|
||||
@@ -216,7 +205,6 @@ with tf.Session(graph=g) as sess:
|
||||
feed_dict={tf_x:x2}))
|
||||
|
||||
|
||||
# In[12]:
|
||||
|
||||
|
||||
print(tf_x)
|
||||
@@ -227,7 +215,6 @@ print(tf_x)
|
||||
|
||||
# #### Defining Variables
|
||||
|
||||
# In[13]:
|
||||
|
||||
|
||||
g1 = tf.Graph()
|
||||
@@ -240,7 +227,6 @@ with g1.as_default():
|
||||
|
||||
# #### Initializing variables
|
||||
|
||||
# In[14]:
|
||||
|
||||
|
||||
## initialize w and evaluate it
|
||||
@@ -249,7 +235,6 @@ with tf.Session(graph=g1) as sess:
|
||||
print(sess.run(w))
|
||||
|
||||
|
||||
# In[15]:
|
||||
|
||||
|
||||
## add the init_op to the graph
|
||||
@@ -262,7 +247,6 @@ with tf.Session(graph=g1) as sess:
|
||||
print(sess.run(w))
|
||||
|
||||
|
||||
# In[16]:
|
||||
|
||||
|
||||
g2 = tf.Graph()
|
||||
@@ -273,7 +257,6 @@ with g2.as_default():
|
||||
w2 = tf.Variable(2, name='w2')
|
||||
|
||||
|
||||
# In[17]:
|
||||
|
||||
|
||||
with tf.Session(graph=g2) as sess:
|
||||
@@ -283,7 +266,6 @@ with tf.Session(graph=g2) as sess:
|
||||
|
||||
# Error if a variable is not initialized:
|
||||
|
||||
# In[18]:
|
||||
|
||||
|
||||
with tf.Session(graph=g2) as sess:
|
||||
@@ -297,7 +279,6 @@ with tf.Session(graph=g2) as sess:
|
||||
|
||||
# #### Variable scope
|
||||
|
||||
# In[19]:
|
||||
|
||||
|
||||
g = tf.Graph()
|
||||
@@ -322,7 +303,6 @@ with g.as_default():
|
||||
|
||||
# #### Reusing variables
|
||||
|
||||
# In[20]:
|
||||
|
||||
|
||||
######################
|
||||
@@ -398,7 +378,6 @@ with g.as_default():
|
||||
init_op = tf.global_variables_initializer()
|
||||
|
||||
|
||||
# In[21]:
|
||||
|
||||
|
||||
## alternative way
|
||||
@@ -432,7 +411,6 @@ with g.as_default():
|
||||
|
||||
# ### Building a regression model
|
||||
|
||||
# In[22]:
|
||||
|
||||
|
||||
## define a graph
|
||||
@@ -473,7 +451,6 @@ with g.as_default():
|
||||
train_op = optim.minimize(cost, name='train_op')
|
||||
|
||||
|
||||
# In[23]:
|
||||
|
||||
|
||||
## create a random toy dataset for regression
|
||||
@@ -495,13 +472,12 @@ def make_random_data():
|
||||
x, y = make_random_data()
|
||||
|
||||
plt.plot(x, y, 'o')
|
||||
plt.savefig('images/14_03.png', dpi=300)
|
||||
# plt.savefig('images/14_03.png', dpi=300)
|
||||
plt.show()
|
||||
|
||||
|
||||
# ### Executing objects in a TensorFlow graph using their names
|
||||
|
||||
# In[24]:
|
||||
|
||||
|
||||
## train/test splits:
|
||||
@@ -527,12 +503,11 @@ with tf.Session(graph=g) as sess:
|
||||
|
||||
|
||||
plt.plot(training_costs)
|
||||
plt.savefig('images/14_04.png', dpi=300)
|
||||
# plt.savefig('images/14_04.png', dpi=300)
|
||||
|
||||
|
||||
# Executing with variable names:
|
||||
|
||||
# In[25]:
|
||||
|
||||
|
||||
## train/test splits
|
||||
@@ -562,7 +537,6 @@ with tf.Session(graph=g) as sess:
|
||||
|
||||
# ## Saving and restoring a model in TensorFlow
|
||||
|
||||
# In[26]:
|
||||
|
||||
|
||||
## add saver to the graph
|
||||
@@ -591,7 +565,6 @@ with tf.Session(graph=g) as sess:
|
||||
|
||||
# Restoring the saved model:
|
||||
|
||||
# In[27]:
|
||||
|
||||
|
||||
## new file: loading a trained model
|
||||
@@ -608,13 +581,11 @@ with tf.Session(graph=g2) as sess:
|
||||
feed_dict={'tf_x:0' : x_test})
|
||||
|
||||
|
||||
# In[28]:
|
||||
|
||||
|
||||
print('SSE: %.4f' % (np.sum(np.square(y_pred - y_test))))
|
||||
|
||||
|
||||
# In[29]:
|
||||
|
||||
|
||||
x_arr = np.arange(-2, 4, 0.1)
|
||||
@@ -632,13 +603,12 @@ plt.figure()
|
||||
plt.plot(x_train, y_train, 'bo')
|
||||
plt.plot(x_test, y_test, 'bo', alpha=0.3)
|
||||
plt.plot(x_arr, y_arr.T[:, 0], '-r', lw=3)
|
||||
plt.savefig('images/14_05.png', dpi=400)
|
||||
# plt.savefig('images/14_05.png', dpi=400)
|
||||
plt.show()
|
||||
|
||||
|
||||
# ## Transforming Tensors as multidimensional data arrays
|
||||
|
||||
# In[30]:
|
||||
|
||||
|
||||
g = tf.Graph()
|
||||
@@ -658,7 +628,6 @@ with g.as_default():
|
||||
print(T3)
|
||||
|
||||
|
||||
# In[31]:
|
||||
|
||||
|
||||
with g.as_default():
|
||||
@@ -670,7 +639,6 @@ with g.as_default():
|
||||
print(T5)
|
||||
|
||||
|
||||
# In[32]:
|
||||
|
||||
|
||||
with tf.Session(graph = g) as sess:
|
||||
@@ -679,7 +647,6 @@ with tf.Session(graph = g) as sess:
|
||||
print(sess.run(T5))
|
||||
|
||||
|
||||
# In[33]:
|
||||
|
||||
|
||||
with g.as_default():
|
||||
@@ -691,7 +658,6 @@ with g.as_default():
|
||||
print(T7)
|
||||
|
||||
|
||||
# In[34]:
|
||||
|
||||
|
||||
with g.as_default():
|
||||
@@ -701,15 +667,14 @@ with g.as_default():
|
||||
print(t5_splt)
|
||||
|
||||
|
||||
# In[35]:
|
||||
|
||||
|
||||
g = tf.Graph()
|
||||
with g.as_default():
|
||||
t1 = tf.ones(shape=(10, 1),
|
||||
dtype=tf.float32, name='t1')
|
||||
t2 = tf.zeros(shape=(10, 1),
|
||||
t1 = tf.ones(shape=(5, 1),
|
||||
dtype=tf.float32, name='t1')
|
||||
t2 = tf.zeros(shape=(5, 1),
|
||||
dtype=tf.float32, name='t2')
|
||||
print(t1)
|
||||
print(t2)
|
||||
|
||||
@@ -720,7 +685,6 @@ with g.as_default():
|
||||
print(t4)
|
||||
|
||||
|
||||
# In[36]:
|
||||
|
||||
|
||||
with tf.Session(graph = g) as sess:
|
||||
@@ -731,7 +695,6 @@ with tf.Session(graph = g) as sess:
|
||||
|
||||
# ## Utilizing control flow mechanics in building graphs
|
||||
|
||||
# In[37]:
|
||||
|
||||
|
||||
## Python control flow
|
||||
@@ -765,7 +728,6 @@ with tf.Session(graph=g) as sess:
|
||||
file_writer = tf.summary.FileWriter(logdir='./logs/py-cflow/', graph=g)
|
||||
|
||||
|
||||
# In[38]:
|
||||
|
||||
|
||||
## TensorFlow control flow
|
||||
@@ -798,17 +760,14 @@ with tf.Session(graph=g) as sess:
|
||||
#file_writer = tf.summary.FileWriter(logdir='./logs/tf-cond/', graph=g)
|
||||
|
||||
|
||||
# In[39]:
|
||||
|
||||
|
||||
|
||||
|
||||
# ## Visualizing the graph with TensorBoard
|
||||
|
||||
# In[40]:
|
||||
|
||||
|
||||
import tensorflow as tf
|
||||
|
||||
|
||||
###########################
|
||||
@@ -894,17 +853,14 @@ with tf.Session(graph = g) as sess:
|
||||
|
||||
|
||||
|
||||
# In[41]:
|
||||
|
||||
|
||||
|
||||
|
||||
# In[42]:
|
||||
|
||||
|
||||
|
||||
|
||||
# In[43]:
|
||||
|
||||
|
||||
|
||||
@@ -917,12 +873,10 @@ with tf.Session(graph = g) as sess:
|
||||
#
|
||||
# Readers may ignore the next cell.
|
||||
|
||||
# In[ ]:
|
||||
|
||||
|
||||
|
||||
|
||||
# In[ ]:
|
||||
|
||||
|
||||
|
||||
|
||||
|
Before Width: | Height: | Size: 55 KiB After Width: | Height: | Size: 49 KiB |
|
Before Width: | Height: | Size: 199 KiB After Width: | Height: | Size: 177 KiB |
@@ -0,0 +1,52 @@
|
||||
Python Machine Learning - Code Examples
|
||||
|
||||
|
||||
## Chapter 15 - Classifying Images with Deep Convolutional Neural Networks
|
||||
|
||||
### Chapter Outline
|
||||
|
||||
- Building blocks of convolutional neural networks
|
||||
- Understanding CNNs and learning feature hierarchies
|
||||
- Performing discrete convolutions
|
||||
- Performing a discrete convolution in one dimension
|
||||
- The effect of zero-padding in a convolution
|
||||
- Determining the size of the convolution output
|
||||
- Performing a discrete convolution in 2D
|
||||
- Subsampling
|
||||
- Putting everything together to build a CNN 508
|
||||
- Working with multiple input or color channels 508
|
||||
- Regularizing a neural network with dropout 512
|
||||
- Implementing a deep convolutional neural network using TensorFlow
|
||||
- The multilayer CNN architecture 514 Loading and preprocessing the data
|
||||
- Implementing a CNN in the TensorFlow low-level API
|
||||
- Implementing a CNN in the TensorFlow layers API
|
||||
- Summary
|
||||
|
||||
### A note on using the code examples
|
||||
|
||||
The recommended way to interact with the code examples in this book is via Jupyter Notebook (the `.ipynb` files). Using Jupyter Notebook, you will be able to execute the code step by step and have all the resulting outputs (including plots and images) all in one convenient document.
|
||||
|
||||

|
||||
|
||||
|
||||
|
||||
Setting up Jupyter Notebook is really easy: if you are using the Anaconda Python distribution, all you need to install jupyter notebook is to execute the following command in your terminal:
|
||||
|
||||
conda install jupyter notebook
|
||||
|
||||
Then you can launch jupyter notebook by executing
|
||||
|
||||
jupyter notebook
|
||||
|
||||
A window will open up in your browser, which you can then use to navigate to the target directory that contains the `.ipynb` file you wish to open.
|
||||
|
||||
**More installation and setup instructions can be found in the [README.md file of Chapter 1](../ch01/README.md)**.
|
||||
|
||||
**(Even if you decide not to install Jupyter Notebook, note that you can also view the notebook files on GitHub by simply clicking on them: [`ch15.ipynb`](ch15.ipynb))**
|
||||
|
||||
In addition to the code examples, I added a table of contents to each Jupyter notebook as well as section headers that are consistent with the content of the book. Also, I included the original images and figures in hope that these make it easier to navigate and work with the code interactively as you are reading the book.
|
||||
|
||||

|
||||
|
||||
|
||||
When I was creating these notebooks, I was hoping to make your reading (and coding) experience as convenient as possible! However, if you don't wish to use Jupyter Notebooks, I also converted these notebooks to regular Python script files (`.py` files) that can be viewed and edited in any plaintext editor.
|
||||
@@ -1787,15 +1787,14 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 2,
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"[NbConvertApp] Converting notebook ch15.ipynb to script\n",
|
||||
"[NbConvertApp] Writing 28884 bytes to ch15.py\n"
|
||||
"[NbConvertApp] Converting notebook ch15.ipynb to script\r\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
from __future__ import print_function
|
||||
|
||||
|
||||
|
||||
# coding: utf-8
|
||||
|
||||
@@ -19,6 +16,8 @@ from __future__ import print_function
|
||||
# In[1]:
|
||||
|
||||
|
||||
get_ipython().magic('load_ext watermark')
|
||||
get_ipython().magic("watermark -a 'Sebastian Raschka & Vahid Mirjalili' -d -p numpy,scipy,tensorflow")
|
||||
|
||||
|
||||
# *The use of `watermark` is optional. You can install this IPython extension via "`pip install watermark`". For more information, please see*: https://github.com/rasbt/watermark.
|
||||
@@ -43,12 +42,14 @@ from __future__ import print_function
|
||||
|
||||
|
||||
from IPython.display import Image
|
||||
get_ipython().magic('matplotlib inline')
|
||||
|
||||
|
||||
# In[3]:
|
||||
|
||||
|
||||
# This is for Python 2.7 compatibility
|
||||
from __future__ import print_function
|
||||
|
||||
|
||||
# # Building blocks of convolutional neural networks
|
||||
@@ -58,6 +59,7 @@ from IPython.display import Image
|
||||
# In[4]:
|
||||
|
||||
|
||||
Image(filename='images/15_01.png', width=700)
|
||||
|
||||
|
||||
# ## Performing discrete convolutions
|
||||
@@ -67,11 +69,13 @@ from IPython.display import Image
|
||||
# In[5]:
|
||||
|
||||
|
||||
Image(filename='images/15_02.png', width=700)
|
||||
|
||||
|
||||
# In[6]:
|
||||
|
||||
|
||||
Image(filename='images/15_03.png', width=700)
|
||||
|
||||
|
||||
# ### The effect of zero-padding in convolution
|
||||
@@ -79,6 +83,7 @@ from IPython.display import Image
|
||||
# In[7]:
|
||||
|
||||
|
||||
Image(filename='images/15_11.png', width=700)
|
||||
|
||||
|
||||
# ### Determining the size of the convolution output
|
||||
@@ -115,11 +120,13 @@ print('Numpy Results: ',
|
||||
# In[9]:
|
||||
|
||||
|
||||
Image(filename='images/15_04.png', width=700)
|
||||
|
||||
|
||||
# In[10]:
|
||||
|
||||
|
||||
Image(filename='images/15_05.png', width=900)
|
||||
|
||||
|
||||
# In[11]:
|
||||
@@ -163,6 +170,7 @@ print('Scipy Results: \n',
|
||||
# In[12]:
|
||||
|
||||
|
||||
Image(filename='images/15_06.png', width=700)
|
||||
|
||||
|
||||
# # Putting everything together to build a CNN
|
||||
@@ -194,6 +202,7 @@ print(img[100:102, 100:102, :])
|
||||
# In[14]:
|
||||
|
||||
|
||||
Image(filename='images/15_07.png', width=800)
|
||||
|
||||
|
||||
# ## Regularizing a neural network with dropout
|
||||
@@ -201,6 +210,7 @@ print(img[100:102, 100:102, :])
|
||||
# In[15]:
|
||||
|
||||
|
||||
Image(filename='images/15_08.png', width=800)
|
||||
|
||||
|
||||
# # Implementing a deep convolutional neural network using TensorFlow
|
||||
@@ -210,6 +220,7 @@ print(img[100:102, 100:102, :])
|
||||
# In[16]:
|
||||
|
||||
|
||||
Image(filename='images/15_09.png', width=800)
|
||||
|
||||
|
||||
# ## Loading and preprocessing the data
|
||||
@@ -349,7 +360,7 @@ def conv_layer(input_tensor, name,
|
||||
padding=padding_mode)
|
||||
print(conv)
|
||||
conv = tf.nn.bias_add(conv, biases,
|
||||
name='net_pre-activaiton')
|
||||
name='net_pre-activation')
|
||||
print(conv)
|
||||
conv = tf.nn.relu(conv, name='activation')
|
||||
print(conv)
|
||||
@@ -390,7 +401,7 @@ def fc_layer(input_tensor, name,
|
||||
layer = tf.matmul(input_tensor, weights)
|
||||
print(layer)
|
||||
layer = tf.nn.bias_add(layer, biases,
|
||||
name='net_pre-activaiton')
|
||||
name='net_pre-activation')
|
||||
print(layer)
|
||||
if activation_fn is None:
|
||||
return layer
|
||||
@@ -785,6 +796,7 @@ with tf.Session(graph=g) as sess:
|
||||
# In[4]:
|
||||
|
||||
|
||||
Image(filename='images/15_10.png', width=800)
|
||||
|
||||
|
||||
# ## Implementing a CNN in the TensorFlow layers API
|
||||
@@ -1015,13 +1027,8 @@ print('Test Accuracy: %.2f%%' % (100*
|
||||
#
|
||||
# Readers may ignore the next cell.
|
||||
|
||||
# In[ ]:
|
||||
|
||||
|
||||
|
||||
|
||||
# In[ ]:
|
||||
|
||||
# In[1]:
|
||||
|
||||
|
||||
get_ipython().system(' python ../.convert_notebook_to_script.py --input ch15.ipynb --output ch15.py')
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
Python Machine Learning - Code Examples
|
||||
|
||||
|
||||
## Chapter 16 - Modeling Sequential Data Using Recurrent Neural Networks
|
||||
|
||||
### Chapter Outline
|
||||
|
||||
|
||||
- Introducing sequential data
|
||||
- Modeling sequential data: Order matters
|
||||
- Understanding the different categories of sequence modeling
|
||||
- Recurrent neural networks for modeling sequences
|
||||
- Understanding the structure and flow of a recurrent neural network
|
||||
- Computing activations in an RNN
|
||||
- The challenges of learning long-range interactions
|
||||
- Long short-term memory units
|
||||
- Implementing a multilayer RNN for sequence modeling in TensorFlow
|
||||
- Performing sentiment analysis of IMDb movie reviews using multilayer RNNs
|
||||
- Preparing the data
|
||||
- Embedding
|
||||
- Building the RNN model
|
||||
- Step 1: Defining multilayer RNN cells
|
||||
- Step 2: Defining the initial states for the RNN cells
|
||||
- Step 3: Creating the recurrent neural network using the RNN cells and their states
|
||||
- Example application: character-level language modeling
|
||||
- Preparing the data
|
||||
- Building the character-level RNN model
|
||||
- Summary
|
||||
|
||||
### A note on using the code examples
|
||||
|
||||
The recommended way to interact with the code examples in this book is via Jupyter Notebook (the `.ipynb` files). Using Jupyter Notebook, you will be able to execute the code step by step and have all the resulting outputs (including plots and images) all in one convenient document.
|
||||
|
||||

|
||||
|
||||
|
||||
|
||||
Setting up Jupyter Notebook is really easy: if you are using the Anaconda Python distribution, all you need to install jupyter notebook is to execute the following command in your terminal:
|
||||
|
||||
conda install jupyter notebook
|
||||
|
||||
Then you can launch jupyter notebook by executing
|
||||
|
||||
jupyter notebook
|
||||
|
||||
A window will open up in your browser, which you can then use to navigate to the target directory that contains the `.ipynb` file you wish to open.
|
||||
|
||||
**More installation and setup instructions can be found in the [README.md file of Chapter 1](../ch01/README.md)**.
|
||||
|
||||
**(Even if you decide not to install Jupyter Notebook, note that you can also view the notebook files on GitHub by simply clicking on them: [`ch16.ipynb`](ch16.ipynb))**
|
||||
|
||||
In addition to the code examples, I added a table of contents to each Jupyter notebook as well as section headers that are consistent with the content of the book. Also, I included the original images and figures in hope that these make it easier to navigate and work with the code interactively as you are reading the book.
|
||||
|
||||

|
||||
|
||||
|
||||
When I was creating these notebooks, I was hoping to make your reading (and coding) experience as convenient as possible! However, if you don't wish to use Jupyter Notebooks, I also converted these notebooks to regular Python script files (`.py` files) that can be viewed and edited in any plaintext editor.
|
||||
@@ -96,7 +96,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 2,
|
||||
"execution_count": 1,
|
||||
"metadata": {
|
||||
"collapsed": true
|
||||
},
|
||||
@@ -271,17 +271,17 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 3,
|
||||
"execution_count": 2,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"data": {
|
||||
"image/png": "iVBORw0KGgoAAAANSUhEUgAAD2kAAAZoCAYAAAAC9h9jAAABGWlDQ1BJQ0MgUHJvZmlsZQAAKJFj\nYGBSSCwoyGESYGDIzSspCnJ3UoiIjFJgf8jAycDFIMygxSCemFxc4BgQ4MMABDAaFXy7xsAIoi/r\ngszClMcLuFJSi5OB9B8gzk4uKCphYGDMALKVy0sKQOweIFskKRvMXgBiFwEdCGRvAbHTIewTYDUQ\n9h2wmpAgZyD7A5DNlwRmM4Hs4kuHsAVAbKi9ICDomJKflKoA8r2GoaWlhSaJfiAISlIrSkC0c35B\nZVFmekaJgiMwpFIVPPOS9XQUjAwMzRkYQOEOUf05EByejGJnEGIIgBCbI8HA4L+UgYHlD0LMpJeB\nYYEOAwP/VISYmiEDg4A+A8O+OcmlRWVQYxiZjBkYCPEBLvxKYCQKtVEAAAAJcEhZcwAALiMAAC4j\nAXilP3YAAAQoaVRYdFhNTDpjb20uYWRvYmUueG1wAAAAAAA8eDp4bXBtZXRhIHhtbG5zOng9ImFk\nb2JlOm5zOm1ldG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whpp0WMCRAgQIAAAQIECBAgQLine truncated
|
||||
"image/png": "iVBORw0KGgoAAAANSUhEUgAADw4AAAaXCAYAAADVCaumAAABGWlDQ1BJQ0MgUHJvZmlsZQAAKJFj\nYGBSSCwoyGESYGDIzSspCnJ3UoiIjFJgf8jAySDAwMSgyiCYmFxc4BgQ4MMABDAaFXy7xsAIoi/r\ngszClMcLuFJSi5OB9B8gzk4uKCphYGDMALKVy0sKQOweIFskKRvMXgBiFwEdCGRvAbHTIewTYDUQ\n9h2wmpAgZyD7A5DNlwRmM4Hs4kuHsAVAbKi9ICDomJKflKoA8r2GoaWlhSaJfiAISlIrSkC0c35B\nZVFmekaJgiMwpFIVPPOS9XQUjAwMzRkYQOEOUf05EByejGJnEGIIgBCbI8HA4L+UgYHlD0LMpJeB\nYYEOAwP/VISYmiEDg4A+A8O+OcmlRWVQYxiZjBkYCPEBAxRKSpVeZmIAAAAJcEhZcwAALiMAAC4j\nAXilP3YAAEAASURBVHgB7N0LkJV1/T/wzy67chNSbi2IaSQCecHBSymKqIU1jiNYEpqjeRvTxpQx\nRytHSadmGgFvSb9BGksrb6UBTUaZ98URS9EEHAMTMiFAIC+sssD+ec4/HS+w5yx7O+f7vJ6ZM7Dn\n+T7f5/t5fb4q1Hmfp6pp2xEOAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQI\nECBAgAABAgQIECBAgAABAgQIECBAgAABAgQqWqC6oldv8QQIECBAgAABAgQIECBAgAABAgQIECBA\ngAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIFAQEh20EAgQIECBAgAAB\nAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgkI\nCA4n0EQlECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAAB\nAgQIECBAgAABAgQIEBActgcIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBA\ngAABAgQIECBAgAABAgQIECBAgAABAgQIJCAgOJxAE5VAgAABAgQIECBAgAABAgQIECBAgAABAgQI\nECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAQHDYHiBAgAABAgQIECBAgAAB\nAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECCQgIDgcAJN\nVAIBAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAAB\nAgQIECBAgAABwWF7gAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBA\ngAABAgQIECBAgAABAgQIECBAgEACAoLDCTRRCQQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQI\nECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQEh+0BAgQIECBAgAABAgQIECBAgAAB\nAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgkICA4n0EQlECBA\ngAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAAB\nAgQIEBActgcIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBA\ngAABAgQIECBAgAABAgQIJCAgOJxAE5VAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQI\nECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAQHDYHiBAgAABAgQIECBAgAABAgQIECBAgAAB\nAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECCQgIDgcAJNVAIBAgQIECBA\ngAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAAB\nwWF7gAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBA\ngAABAgQIECBAgEACAoLDCTRRCQQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQI\nECBAgAABAgQIECBAgAABAgQIECBAgAABAgQEh+0BAgQIECBAgAABAgQIECBAgAABAgQIECBAgAAB\nAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgkICA4n0EQlECBAgAABAgQIECBA\ngAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIEBActgcI\nECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBA\ngAABAgQIJCAgOJxAE5VAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQI\nECBAgAABAgQIECBAgAABAgQIECBAQHDYHiBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAAB\nAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECCQgIDgcAJNVAIBAgQIECBAgAABAgQIECBA\ngAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABwWF7gAABAgQI\nECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBA\ngEACAoLDCTRRCQQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQI\nECBAgAABAgQIECBAgAABAgQEh+0BAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAAB\nAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgkICA4n0EQlECBAgAABAgQIECBAgAABAgQIECBA\ngAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIEBActgcIECBAgAABAgQI\nECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIJCAg\nOJxAE5VAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQI\nECBAgAABAgQIECBAQHDYHiBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAAB\nAgQIECBAgAABAgQIECBAgAABAgQIECCQgIDgcAJNVAIBAgQIECBAgAABAgQIECBAgAABAgQIECBA\ngAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABwWF7gAABAgQIECBAgAABAgQI\nECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgEACAoLDCTRR\nCQQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQI\nECBAgAABAgQEh+0BAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAAB\nAgQIECBAgAABAgQIECBAgAABAgkICA4n0EQlECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBA\ngAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIEBActgcIECBAgAABAgQIECBAgAABAgQI\nECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIJCAgOJxAE5VAgAAB\nAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQI\nECBAQHDYHiBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAAB\nAgQIECBAgAABAgQIECCQgIDgcAJNVAIBAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBA\ngAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABwWF7gAABAgQIECBAgAABAgQIECBAgAABAgQI\nECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgEACAoLDCTRRCQQIECBAgAAB\nAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQE\nh+0BAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAAB\nAgQIECBAgAABAgkICA4n0EQlECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBA\ngAABAgQIECBAgAABAgQIECBAgAABAgQIEBActgcIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQI\nECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIJCAgOJxAE5VAgAABALine truncated
|
||||
"text/plain": [
|
||||
"<IPython.core.display.Image object>"
|
||||
]
|
||||
},
|
||||
"execution_count": 3,
|
||||
"execution_count": 2,
|
||||
"metadata": {
|
||||
"image/png": {
|
||||
"width": 600
|
||||
@@ -2841,7 +2841,7 @@
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"[NbConvertApp] Converting notebook ch16.ipynb to script\n",
|
||||
"[NbConvertApp] Writing 24782 bytes to ch16.py\n"
|
||||
"[NbConvertApp] Writing 24796 bytes to ch16.py\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
|
||||
@@ -1,6 +1,16 @@
|
||||
|
||||
# coding: utf-8
|
||||
|
||||
|
||||
import gzip
|
||||
import pyprind
|
||||
import pandas as pd
|
||||
from string import punctuation
|
||||
import re
|
||||
import numpy as np
|
||||
import os
|
||||
from collections import Counter
|
||||
import tensorflow as tf
|
||||
|
||||
# *Python Machine Learning 2nd Edition* by [Sebastian Raschka](https://sebastianraschka.com) and Vahid Mirjalili, Packt Publishing Ltd. 2017
|
||||
#
|
||||
# Code Repository: https://github.com/rasbt/python-machine-learning-book-2nd-edition
|
||||
@@ -15,7 +25,6 @@
|
||||
|
||||
# Note that the optional watermark extension is a small IPython notebook plugin that is being used to make the code reproducible. You can just skip the following line(s).
|
||||
|
||||
# In[1]:
|
||||
|
||||
|
||||
|
||||
@@ -44,16 +53,12 @@
|
||||
# - [Building the character-level RNN model](#Building-the-character-level-RNN-model)
|
||||
# - [Summary](#Summary)
|
||||
|
||||
# In[2]:
|
||||
|
||||
|
||||
from IPython.display import Image
|
||||
|
||||
|
||||
# In[ ]:
|
||||
|
||||
|
||||
import gzip
|
||||
|
||||
|
||||
with gzip.open('movie_data.csv.gz') as f_in, open('movie_data.csv', 'wb') as f_out:
|
||||
@@ -66,14 +71,12 @@ with gzip.open('movie_data.csv.gz') as f_in, open('movie_data.csv', 'wb') as f_o
|
||||
|
||||
# ## Representing sequences
|
||||
|
||||
# In[3]:
|
||||
|
||||
|
||||
|
||||
|
||||
# ## Understanding the different categories of sequence modeling
|
||||
|
||||
# In[4]:
|
||||
|
||||
|
||||
|
||||
@@ -82,38 +85,32 @@ with gzip.open('movie_data.csv.gz') as f_in, open('movie_data.csv', 'wb') as f_o
|
||||
|
||||
# ## Understanding the structure and flow of a recurrent neural network
|
||||
|
||||
# In[5]:
|
||||
|
||||
|
||||
|
||||
|
||||
# In[6]:
|
||||
|
||||
|
||||
|
||||
|
||||
# ## Computing activations in an RNN
|
||||
|
||||
# In[7]:
|
||||
|
||||
|
||||
|
||||
|
||||
# In[8]:
|
||||
|
||||
|
||||
|
||||
|
||||
# ## The challenges of learning long-range interactions
|
||||
|
||||
# In[9]:
|
||||
|
||||
|
||||
|
||||
|
||||
# ## Long short-term memory units
|
||||
|
||||
# In[10]:
|
||||
|
||||
|
||||
|
||||
@@ -124,26 +121,18 @@ with gzip.open('movie_data.csv.gz') as f_in, open('movie_data.csv', 'wb') as f_o
|
||||
|
||||
# ### Preparing the data
|
||||
|
||||
# In[11]:
|
||||
|
||||
|
||||
|
||||
|
||||
# In[1]:
|
||||
|
||||
|
||||
import pyprind
|
||||
import pandas as pd
|
||||
from string import punctuation
|
||||
import re
|
||||
import numpy as np
|
||||
|
||||
|
||||
df = pd.read_csv('movie_data.csv', encoding='utf-8')
|
||||
print(df.head(3))
|
||||
|
||||
|
||||
# In[ ]:
|
||||
|
||||
|
||||
## @Readers: PLEASE IGNORE THIS CELL
|
||||
@@ -155,14 +144,12 @@ print(df.head(3))
|
||||
## speeding up the run using a smaller
|
||||
## dataset for debugging
|
||||
|
||||
import os
|
||||
|
||||
|
||||
if 'TRAVIS' in os.environ:
|
||||
df = pd.read_csv('movie_data.csv', encoding='utf-8', nrows=500)
|
||||
|
||||
|
||||
# In[2]:
|
||||
|
||||
|
||||
## Preprocessing the data:
|
||||
@@ -170,7 +157,6 @@ if 'TRAVIS' in os.environ:
|
||||
## count each word's occurrence
|
||||
|
||||
|
||||
from collections import Counter
|
||||
|
||||
|
||||
counts = Counter()
|
||||
@@ -183,7 +169,6 @@ for i,review in enumerate(df['review']):
|
||||
counts.update(text.split())
|
||||
|
||||
|
||||
# In[3]:
|
||||
|
||||
|
||||
## Create a mapping:
|
||||
@@ -202,7 +187,6 @@ for review in df['review']:
|
||||
pbar.update()
|
||||
|
||||
|
||||
# In[4]:
|
||||
|
||||
|
||||
## Define fixed-length sequences:
|
||||
@@ -236,7 +220,6 @@ def create_batch_generator(x, y=None, batch_size=64):
|
||||
yield x[ii:ii+batch_size]
|
||||
|
||||
|
||||
# In[ ]:
|
||||
|
||||
|
||||
## @Readers: PLEASE IGNORE THIS CELL
|
||||
@@ -257,17 +240,14 @@ if 'TRAVIS' in os.environ:
|
||||
|
||||
# ### Embedding
|
||||
|
||||
# In[12]:
|
||||
|
||||
|
||||
|
||||
|
||||
# ### Building the RNN model
|
||||
|
||||
# In[5]:
|
||||
|
||||
|
||||
import tensorflow as tf
|
||||
|
||||
|
||||
class SentimentRNN(object):
|
||||
@@ -420,7 +400,6 @@ class SentimentRNN(object):
|
||||
#
|
||||
#
|
||||
|
||||
# In[6]:
|
||||
|
||||
|
||||
## Train:
|
||||
@@ -436,13 +415,11 @@ rnn = SentimentRNN(n_words=n_words,
|
||||
learning_rate=0.001)
|
||||
|
||||
|
||||
# In[7]:
|
||||
|
||||
|
||||
rnn.train(X_train, y_train, num_epochs=40)
|
||||
|
||||
|
||||
# In[ ]:
|
||||
|
||||
|
||||
## Test:
|
||||
@@ -452,7 +429,6 @@ print('Test Acc.: %.3f' % (
|
||||
np.sum(preds == y_true) / len(y_true)))
|
||||
|
||||
|
||||
# In[ ]:
|
||||
|
||||
|
||||
## Get probabilities:
|
||||
@@ -461,7 +437,6 @@ proba = rnn.predict(X_test, return_proba=True)
|
||||
|
||||
# ## Example application: character-level language modeling
|
||||
|
||||
# In[13]:
|
||||
|
||||
|
||||
|
||||
@@ -469,25 +444,20 @@ proba = rnn.predict(X_test, return_proba=True)
|
||||
# ### Preparing the data
|
||||
#
|
||||
|
||||
# In[14]:
|
||||
|
||||
|
||||
|
||||
|
||||
# In[15]:
|
||||
|
||||
|
||||
|
||||
|
||||
# In[16]:
|
||||
|
||||
|
||||
|
||||
|
||||
# In[1]:
|
||||
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
## Reading and processing text
|
||||
@@ -502,7 +472,6 @@ text_ints = np.array([char2int[ch] for ch in text],
|
||||
dtype=np.int32)
|
||||
|
||||
|
||||
# In[ ]:
|
||||
|
||||
|
||||
## @Readers: PLEASE IGNORE THIS CELL
|
||||
@@ -523,7 +492,6 @@ if 'TRAVIS' in os.environ:
|
||||
dtype=np.int32)
|
||||
|
||||
|
||||
# In[2]:
|
||||
|
||||
|
||||
def reshape_data(sequence, batch_size, num_steps):
|
||||
@@ -553,7 +521,6 @@ print(train_y[0, :10])
|
||||
print(''.join(int2char[i] for i in train_x[0, :50]))
|
||||
|
||||
|
||||
# In[3]:
|
||||
|
||||
|
||||
np.random.seed(123)
|
||||
@@ -574,11 +541,8 @@ for b in bgen:
|
||||
|
||||
# ### Building the character-level RNN model
|
||||
|
||||
# In[4]:
|
||||
|
||||
|
||||
import tensorflow as tf
|
||||
import os
|
||||
|
||||
class CharRNN(object):
|
||||
def __init__(self, num_classes, batch_size=64,
|
||||
@@ -759,7 +723,6 @@ class CharRNN(object):
|
||||
return ''.join(observed_seq)
|
||||
|
||||
|
||||
# In[5]:
|
||||
|
||||
|
||||
def get_top_char(probas, char_size, top_n=5):
|
||||
@@ -770,7 +733,6 @@ def get_top_char(probas, char_size, top_n=5):
|
||||
return ch_id
|
||||
|
||||
|
||||
# In[6]:
|
||||
|
||||
|
||||
batch_size = 64
|
||||
@@ -785,7 +747,6 @@ rnn.train(train_x, train_y,
|
||||
ckpt_dir='./model-100/')
|
||||
|
||||
|
||||
# In[7]:
|
||||
|
||||
|
||||
np.random.seed(123)
|
||||
@@ -795,7 +756,6 @@ print(rnn.sample(ckpt_dir='./model-100/',
|
||||
output_length=500))
|
||||
|
||||
|
||||
# In[8]:
|
||||
|
||||
|
||||
## run for 200 epochs
|
||||
@@ -808,7 +768,6 @@ rnn.train(train_x, train_y,
|
||||
ckpt_dir='./model-200/')
|
||||
|
||||
|
||||
# In[9]:
|
||||
|
||||
|
||||
del rnn
|
||||
@@ -827,7 +786,11 @@ print(rnn.sample(ckpt_dir='./model-200/',
|
||||
#
|
||||
# Readers may ignore the next cell.
|
||||
|
||||
# In[ ]:
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
Before Width: | Height: | Size: 405 KiB After Width: | Height: | Size: 406 KiB |