深度学习-从零开始(2) - LinearRegression

2023-10-07 20:33

本文主要是介绍深度学习-从零开始(2) - LinearRegression,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

本章背景

本章是来源于coursera课程 python-machine-learning中的作业2内容。

本章内容

  • 多项式线性回归
  • 决定系数 R2 (coefficient of determination) 的计算
  • ridge线性回归
  • lasso线性回归

参考

  • 评价回归模型
  • r2_score为负数的问题探讨

0. Polynomial LinearRegression(多项式线性回归)

随机创建如下数据:

import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_splitnp.random.seed(0)
n = 15
x = np.linspace(0,10,n) + np.random.randn(n)/5
y = np.sin(x)+x/6 + np.random.randn(n)/10X_train, X_test, y_train, y_test = train_test_split(x, y, random_state=0)

创建特定维度的多项式线性回归:

使用degree = 1,3,6 and 9 来训练X_train,并随机生成一些预测数据验证拟合结果:

def test_1():from sklearn.linear_model import LinearRegressionfrom sklearn.preprocessing import PolynomialFeaturesxx_pred = np.linspace(0, 10, 100)degrees = [1, 3, 6, 9]results = []for index in range(0, 4):degree = degrees[index]regression = LinearRegression()featurizer = PolynomialFeatures(degree=degree)X_train_features = featurizer.fit_transform(X_train.reshape(-1, 1))regression.fit(X_train_features, y_train.reshape(-1, 1))xx_pred_features = featurizer.transform(xx_pred.reshape(-1, 1))yy_pred = regression.predict(xx_pred_features)# append the resultsresults.append(yy_pred.reshape(1, -1))return np.concatenate(results)# 将几个维度的多项式拟合曲线绘制出来
def plot_results(degree_predictions):import matplotlib.pyplot as pltplt.figure(figsize=(10,5))plt.plot(X_train, y_train, 'o', label='training data', markersize=10)plt.plot(X_test, y_test, 'o', label='test data', markersize=10)for i,degree in enumerate([1,3,6,9]):plt.plot(np.linspace(0,10,100), degree_predictions[i], alpha=0.8, lw=2, label='degree={}'.format(degree))plt.ylim(-1,2.5)plt.legend(loc=4)plt.show()plot_results(test_1())

1. coefficient of determination (决定系数R2)

决定系数(coefficient of determination)的计算方法:
R2-score公式
R2期待值越接近1说明拟合越好,越接近0说明拟合结果差。同时根据公式可以发现,在实际计算中R2是可能为负数的,通过简单计算,当R^2为负数时,说明:
当R2-score为负数
说明拟合结果差到不如使用均值。
还是使用上面的数据,分别计算X_train 和 X_test的R^2:

def test_2():from sklearn.linear_model import LinearRegressionfrom sklearn.preprocessing import PolynomialFeaturesfrom sklearn.metrics.regression import r2_score# Your code hereresults = []model_cnt = 10result_train = []result_test = []for degree in range(0, model_cnt):linearRegression = LinearRegression()featurizer = PolynomialFeatures(degree=degree)X_train_features = featurizer.fit_transform(X_train.reshape(-1, 1))y_train_features = y_train.reshape(-1, 1)linearRegression.fit(X_train_features, y_train_features)y_train_pred = linearRegression.predict(X_train_features)print('X_train r2_score ==> : ', r2_score(y_train_features, y_train_pred))result_train.append(r2_score(y_train_features, y_train_pred))# calculate the values for Test setX_test_features = featurizer.transform(X_test.reshape(-1, 1))y_test_pred = linearRegression.predict(X_test_features)y_test_features = y_test.reshape(-1, 1)print('X_test r2-score ==> : ', r2_score(y_test_features, y_test_pred))result_test.append(r2_score(y_test_features, y_test_pred))results.append(np.array(result_train).reshape(10, ))results.append(np.array(result_test).reshape(10, ))print(results[0].shape, results[1].shape)print(results)return results# Your answer here

从代码中也可以看出来,在sklearn工具包中已经包含了r2_score的计算函数,直接传入真实值和预测值即可计算,当然可以通过如上公式自行计算。

2. Ridge线性回归

Ridge线性回归是改良后的最小二乘法, 是有偏估计的回归方法, 即给损失函数加上一个正则化项, 也叫惩罚项(L2范数),防止过拟合。

Ridge回归的特点是以损失部分信息、降低精度为代价获得回归系数更为符合实际、更可靠的回归方法,对病态数据的拟合要强于最小二乘法。

