【机器学习】python机器学习使用scikit-learn对模型进行评估:使用t分布及z分布评估模型误差的95%置信空间

36 篇文章 5 订阅
27 篇文章 3 订阅

端到端机器学习导航:
【机器学习】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)

用随机森林预测及使用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))

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

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

颢师傅

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

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

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

打赏作者

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

抵扣说明:

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

余额充值