訓練誤差與測試誤差?

本案例可視化了估算器在未曾見過的數據(測試數據)上的性能與訓練數據的性能如何不同。隨著正則化的增加,訓練集的性能會下降,而測試集上的性能在正則化參數的值范圍內最佳。這是一個使用Elastic-Net回歸模型、使用可解釋性方差,即來衡量性能的案例。(譯者注:可解釋性方差與有同向數學關系,因此兩者在某種意義上可以等同)

輸出:

Optimal regularization parameter : 0.00013141473626117567

輸入:

print(__doc__)

# 作者: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# 執照: BSD 3 clause

import numpy as np
from sklearn import linear_model

# #############################################################################
# 獲取樣本信息
n_samples_train, n_samples_test, n_features = 75150500
np.random.seed(0)
coef = np.random.randn(n_features)
coef[50:] = 0.0  # 只有前10個特征會影響模型
X = np.random.randn(n_samples_train + n_samples_test, n_features)
y = np.dot(X, coef)

# 分割訓練集與測試集
X_train, X_test = X[:n_samples_train], X[n_samples_train:]
y_train, y_test = y[:n_samples_train], y[n_samples_train:]

# #############################################################################
# 計算訓練與測試誤差
alphas = np.logspace(-5160)
enet = linear_model.ElasticNet(l1_ratio=0.7, max_iter=10000)
train_errors = list()
test_errors = list()
for alpha in alphas:
    enet.set_params(alpha=alpha)
    enet.fit(X_train, y_train)
    train_errors.append(enet.score(X_train, y_train))
    test_errors.append(enet.score(X_test, y_test))

i_alpha_optim = np.argmax(test_errors)
alpha_optim = alphas[i_alpha_optim]
print("Optimal regularization parameter : %s" % alpha_optim)

# 使用最佳正則化參數估計完整數據上的coef_
enet.set_params(alpha=alpha_optim)
coef_ = enet.fit(X, y).coef_

# #############################################################################
# 繪制結果方程

import matplotlib.pyplot as plt
plt.subplot(211)
plt.semilogx(alphas, train_errors, label='Train')
plt.semilogx(alphas, test_errors, label='Test')
plt.vlines(alpha_optim, plt.ylim()[0], np.max(test_errors), color='k',
           linewidth=3, label='Optimum on test')
plt.legend(loc='lower left')
plt.ylim([01.2])
plt.xlabel('Regularization parameter')
plt.ylabel('Performance')

# 展示預測的 coef_ 與真實的系數之間的差異
plt.subplot(212)
plt.plot(coef, label='True coef')
plt.plot(coef_, label='Estimated coef')
plt.legend()
plt.subplots_adjust(0.090.040.940.940.260.26)
plt.show()

腳本的總運行時間:(0分鐘2.662秒)