This commit is contained in:
packtBhagyashree committed 2017-09-19 15:50:43 +05:30
1 parent 1cf55acd75
commit 96f3e58e99
51 files changed
+1120 -1053

No files matched your search

+48
View File
@@ -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.
![](images/jupyter-example-1.png)
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.
![](images/jupyter-example-2.png)
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.
+3 -127
View File
@@ -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": {
+6 -36
View File
@@ -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[ ]:
Binary file not shown.

After

Width:  |  Height:  |  Size: 93 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 124 KiB