【机器学习】6.1.过拟合和欠拟合

包含全部示例的代码仓库见GIthub

1 导入库

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
from sklearn.metrics import mean_squared_error

2 数据准备

x = np.linspace(0,10,20)
y = x**3 + np.random.rand(20)*160 + 10
plt.scatter(x, y)

在这里插入图片描述

3 模型构建

3.1 欠拟合

model = LinearRegression()
model.fit(x.reshape(-1,1), y)
y_pred = model.predict(x.reshape(-1,1))
plt.scatter(x, y)
plt.plot(x, y_pred, c='r')

在这里插入图片描述

3.2 正常拟合

q4 = PolynomialFeatures(degree=4)
x4 = q4.fit_transform(x.reshape(-1,1))
model4 = LinearRegression()
model4.fit(x4, y)
y_pred4 = model4.predict(x4)
plt.scatter(x, y)
plt.plot(x, y_pred4, c='r')

在这里插入图片描述

3.3 过拟合

q20 = PolynomialFeatures(degree=20)
x20 = q20.fit_transform(x.reshape(-1,1))
model20 = LinearRegression()
model20.fit(x20, y)
y_pred20 = model20.predict(x20)
plt.scatter(x, y)
plt.plot(x, y_pred20, c='r')

在这里插入图片描述

x2 = np.linspace(0,20,30)
y2 = x2**3 + np.random.rand(30)*160 + 10

用新的数据集进行模型预测

q20 = PolynomialFeatures(degree=20)
x22 = q20.fit_transform(x2.reshape(-1,1))
y_pred22 = model20.predict(x22)
plt.scatter(x, y)
plt.plot(x2, y_pred22, c='r')

在这里插入图片描述

4 模型测试

欠拟合

mean_squared_error(model.predict(x.reshape(-1,1)),y)
# output
14478.676863285145

正常拟合

mean_squared_error(model4.predict(x4),y)
# output
1757.2597799281452

过拟合

mean_squared_error(model20.predict(x20),y)
# output
1208.419154080902
  • 11
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LouHerGetUp

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值