Ridge的公式如下
Ridge回归损失函数
其中, m是样本量, n是特征数, λ是惩罚项参数(其取值大于0), 加惩罚项主要为了让模型参数的取值不能过大. 当λ趋于无穷大时, 对应βj趋向于0, 而βj表示的是因变量随着某一自变量改变一个单位而变化的数值(假设其他自变量均保持不变), 这时, 自变量之间的共线性对因变量的影响几乎不存在, 故其能有效解决自变量之间的多重共线性问题, 同时也能防止过拟合.

代码示例:

    import numpy as npimport pandas as pdfrom sklearn.model_selection import train_test_splitfrom matplotlib.pyplot import MultipleLocatorfrom sklearn.preprocessing import PolynomialFeaturesfrom sklearn.linear_model import Lasso, LinearRegression, Ridgefrom sklearn.metrics.regression import r2_scorenp.random.seed(0)n = 15x = np.linspace(0, 10, n) + np.random.randn(n) / 5y = np.sin(x) + x / 6 + np.random.randn(n) / 10X_train, X_test, y_train, y_test = train_test_split(x, y, random_state=0)# Your code herenormalLinearRegression = LinearRegression()ridgeLinearRegression = Ridge(alpha=0.01, max_iter=10000, solver='svd')featurizer = PolynomialFeatures(degree=12)X_train_features = featurizer.fit_transform(X_train.reshape(-1, 1))X_test_features = featurizer.transform(X_test.reshape(-1, 1))# train the non-regularized linearRegression modelnormalLinearRegression.fit(X_train_features, y_train.reshape(-1, 1))y_test_pred_normal = normalLinearRegression.predict(X_test_features)# cal the R2 score for non-regularized modelr2_score_normal = r2_score(y_test.reshape(-1, 1), y_test_pred_normal)print('non-regularized linearRegression r2-score ==> ', r2_score_normal)# train the ridge linearRegression modelridgeLinearRegression.fit(X_train_features, y_train.reshape(-1, 1))y_test_pred_ridge = ridgeLinearRegression.predict(X_test_features)# cal the R2-score for Ridge-regressionr2_score_ridge = r2_score(y_test.reshape(-1, 1), y_test_pred_ridge)print('ridge-regularized linearRegression r2-score ==> ', r2_score_ridge)

Ridge回归并不能解决减少系数/维度数量的问题,其系数均不为0。

3. LASSO线性回归

模型参数越多复杂度越高,即使用线性回归依然有很多的参数需要训练,并且这也会造成一定程度上的过拟合。并且最终得到的模型的可解释性也不高。这个时候可以考虑引入lasso回归。

Lasso回归的特点是可以在拟合训练数据的同时进行变量选择(Variable Selection)。那么它是通过什么机制选择的呢?答案就是:正则化(Regularization)!或者可以简单的把这个东西叫做惩罚项。

LASSO的公式如下
Lasso回归损失函数
代码示例:

    import numpy as npimport pandas as pdfrom sklearn.model_selection import train_test_splitfrom matplotlib.pyplot import MultipleLocatorfrom sklearn.preprocessing import PolynomialFeaturesfrom sklearn.linear_model import Lasso, LinearRegression, Ridgefrom sklearn.metrics.regression import r2_scorenp.random.seed(0)n = 15x = np.linspace(0, 10, n) + np.random.randn(n) / 5y = np.sin(x) + x / 6 + np.random.randn(n) / 10X_train, X_test, y_train, y_test = train_test_split(x, y, random_state=0)# Your code herenormalLinearRegression = LinearRegression()ridgeLinearRegression = Ridge(alpha=0.01, max_iter=10000, solver='svd')featurizer = PolynomialFeatures(degree=12)X_train_features = featurizer.fit_transform(X_train.reshape(-1, 1))X_test_features = featurizer.transform(X_test.reshape(-1, 1))# train the non-regularized linearRegression modelnormalLinearRegression.fit(X_train_features, y_train.reshape(-1, 1))y_test_pred_normal = normalLinearRegression.predict(X_test_features)# cal the R2 score for non-regularized modelr2_score_normal = r2_score(y_test.reshape(-1, 1), y_test_pred_normal)print('non-regularized linearRegression r2-score ==> ', r2_score_normal)# train the lasso linearRegression modellassoLinearRegression.fit(X_train_features, y_train.reshape(-1, 1))y_test_pred_lasso = lassoLinearRegression.predict(X_test_features)# cal the R2 score for lasso-regularized modelr2_score_lasso = r2_score(y_test.reshape(-1, 1), y_test_pred_lasso)print('lasso-regularized linearRegression r2-score ==> ', r2_score_lasso)

