python 留一交叉验证

基本原理

K折交叉验证

简单来说,K折交叉验证就是:

  • 把数据集划分成K份,取出其中一份作为测试集,另外的K - 1份作为训练集。
  • 通过训练集得到回归方程,再把测试集带入该回归方程,得到预测值。
  • 计算预测值与真实值的差值的平方,得到平方损失函数(或其他的损失函数)。
  • 重复以上过程,总共得到K个回归方程和K个损失函数,其中损失函数最小的回归方程就是最优解。
留一交叉验证

留一交叉验证是K折交叉验证的特殊情况,即:将数据集划分成N份,N为数据集总数。就是只留一个数据作为测试集,该特殊情况称为“留一交叉验证”。

代码实现

'''留一交叉验证'''

import numpy as np

# K折交叉验证
data = [[12, 1896], [11, 1900], [11, 1904], [10.8, 1908], [10.8, 1912], [10.8, 1920], [10.6, 1924], [10.8, 1928],
        [10.3, 1932], [10.3, 1936], [10.3, 1948], [10.4, 1952], [10.5, 1956], [10.2, 1960], [10.0, 1964], [9.95, 1968],
        [10.14, 1972], [10.06, 1976], [10.25, 1980], [9.99, 1984], [9.92, 1988], [9.96, 1992], [9.84, 1996],
        [9.87, 2000], [9.85, 2004], [9.69, 2008]]

length = len(data)


# 得到训练集和测试集
def Get_test_train(length, data, i):
    test_data = data[i]  # 测试集
    train_data = data[:]
    train_data.pop(i)  # 训练集
    return train_data, test_data


# 得到线性回归直线
def Get_line(train_data):
    time = []
    year = []
    average_year_time = 0
    average_year_year = 0

    for i in train_data:
        time.append(i[0])
        year.append(i[1])

    time = np.array(time)
    year = np.array(year)

    average_year = sum(year) / length  # year拔
    average_time = sum(time) / length  # time拔

    for i in train_data:
        average_year_time = average_year_time + i[0] * i[1]
        average_year_year = average_year_year + i[1] ** 2
    average_year_time = average_year_time / length  # (year, time)拔
    average_year_year = average_year_year / length  # (year, year)拔
    # 线性回归:t = w0 + w1 * x
    w1 = (average_year_time - average_year * average_time) / (average_year_year - average_year * average_year)
    w0 = average_time - w1 * average_year
    return w0, w1


# 得到损失函数
def Get_loss_func(w0, w1, test_data):
    time_real = test_data[0]
    time_predict = eval('{} + {} * {}'.format(w0, w1, test_data[1]))
    loss = (time_predict - time_real) ** 2
    dic['t = {} + {}x'.format(w0, w1)] = loss
    return dic


if __name__ == '__main__':
    dic = {}  # 存放建为回归直线,值为损失函数的字典

    for i in range(length):
        train_data, test_data = Get_test_train(length, data, i)
        w0, w1 = Get_line(train_data)
        Get_loss_func(w0, w1, test_data)
        dic = Get_loss_func(w0, w1, test_data)

    min_loss = min(dic.values())
    best_line = [k for k, v in dic.items() if v == min_loss][0]
    print('最佳回归直线:', best_line)
    print('最小损失函数:', min_loss)

  • 0
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值