# 导入第三方模块
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn import model_selection
from sklearn.linear_model import Ridge,RidgeCV

# 读取糖尿病数据集
diabetes = pd.read_excel(r'F:\\python_Data_analysis_and_mining\\08\\diabetes.xlsx', sep = '')
print(diabetes.shape)
print(diabetes.head())
# 构造自变量(剔除患者性别、年龄和因变量)
predictors = diabetes.columns[2:-1]
# 将数据集拆分为训练集和测试集
X_train, X_test, y_train, y_test = model_selection.train_test_split(diabetes[predictors], diabetes['Y'],test_size = 0.2, random_state = 1234 )
# 构造不同的Lambda值
Lambdas = np.logspace(-5, 2, 200)
print(Lambdas.shape)
# 构造空列表,用于存储模型的偏回归系数
ridge_cofficients = []
# 循环迭代不同的Lambda值
for Lambda in Lambdas:
ridge = Ridge(alpha = Lambda, normalize=True)
ridge.fit(X_train, y_train)
ridge_cofficients.append(ridge.coef_)
print(np.shape(ridge_cofficients))
# 绘制Lambda与回归系数的关系
# 中文乱码和坐标轴负号的处理
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
plt.rcParams['axes.unicode_minus'] = False
# 设置绘图风格
plt.style.use('ggplot')
plt.plot(Lambdas, ridge_cofficients)
# 对x轴作对数变换
plt.xscale('log')
# 设置折线图x轴和y轴标签
plt.xlabel('Lambda')
plt.ylabel('Cofficients')
# 图形显示
plt.show()

# 岭回归模型的交叉验证
# 设置交叉验证的参数,对于每一个Lambda值,都执行10重交叉验证
ridge_cv = RidgeCV(alphas = Lambdas, normalize=True, scoring='neg_mean_squared_error', cv = 10)
print(ridge_cv)
# 模型拟合
ridge_cv.fit(X_train, y_train)
# 返回最佳的lambda值
ridge_best_Lambda = ridge_cv.alpha_
print(ridge_best_Lambda)

# 导入第三方包中的函数
from sklearn.metrics import mean_squared_error

# 基于最佳的Lambda值建模
ridge = Ridge(alpha = ridge_best_Lambda, normalize=True)
ridge.fit(X_train, y_train)
# 返回岭回归系数
pd.Series(index = ['Intercept'] + X_train.columns.tolist(),data = [ridge.intercept_] + ridge.coef_.tolist())
# 预测
ridge_predict = ridge.predict(X_test)
# 预测效果验证
RMSE = np.sqrt(mean_squared_error(y_test,ridge_predict))
print(RMSE)

# 导入第三方模块中的函数
from sklearn.linear_model import Lasso,LassoCV

# 构造空列表,用于存储模型的偏回归系数
lasso_cofficients = []
for Lambda in Lambdas:
lasso = Lasso(alpha = Lambda, normalize=True, max_iter=10000)
lasso.fit(X_train, y_train)
lasso_cofficients.append(lasso.coef_)

# 绘制Lambda与回归系数的关系
plt.plot(Lambdas, lasso_cofficients)
# 对x轴作对数变换
plt.xscale('log')
# 设置折线图x轴和y轴标签
plt.xlabel('Lambda')
plt.ylabel('Cofficients')
# 显示图形
plt.show()

# LASSO回归模型的交叉验证
lasso_cv = LassoCV(alphas = Lambdas, normalize=True, cv = 10, max_iter=10000)
lasso_cv.fit(X_train, y_train)
# 输出最佳的lambda值
lasso_best_alpha = lasso_cv.alpha_
print(lasso_best_alpha)
# 基于最佳的lambda值建模
lasso = Lasso(alpha = lasso_best_alpha, normalize=True, max_iter=10000)
lasso.fit(X_train, y_train)
# 返回LASSO回归的系数
pd.Series(index = ['Intercept'] + X_train.columns.tolist(),data = [lasso.intercept_] + lasso.coef_.tolist())

# 预测
lasso_predict = lasso.predict(X_test)
# 预测效果验证
RMSE = np.sqrt(mean_squared_error(y_test,lasso_predict))
print(RMSE)

# 导入第三方模块
from statsmodels import api as sms

# 为自变量X添加常数列1,用于拟合截距项
X_train2 = sms.add_constant(X_train)
X_test2 = sms.add_constant(X_test)

# 构建多元线性回归模型
linear = sms.formula.OLS(y_train, X_train2).fit()
# 返回线性回归模型的系数
print(linear.params)

# 模型的预测
linear_predict = linear.predict(X_test2)
# 预测效果验证
RMSE = np.sqrt(mean_squared_error(y_test,linear_predict))
print(RMSE)