Lasso回归可以解决减少系数/维度数量的问题,其部分系数为0。

这篇关于深度学习-从零开始(2) - LinearRegression的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/160267

相关文章

深度解析Python中递归下降解析器的原理与实现

《深度解析Python中递归下降解析器的原理与实现》在编译器设计、配置文件处理和数据转换领域,递归下降解析器是最常用且最直观的解析技术,本文将详细介绍递归下降解析器的原理与实现,感兴趣的小伙伴可以跟随... 目录引言:解析器的核心价值一、递归下降解析器基础1.1 核心概念解析1.2 基本架构二、简单算术表达

深度解析Java @Serial 注解及常见错误案例

《深度解析Java@Serial注解及常见错误案例》Java14引入@Serial注解,用于编译时校验序列化成员,替代传统方式解决运行时错误,适用于Serializable类的方法/字段,需注意签... 目录Java @Serial 注解深度解析1. 注解本质2. 核心作用(1) 主要用途(2) 适用位置3

Java MCP 的鉴权深度解析

《JavaMCP的鉴权深度解析》文章介绍JavaMCP鉴权的实现方式,指出客户端可通过queryString、header或env传递鉴权信息,服务器端支持工具单独鉴权、过滤器集中鉴权及启动时鉴权... 目录一、MCP Client 侧(负责传递,比较简单)(1)常见的 mcpServers json 配置

Maven中生命周期深度解析与实战指南

《Maven中生命周期深度解析与实战指南》这篇文章主要为大家详细介绍了Maven生命周期实战指南,包含核心概念、阶段详解、SpringBoot特化场景及企业级实践建议,希望对大家有一定的帮助... 目录一、Maven 生命周期哲学二、default生命周期核心阶段详解(高频使用)三、clean生命周期核心阶

深度剖析SpringBoot日志性能提升的原因与解决

《深度剖析SpringBoot日志性能提升的原因与解决》日志记录本该是辅助工具,却为何成了性能瓶颈,SpringBoot如何用代码彻底破解日志导致的高延迟问题,感兴趣的小伙伴可以跟随小编一起学习一下... 目录前言第一章:日志性能陷阱的底层原理1.1 日志级别的“双刃剑”效应1.2 同步日志的“吞吐量杀手”

Unity新手入门学习殿堂级知识详细讲解(图文)

《Unity新手入门学习殿堂级知识详细讲解(图文)》Unity是一款跨平台游戏引擎,支持2D/3D及VR/AR开发,核心功能模块包括图形、音频、物理等,通过可视化编辑器与脚本扩展实现开发,项目结构含A... 目录入门概述什么是 UnityUnity引擎基础认知编辑器核心操作Unity 编辑器项目模式分类工程

深度解析Python yfinance的核心功能和高级用法

《深度解析Pythonyfinance的核心功能和高级用法》yfinance是一个功能强大且易于使用的Python库,用于从YahooFinance获取金融数据,本教程将深入探讨yfinance的核... 目录yfinance 深度解析教程 (python)1. 简介与安装1.1 什么是 yfinance?

Python学习笔记之getattr和hasattr用法示例详解

《Python学习笔记之getattr和hasattr用法示例详解》在Python中,hasattr()、getattr()和setattr()是一组内置函数,用于对对象的属性进行操作和查询,这篇文章... 目录1.getattr用法详解1.1 基本作用1.2 示例1.3 原理2.hasattr用法详解2.

深度解析Spring Security 中的 SecurityFilterChain核心功能

《深度解析SpringSecurity中的SecurityFilterChain核心功能》SecurityFilterChain通过组件化配置、类型安全路径匹配、多链协同三大特性,重构了Spri... 目录Spring Security 中的SecurityFilterChain深度解析一、Security

深度解析Nginx日志分析与499状态码问题解决

《深度解析Nginx日志分析与499状态码问题解决》在Web服务器运维和性能优化过程中,Nginx日志是排查问题的重要依据,本文将围绕Nginx日志分析、499状态码的成因、排查方法及解决方案展开讨论... 目录前言1. Nginx日志基础1.1 Nginx日志存放位置1.2 Nginx日志格式2. 499