机器学习中的模型优化与金融预测案例
1. 过拟合问题
1.1 过拟合的演示
为了演示过拟合,我们使用不同次数的多项式特征来增强线性模型,虽然模型在特征方面仍然是线性的,但它比之前研究的模型更强大,有能力包含数据中的错误波动。可以通过将历史数据拆分为训练集和测试集来检测过拟合。
以下是用于演示过拟合的代码:
def demo_overfitting():
def visualize_overfitting():
train_model(optimal_model, X, y)
train_model(complex_model, X, y)
_, ax = plt.subplots(figsize=(9, 7))
ax.set_yticklabels([])
ax.set_xticklabels([])
ax.grid(False)
X_test = np.linspace(0, 1.2, 100)
plt.plot(X_test, np.sin(2 * np.pi * X_test), label='True function')
plt.plot(
X_test,
optimal_model.predict(X_test[:, np.newaxis]),
label='Optimal model',
ls='-.')
plt.plot