吴裕雄 数据挖掘与分析案例实战(7)——岭回归与LASSO回归模型的更多相关文章

  1. 吴裕雄 数据挖掘与分析案例实战(15)——DBSCAN与层次聚类分析

    # 导入第三方模块import pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as snsfr ...

  2. 吴裕雄 数据挖掘与分析案例实战(14)——Kmeans聚类分析

    # 导入第三方包import pandas as pdimport numpy as np import matplotlib.pyplot as pltfrom sklearn.cluster im ...

  3. 吴裕雄 数据挖掘与分析案例实战(13)——GBDT模型的应用

    # 导入第三方包import pandas as pdimport matplotlib.pyplot as plt # 读入数据default = pd.read_excel(r'F:\\pytho ...

  4. 吴裕雄 数据挖掘与分析案例实战(12)——SVM模型的应用

    import pandas as pd # 导入第三方模块from sklearn import svmfrom sklearn import model_selectionfrom sklearn ...

  5. 吴裕雄 数据挖掘与分析案例实战(10)——KNN模型的应用

    # 导入第三方包import pandas as pd # 导入数据Knowledge = pd.read_excel(r'F:\\python_Data_analysis_and_mining\\1 ...

  6. 吴裕雄 数据挖掘与分析案例实战(8)——Logistic回归分类模型

    import numpy as npimport pandas as pdimport matplotlib.pyplot as plt # 自定义绘制ks曲线的函数def plot_ks(y_tes ...

  7. 吴裕雄 数据挖掘与分析案例实战(5)——python数据可视化

    # 饼图的绘制# 导入第三方模块import matplotlibimport matplotlib.pyplot as plt plt.rcParams['font.sans-serif']=['S ...

  8. 吴裕雄 数据挖掘与分析案例实战(4)——python数据处理工具:Pandas

    # 导入模块import pandas as pdimport numpy as np # 构造序列gdp1 = pd.Series([2.8,3.01,8.99,8.59,5.18])print(g ...

  9. 吴裕雄 数据挖掘与分析案例实战(3)——python数值计算工具:Numpy

    # 导入模块,并重命名为npimport numpy as np# 单个列表创建一维数组arr1 = np.array([3,10,8,7,34,11,28,72])print('一维数组:\n',a ...

随机推荐

  1. 温习《PHP 核心技术与最佳实践》这本书

    再次看这本书,顺手提炼了一下大致目录,以便后续看见目录就知道大概讲的些什么内容 PHP 核心技术与最佳实践 1.面向对象思想的核心概念 1.1 面向对象的『形』与『本』 1.2 魔术方法的应用 1.2 ...

  2. 在C#客户端用HTTP上传文件到Java服务器

    在C#客户端用HTTP上传文件到Java服务器  来源:http://www.cnblogs.com/AndyDai/p/5135294.html 最近在做C / S 开发,需要在C#客户端上传文件到 ...

  3. js例子记载

    1.获取项目路径的,不一定有用,仅作参考用: function getRootPath() { var curWwwPath = window.document.location.href; //&q ...

  4. python selenium-4自动化测试模型

    1.线性测试 特点:每一个脚本都是完整且独立的,可以单独执行. 缺点:用例的开发与维护成本很高 2.模块化驱动测试 特点:把重复的操作独立成公共模块,提高测试用例的可维护性 示例:将搜索封装到func ...

  5. 数组比较大小的几种方法及math是方法

    call apply bind 的区别? 解决函数内this的指向: 1.可以在函数外提前声明变量 一般情况下我们用   var _this/that=this 2.通过apply和call来修改函数 ...

  6. 1036 Boys vs Girls (25 分)

    1036 Boys vs Girls (25 分) This time you are asked to tell the difference between the lowest grade of ...

  7. H-Index II @python

    Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimize ...

  8. [UE4]事件代理,无输出参数,蓝图中不需要绑定

    .h UFUNCTION(BlueprintImplementableEvent, meta=(DisplayName = "LoginSuccess")) void LoginS ...

  9. 可以ping通ip地址,但是访问80,或者8080报错

    这个是服务器的防火墙的原因,一般linux防火墙默认是打开的,并且只开放22端口,用于远程连接. 这个时候需要关闭防火墙,或者开放端口.

  10. 第12章 网络基础(1)_网络分层和TCP/IP协议族

    1. 协议的概念 (1)计算机网络中实现通信必须有一些约定.如对速率.传输代码.代码结构.传输控制步骤和出错控制等约定,这些约定即被称为通信协议 (2)在两个节点之间要成功地进行通信,两个节点之间必须 ...