码农知识堂 - 1000bd
  •   Python
  •   PHP
  •   JS/TS
  •   JAVA
  •   C/C++
  •   C#
  •   GO
  •   Kotlin
  •   Swift
  • 【机器学习】python机器学习使用scikit-learn对模型进行评估:使用t分布及z分布评估模型误差的95%置信空间


    端到端机器学习导航:
    【机器学习】python借助pandas加载并显示csv数据文件,并绘制直方图
    【机器学习】python使用matplotlib进行二维数据绘图并保存为png图片
    【机器学习】python借助pandas及scikit-learn使用三种方法分割训练集及测试集
    【机器学习】python借助pandas及matplotlib将输入数据可视化,并计算相关性
    【机器学习】python机器学习借助scikit-learn进行数据预处理工作:缺失值填补,文本处理(一)
    【机器学习】python机器学习scikit-learn和pandas进行Pipeline处理工作:归一化和标准化及自定义转换器(二)
    【机器学习】python机器学习使用scikit-learn评估模型:基于普通抽样及分层抽样的k折交叉验证做模型选择
    【机器学习】python机器学习使用scikit-learn对模型进行微调:使用GridSearchCV及RandomizedSearchCV
    【机器学习】python机器学习使用scikit-learn对模型进行评估:使用t分布及z分布评估模型误差的95%置信空间
    【机器学习】python机器学习使用scikit-learn对模型进行微调:RandomizedSearchCV的分布参数设置
    【机器学习】python机器学习使用scikit-learn对模型进行微调:按特征贡献大小保留最重要k个特征的transform
    【机器学习】python机器学习使用scikit-learn对模型进行微调:使用RandomizedSearchCV对pipline进行参数选择

    用z分布及t分布求置信区间:
    1、当整体标准差已知的时候,就不需要用样本标准差去估计总体标准差了。所以都用z检验。

    2、当总体标准差未知,需要估计,用t检验。当n>>30,z检验和t检验结果相近,以t检验为准。但是z检验比较好计算,就在大样本时替代t。

    数据准备:

    import os
    
    HOUSING_PATH = os.path.join("datasets", "housing")
    import pandas as pd
    
    def load_housing_data(housing_path=HOUSING_PATH):
        csv_path = os.path.join(housing_path, "housing.csv")
        return pd.read_csv(csv_path)
    housing=load_housing_data()
    housing2=housing.copy()
    import numpy as np
    
    #预处理前去掉带文字的指定列
    from sklearn.preprocessing import MinMaxScaler,StandardScaler,OneHotEncoder
    
    from sklearn.impute import SimpleImputer
    housing_num = housing2.drop("ocean_proximity", axis=1)
    from sklearn.preprocessing import StandardScaler
    from sklearn.pipeline import Pipeline
    num_pipeline = Pipeline([
            ('imputer', SimpleImputer(strategy="median")),
            ('std_scaler', StandardScaler())
        ])
    
    
    
    from sklearn.compose import ColumnTransformer
    #返回所有列名
    num_attribs = list(housing_num)
    
    cat_attribs = ["ocean_proximity"]
    #找出待独热编码列的最大分类数,不然在进行测试集划分处理时,
    #容易造成独热向量因测试集构成不同而列数不一致的情况
    categories=housing2['ocean_proximity'].unique()
    full_pipeline = ColumnTransformer([
            ("num", num_pipeline, num_attribs),
            ("cat", OneHotEncoder(categories=[categories]), cat_attribs),
        ])
    #抽样后的数据,去除预测目标列,并拿出对应目标列准备数据训练
    housing_labels = housing2["median_house_value"]
    
    housing_prepared = full_pipeline.fit_transform(housing2)
    from sklearn.model_selection import train_test_split
    train_set, test_set,train_sety, test_sety = train_test_split(housing_prepared,housing_labels, test_size=0.1, random_state=42)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44

    用随机森林预测及使用t分布及z分布计算误差的95%置信区间:

    from sklearn.metrics import mean_squared_error
    from sklearn.ensemble import RandomForestRegressor
    
    from sklearn.model_selection import RandomizedSearchCV
    from scipy.stats import randint
    
    forest_reg = RandomForestRegressor(random_state=200,n_estimators=10,max_features=12)
    #每个迭代探索一种参数组合
    forest_reg.fit(train_set, train_sety)
    pre=forest_reg.predict(test_set)
    print(np.sqrt(mean_squared_error(test_sety,pre)))
    from scipy import stats
    #用t分布计算误差95%的置信区间
    def tscore(y,pre,confidence = 0.95):
        confidence = 0.95
        squared_errors = (pre - y) ** 2
        return np.sqrt(stats.t.interval(confidence, len(squared_errors) - 1,
                                 loc=squared_errors.mean(),
                                 scale=stats.sem(squared_errors)))
    #有0.95的概率误差落在如下范围内:
    print(tscore(test_sety,pre,confidence = 0.95))
    #使用z分布计算
    def zscore(y,pre,confidence = 0.95):
        confidence = 0.95
        squared_errors = (pre - y) ** 2
        m = len(squared_errors)
        mean = squared_errors.mean()
        zscore = stats.norm.ppf((1 + confidence) / 2)
        zmargin = zscore * squared_errors.std(ddof=1) / np.sqrt(m)
        return [np.sqrt(mean - zmargin), np.sqrt(mean + zmargin)]
    print(zscore(test_sety,pre,confidence = 0.95))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

    输出结果:
    均方根误差:432.29251756337266
    t分数置信区间:[187.94412423 581.74792449]
    z分数置信区间:[188.18052438939552, 581.671498118216]

  • 相关阅读:
    (Vue+SpringBoot+elementUi+WangEditer)仿论坛项目
    通信下载模块 如何设计 芯片
    HTML视频背景(动态背景)
    『亚马逊云科技产品测评』活动征文|借助AWS EC2搭建服务器群组运维系统Zabbix+spug
    prometheus使用数据源的timestamp而非server的timestamp
    每日一题 416 分割等和子集(01背包)
    Posgresql数据库项目sql实操1
    vue - 解决vue : 无法加载文件 C:\Users\hp\AppData\Roaming\npm\vue.ps1,因为在此系统上禁
    MySQL关于日期函数的使用-笔记
    记录vue开发实例
  • 原文地址:https://blog.csdn.net/hh1357102/article/details/126357927
  • 最新文章
  • 攻防演习之三天拿下官网站群
    数据安全治理学习——前期安全规划和安全管理体系建设
    企业安全 | 企业内一次钓鱼演练准备过程
    内网渗透测试 | Kerberos协议及其部分攻击手法
    0day的产生 | 不懂代码的"代码审计"
    安装scrcpy-client模块av模块异常,环境问题解决方案
    leetcode hot100【LeetCode 279. 完全平方数】java实现
    OpenWrt下安装Mosquitto
    AnatoMask论文汇总
    【AI日记】24.11.01 LangChain、openai api和github copilot
  • 热门文章
  • 十款代码表白小特效 一个比一个浪漫 赶紧收藏起来吧!!!
    奉劝各位学弟学妹们,该打造你的技术影响力了!
    五年了,我在 CSDN 的两个一百万。
    Java俄罗斯方块,老程序员花了一个周末,连接中学年代!
    面试官都震惊,你这网络基础可以啊!
    你真的会用百度吗?我不信 — 那些不为人知的搜索引擎语法
    心情不好的时候,用 Python 画棵樱花树送给自己吧
    通宵一晚做出来的一款类似CS的第一人称射击游戏Demo!原来做游戏也不是很难,连憨憨学妹都学会了!
    13 万字 C 语言从入门到精通保姆级教程2021 年版
    10行代码集2000张美女图,Python爬虫120例,再上征途
Copyright © 2022 侵权请联系2656653265@qq.com    京ICP备2022015340号-1
正则表达式工具 cron表达式工具 密码生成工具

京公网安备 11010502049817号