mirror of
https://github.com/RustyRaptor/Python-Machine-Learning-Second-Edition.git
synced 2026-12-03 16:05:20 -07:00
commit
This commit is contained in:
1 parent
1cf55acd75
commit
96f3e58e99
51 files changed
+1120
-1053
No files matched your search
@@ -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.
|
||||
+11
-2
@@ -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": {
|
||||
|
||||
+20
-78
@@ -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[ ]:
|
||||
|
||||
|
||||
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 141 KiB |
Reference in new issue
Block a user