Ex 4: Varying regularization in Multi-layer Perceptron
此範例是比較不同的正歸化參數'alpha',對於使用scikit-learn的資料產生器 ,所產生的circlesmoonrandom n-class classification,三種資料集的成效。 PS:正規化為一種處理無限大、發散以及一些不合理表示式的方法,透過引入一項輔助性的概念——正規子(regulator),去限制函數使得函數不會發散 此處的Alpha參數即為正規子,目的是去限制權重(Weight,W)的大小,以防萬一overfitting與underfitting的問題,增加alpha值可能可以處理overfitting,反之減小alpha可能可以解決underfitting的問題,至於權重大小,如何影響輸出請看圖1:
圖1:比較同樣輸入,對於不同大小權重值,對於輸出的影響左圖為權重為5時,當輸入變動0.1時,輸出增加0.5,即輸出改變10%,右圖為權重為1時,當輸入變動0.1時,輸出增加0.1,即輸出改變2%,通常模型對於input較不敏感,模型表現較好 結果將顯示出:使用不同alpha值去限制權重產生出的決策邊界

(一)引入函式庫

1
print(__doc__)
2
3
4
# Author: Issam H. Laradji
5
# License: BSD 3 clause
6
7
import numpy as np
8
from matplotlib import pyplot as plt
9
from matplotlib.colors import ListedColormap
10
from sklearn.model_selection import train_test_split
11
from sklearn.preprocessing import StandardScaler
12
from sklearn.datasets import make_moons, make_circles, make_classification
13
from sklearn.neural_network import MLPClassifier
Copied!

(二)設定模型參數與產生資料

1
h = .02 # step size in the mesh
2
3
alphas = np.logspace(-5, 3, 5)#
4
names = []
5
for i in alphas:
6
names.append('alpha ' + str(i))
7
8
classifiers = []
9
for i in alphas:
10
classifiers.append(MLPClassifier(alpha=i, random_state=1))
11
12
X, y = make_classification(n_features=2, n_redundant=0, n_informative=2,
13
random_state=0, n_clusters_per_class=1)
14
rng = np.random.RandomState(2)
15
X += 2 * rng.uniform(size=X.shape)
16
linearly_separable = (X, y)
17
18
datasets = [make_moons(noise=0.3, random_state=0),
19
make_circles(noise=0.2, factor=0.5, random_state=1),
20
linearly_separable]
21
22
figure = plt.figure(figsize=(17, 9))
23
i = 1
24
# iterate over datasets
25
for X, y in datasets:
26
# preprocess dataset, split into training and test part
27
X = StandardScaler().fit_transform(X)
28
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.4)
29
30
x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5
31
y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5
32
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
33
np.arange(y_min, y_max, h))
Copied!

(三)繪製圖形

1
# just plot the dataset first
2
cm = plt.cm.RdBu
3
cm_bright = ListedColormap(['#FF0000', '#0000FF'])
4
ax = plt.subplot(len(datasets), len(classifiers) + 1, i)
5
# Plot the training points
6
ax.scatter(X_train[:, 0], X_train[:, 1], c=y_train, cmap=cm_bright)
7
# and testing points
8
ax.scatter(X_test[:, 0], X_test[:, 1], c=y_test, cmap=cm_bright, alpha=0.6)
9
ax.set_xlim(xx.min(), xx.max())
10
ax.set_ylim(yy.min(), yy.max())
11
ax.set_xticks(())
12
ax.set_yticks(())
13
i += 1
14
15
# iterate over classifiers
16
for name, clf in zip(names, classifiers):
17
ax = plt.subplot(len(datasets), len(classifiers) + 1, i)
18
clf.fit(X_train, y_train)
19
score = clf.score(X_test, y_test)
20
21
# Plot the decision boundary. For that, we will assign a color to each
22
# point in the mesh [x_min, x_max]x[y_min, y_max].
23
if hasattr(clf, "decision_function"):
24
Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()])
25
else:
26
Z = clf.predict_proba(np.c_[xx.ravel(), yy.ravel()])[:, 1]
27
28
# Put the result into a color plot
29
Z = Z.reshape(xx.shape)
30
ax.contourf(xx, yy, Z, cmap=cm, alpha=.8)
31
32
# Plot also the training points
33
ax.scatter(X_train[:, 0], X_train[:, 1], c=y_train, cmap=cm_bright)
34
# and testing points
35
ax.scatter(X_test[:, 0], X_test[:, 1], c=y_test, cmap=cm_bright,
36
alpha=0.6)
37
38
ax.set_xlim(xx.min(), xx.max())
39
ax.set_ylim(yy.min(), yy.max())
40
ax.set_xticks(())
41
ax.set_yticks(())
42
ax.set_title(name)
43
ax.text(xx.max() - .3, yy.min() + .3, ('%.2f' % score).lstrip('0'),
44
size=15, horizontalalignment='right')
45
i += 1
46
47
figure.subplots_adjust(left=.02, right=.98)
48
plt.show()
Copied!
圖2:不同alpha結果圖,每張子圖右下角是分辨率,alpha值很大,模型的結果明顯underfitting