提交 fe652345 编写于 作者: W wizardforcel

fmt

上级 df4178c6
......@@ -56,19 +56,19 @@ best_model = clf.fit(X, y)
print('Best Number Of Princpal Components:', best_model.best_estimator_.get_params()['preprocess__pca__n_components'])
print('Best Penalty:', best_model.best_estimator_.get_params()['classifier__penalty'])
print('Best C:', best_model.best_estimator_.get_params()['classifier__C'])
```
'''
Best Number Of Princpal Components: 3
Best Penalty: l1
Best C: 59.9484250319
'''
```py
```
## 使用网格搜索的超参数调优
![](img/3f439b203d4e179a2c15c84d3bb15cb7.jpg)
```
```py
# 加载库
import numpy as np
from sklearn import linear_model, datasets
......@@ -116,12 +116,12 @@ array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])
'''
```py
```
## 使用随机搜索的超参数调优
```
```py
# 加载库
from scipy.stats import uniform
from sklearn import linear_model, datasets
......@@ -169,14 +169,14 @@ array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 1, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])
'''
```py
```
## 使用网格搜索的模型选择
![](img/bc7d72780c8296115ef744873807d5ff.jpg)
```
```py
# 加载库
import numpy as np
from sklearn import datasets
......@@ -192,11 +192,11 @@ np.random.seed(0)
iris = datasets.load_iris()
X = iris.data
y = iris.target
```py
```
请注意,我们包括需要搜索的多个可能的学习算法和多个可能的超参数值。
```
```py
# 创建流水线
pipe = Pipeline([('classifier', RandomForestClassifier())])
......@@ -234,12 +234,12 @@ array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])
'''
```py
```
## 带有参数选项的流水线
```
```py
# 导入所需的包
import numpy as np
from sklearn import linear_model, decomposition, datasets
......
......@@ -10,7 +10,7 @@
![](img/53a181f79fb487549a6006294f7bc879.jpg)
```
```py
# 加载库
from sklearn.ensemble import AdaBoostClassifier
from sklearn import datasets
......@@ -28,7 +28,7 @@ y = iris.target
* `learning_rate`是每个模型对权重的贡献,默认为`1`。 降低学习率将意味着权重将增加或减少到很小的程度,迫使模型训练更慢(但有时会产生更好的表现得分)。
* `loss``AdaBoostRegressor`独有的,它设置了更新权重时使用的损失函数。 这默认为线性损失函数,但可以更改为`square``exponential`
```
```py
# 创建 adaboost 决策树分类器对象
clf = AdaBoostClassifier(n_estimators=50,
learning_rate=1,
......@@ -42,7 +42,7 @@ model = clf.fit(X, y)
![](img/ec18cd723a8b269d960ff8c900a113eb.jpg)
```
```py
# 加载库
from sklearn.tree import DecisionTreeClassifier
from sklearn import datasets
......@@ -76,7 +76,7 @@ model.predict_proba(observation)
![](img/89fdaf9caa2b88f10c2e281f0071ab1e.jpg)
```
```py
# 加载库
from sklearn.tree import DecisionTreeRegressor
from sklearn import datasets
......@@ -93,7 +93,7 @@ $\text{MSE} = \frac{1}{n} \sum_{i=1}^{n} (y_i - \hat{y}_i)^2$
其中 $y_i$ 是目标的真实值,$\hat{y}_i$ 是预测值。
```
```py
# 创建决策树回归器对象
regr = DecisionTreeRegressor(random_state=0)
......@@ -113,7 +113,7 @@ model.predict(observation)
![](img/3eb344ac521726353def27e303517ba9.jpg)
```
```py
# 加载库
from sklearn.ensemble import RandomForestClassifier
from sklearn import datasets
......@@ -175,7 +175,7 @@ plt.show()
注:还有其他重要定义,但在本教程中,我们将讨论限制为基尼重要性。
```
```py
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn import datasets
......@@ -186,7 +186,7 @@ from sklearn.metrics import accuracy_score
本教程中使用的数据集是着名的[鸢尾花数据集](https://en.wikipedia.org/wiki/Iris_flower_data_set)鸢尾花数据包含来自三种鸢尾`y`和四个特征变量`X`的 50 个样本。
```
```py
# 加载鸢尾花数据集
iris = datasets.load_iris()
......@@ -246,7 +246,7 @@ for feature in zip(feat_labels, clf.feature_importances_):
上面的得分是每个变量的重要性得分。 有两点需要注意。 首先,所有重要性得分加起来为 100%。 其次,“花瓣长度”和“花瓣宽度”远比其他两个特征重要。结合起来,“花瓣长度”和“花瓣宽度”的重要性约为 0.86!显然,这些是最重要的特征。
```
```py
# 创建一个选择器对象,
# 该对象将使用随机森林分类器来标识重要性大于 0.15 的特征
sfm = SelectFromModel(clf, threshold=0.15)
......@@ -314,7 +314,7 @@ accuracy_score(y_test, y_important_pred)
## 在随机森林中处理不平衡类别
```
```py
# 加载库
from sklearn.ensemble import RandomForestClassifier
import numpy as np
......@@ -339,7 +339,7 @@ $w_j = \frac{n}{kn_{j}}$
其中 $w_j$ 是类 $j$ 的权重,$n$ 是观测数,$n_j$ 是类 $j$ 中的观测数,$k$ 是类的总数。
```
```py
# 创建决策树分类器对象
clf = RandomForestClassifier(random_state=0, n_jobs=-1, class_weight="balanced")
......@@ -349,7 +349,7 @@ model = clf.fit(X, y)
## 随机森林分类器
```
```py
# 加载库
from sklearn.ensemble import RandomForestClassifier
from sklearn import datasets
......@@ -372,7 +372,7 @@ observation = [[ 5, 4, 3, 2]]
model.predict(observation)
```
```
```py
array([1])
```
......@@ -386,7 +386,7 @@ array([1])
本教程的数据很有名。 被称为[鸢尾花数据集](https://en.wikipedia.org/wiki/Iris_flower_data_set),它包含四个变量,测量了三个鸢尾花物种的各个部分,然后是带有物种名称的第四个变量。 它在机器学习和统计社区中如此着名的原因是,数据需要很少的预处理(即没有缺失值,所有特征都是浮点数等)。
```
```py
# 加载鸢尾花数据集
from sklearn.datasets import load_iris
......@@ -420,7 +420,7 @@ df.head()
| 3 | 4.6 | 3.1 | 1.5 | 0.2 |
| 4 | 5.0 | 3.6 | 1.4 | 0.2 |
```
```py
# 添加带有物种名称的新列,我们要尝试预测它
df['species'] = pd.Categorical.from_codes(iris.target, iris.target_names)
......@@ -436,7 +436,7 @@ df.head()
| 3 | 4.6 | 3.1 | 1.5 | 0.2 | setosa |
| 4 | 5.0 | 3.6 | 1.4 | 0.2 | setosa |
```
```py
# 创建一个新列,每列生成一个0到1之间的随机数,
# 如果该值小于或等于.75,则将该单元格的值设置为 True
# 否则为 False。这是一种简洁方式,
......@@ -455,7 +455,7 @@ df.head()
| 3 | 4.6 | 3.1 | 1.5 | 0.2 | setosa | True |
| 4 | 5.0 | 3.6 | 1.4 | 0.2 | setosa | True |
```
```py
# 创建两个新的数据帧,一个包含训练行,另一个包含测试行
train, test = df[df['is_train']==True], df[df['is_train']==False]
......@@ -520,7 +520,7 @@ RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini',
让我们现在实现它。
```
```py
# 将我们训练的分类器应用于测试数据
# (记住,以前从未见过它)
clf.predict(test[features])
......@@ -533,7 +533,7 @@ array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 2, 2, 1, 1, 2, 2, 2,
你在上面看到什么? 请记住,我们将三种植物中的每一种编码为 0, 1 或 2。 以上数字列表显示,我们的模型基于萼片长度,萼片宽度,花瓣长度和花瓣宽度,预测每种植物的种类。 分类器对于每种植物有多自信? 我们也可以看到。
```
```py
# 查看前 10 个观测值的预测概率
clf.predict_proba(test[features])[0:10]
......@@ -555,7 +555,7 @@ array([[ 1\. , 0\. , 0\. ],
现在我们已经预测了测试数据中所有植物的种类,我们可以比较我们预测的物种与该植物的实际物种。
```
```py
# 为每个预测的植物类别
# 创建植物的实际英文名称
preds = iris.target_names[clf.predict(test[features])]
......@@ -588,7 +588,7 @@ Categories (3, object): [setosa, versicolor, virginica]
混淆矩阵的简短解释方式是:对角线上的任何东西都被正确分类,对角线之外的任何东西都被错误地分类。
```
```py
# 创建混淆矩阵
pd.crosstab(test['species'], preds, rownames=['Actual Species'], colnames=['Predicted Species'])
```
......@@ -602,7 +602,7 @@ pd.crosstab(test['species'], preds, rownames=['Actual Species'], colnames=['Pred
虽然我们没有像 OLS 那样得到回归系数,但我们得到的分数告诉我们,每个特征在分类中的重要性。 这是随机森林中最强大的部分之一,因为我们可以清楚地看到,在分类中花瓣宽度比萼片宽度更重要。
```
```py
# 查看特征列表和它们的重要性得分
list(zip(train[features], clf.feature_importances_))
......@@ -616,7 +616,7 @@ list(zip(train[features], clf.feature_importances_))
## 随机森林回归
```
```py
# 加载库
from sklearn.ensemble import RandomForestRegressor
from sklearn import datasets
......@@ -635,7 +635,7 @@ model = regr.fit(X, y)
## 在随机森林中选择特征重要性
```
```py
# 加载库
from sklearn.ensemble import RandomForestClassifier
from sklearn import datasets
......@@ -652,7 +652,7 @@ clf = RandomForestClassifier(random_state=0, n_jobs=-1)
数字越大,特征越重要(所有重要性得分总和为1)。 通过绘制这些值,我们可以为随机森林模型添加可解释性。
```
```py
# 创建选择重要性大于或等于阈值的特征的对象
selector = SelectFromModel(clf, threshold=0.3)
......@@ -676,7 +676,7 @@ model = clf.fit(X_important, y)
## 泰坦尼克比赛和随机森林
```
```py
import pandas as pd
import numpy as np
from sklearn import preprocessing
......@@ -687,7 +687,7 @@ import csv as csv
你可以在 [Kaggle](https://www.kaggle.com/c/titanic) 获取数据。
```
```py
# 加载数据
train = pd.read_csv('data/train.csv')
test = pd.read_csv('data/test.csv')
......@@ -700,7 +700,7 @@ features = ['Age', 'SibSp','Parch','Fare','male','embarked_Q','embarked_S','Pcla
在这里,我们将性别标签(`male``female`)转换为虚拟变量(`1``0`)。
```
```py
# 创建编码器
sex_encoder = preprocessing.LabelEncoder()
......@@ -744,7 +744,7 @@ test = pd.concat([test, test_Pclass_dummied], axis=1)
`Age`特征的许多值都缺失,并且会妨碍随机森林进行训练。 我们解决这个问题,我们将用年龄的平均值填充缺失值(一个实用的操作)。
```
```py
# 创建填充器对象
age_imputer = preprocessing.Imputer(missing_values='NaN', strategy='mean', axis=0)
......@@ -813,7 +813,7 @@ submission_file.close()
## 可视化决策树
```
```py
# 加载库
from sklearn.tree import DecisionTreeClassifier
from sklearn import datasets
......@@ -846,7 +846,7 @@ Image(graph.create_png())
![png](https://chrisalbon.com/machine_learning/trees_and_forests/visualize_a_decision_tree/visualize_a_decision_tree_8_0.png)
```
```py
# 创建 PDF
graph.write_pdf("iris.pdf")
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册